package com.kmall.api.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.kmall.api.annotation.IgnoreAuth;
import com.kmall.api.annotation.LoginUser;
import com.kmall.api.dto.SendMsgVo;
import com.kmall.api.util.SendMsgUtil;
import com.kmall.common.entity.SysSmsLogEntity;
import com.kmall.api.entity.UserVo;
import com.kmall.api.service.ApiUserService;
import com.kmall.common.service.SysSmsLogService;
import com.kmall.api.util.ApiBaseAction;
import com.kmall.common.utils.CharUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 作者: @author Scott <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    protected Logger log = Logger.getLogger(ApiUserController.class);
    @Autowired
    private ApiUserService userService;
    @Autowired
    private SysSmsLogService smsLogService;

    /**
     */
    @IgnoreAuth
    @GetMapping("info")
    public Object info(String mobile) {
        Map param = new HashMap();
        param.put("mobile", mobile);
        UserVo user = userService.queryByMobile(mobile);
        user.setPassword("");
        return user;
    }

    /**
     * 发送短信
     */
    @PostMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String sms_code = SendMsgUtil.createRandomVcode();
        String phone = jsonParams.getString("phone");
//        String msgContent = "【前海电商】手机验证码为："+sms_code;
        String msgContent = "【中网小程序】亲爱的"+loginUser.getNickname()+"，您的验证码是"+sms_code+"。有效期为5分钟，请尽快验证";

        System.out.println("msgContent:"+msgContent);
        // 一分钟之内不能重复发送短信
        SysSmsLogEntity smsLogVo = smsLogService.querySmsCodeByUserId(loginUser.getId());
        if (null != smsLogVo && (System.currentTimeMillis() - smsLogVo.getStime().getTime()) / 1000 < 1 * 60) {
            return toResponsFail("短信已发送");
        }

        try{
            //发送验证码到手机
            String result = SendMsgUtil.sendMsg(phone,msgContent);
            SendMsgVo vo = JSON.parseObject(result,SendMsgVo.class);
            System.out.println(result);

            SysSmsLogEntity smsLog = new SysSmsLogEntity();
            smsLog.setUserId(loginUser.getId());
            smsLog.setMobile(phone);
            smsLog.setContent(msgContent);
            smsLog.setSmsCode(sms_code);
            if(vo.getCode().equalsIgnoreCase("0")){
                smsLog.setSendStatus(1);
                smsLog.setSendId(vo.getSid());
                smsLog.setReturnMsg(vo.getMsg());

                SysSmsLogEntity sysSmsLogEntity = smsLogService.sendSms(smsLog);
                if (null == sysSmsLogEntity) {
                    return toResponsFail("短信记录失败");
                } else {
                    return toResponsSuccess("短信发送成功");
                }
            }else{
                smsLog.setSendStatus(0);
                smsLog.setReturnMsg(vo.getMsg());
                smsLogService.sendSms(smsLog);
                return toResponsFail("短信发送失败："+vo.getMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            return toResponsFail("短信发送失败");
        }

    }

    /**
     * 获取当前会员等级
     *
     * @return
     */
    @PostMapping("getCurUser")
    public Object getUserLevel() {
        Long userId = getUserId();
        UserVo userInfo = userService.queryObject(userId);
        String userLevel = userService.getUserLevel(userInfo);
        userInfo.setUserLevel(userLevel);
        return toResponsSuccess(userInfo);
    }
}