package com.kmall.api.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kmall.api.annotation.LoginUser;
import com.kmall.api.dto.SendMsgVo;
import com.kmall.api.entity.FullUserInfo;
import com.kmall.api.entity.UserInfo;
import com.kmall.api.service.TokenService;
import com.kmall.api.util.ApiUserUtils;
import com.kmall.api.util.CommonUtil;
import com.kmall.manager.entity.SysSmsLogEntity;
import com.kmall.manager.service.SysSmsLogService;
import com.kmall.api.util.SendMsgUtil;
import com.kmall.api.entity.UserVo;
import com.kmall.api.service.ApiUserService;
import com.kmall.api.util.ApiBaseAction;
import com.qiniu.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
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;
    @Autowired
    private TokenService tokenService;

    /**
     */
    /*@IgnoreAuth
    @GetMapping("info")
    public Object info(String mobile) {
        Map param = Maps.newHashMap();
        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 = "【中网小程序】亲爱的亲，您的验证码是"+sms_code+"。有效期为5分钟，请尽快验证";

        logger.info(msgContent);
        // 一分钟之内不能重复发送短信
        SysSmsLogEntity smsLogVo = smsLogService.querySmsCodeByMobile(phone);
        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);

            SysSmsLogEntity smsLog = new SysSmsLogEntity();
            if(loginUser != null){
                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());
                smsLog.setMerchSn(getMerchSn());
                smsLog.setStoreId(getStoreId().intValue());

                SysSmsLogEntity sysSmsLogEntity = smsLogService.sendSms(smsLog);
                if (null == sysSmsLogEntity) {
                    return toResponsFail("短信记录失败");
                } else {
                    return toResponsSuccess("短信发送成功");
                }
            }else{
                smsLog.setSendStatus(0);
                smsLog.setReturnMsg(vo.getMsg());
                smsLog.setStoreId(getStoreId().intValue());
                smsLog.setMerchSn(getMerchSn());
                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);
    }

    public static String filterEmoji(String source) {
        if (source != null && source.length() > 0) {
            return source.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "");
        } else {
            return source;
        }
    }
    /**
     * 手机号登陆
     */
    @PostMapping("userLogin")
    public Object userLogin(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String openId = jsonParam.getString("openId");
        String phone = jsonParam.getString("phone");
        String smscode = jsonParam.getString("smscode");
        Long storeId = jsonParam.getLong("storeId");
        String merchSn = jsonParam.getString("merchSn");
        FullUserInfo fullUserInfo = null;
        if (null != jsonParam.get("userInfo")) {
            fullUserInfo = jsonParam.getObject("userInfo", FullUserInfo.class);
        }
        UserInfo userInfo = fullUserInfo.getUserInfo();
        if(userInfo == null){
            return toResponsFail("登录失败");
        }
        if (StringUtils.isNullOrEmpty(openId)) {
            return toResponsFail("登录失败");
        }

        UserVo userVoByOpenId = userService.queryByOpenId(openId);
        if(userVoByOpenId == null){
            userInfo.setNickName(filterEmoji(userInfo.getNickName()));;
            Date nowTime = new Date();
            UserVo saveUserVo = new UserVo();
            saveUserVo.setPassword(openId);
            saveUserVo.setRegister_time(nowTime);
            saveUserVo.setRegister_ip(this.getClientIp());
            saveUserVo.setLast_login_ip(saveUserVo.getRegister_ip());
            saveUserVo.setLast_login_time(saveUserVo.getRegister_time());
            saveUserVo.setWeixin_openid(openId);
            saveUserVo.setAvatar(userInfo.getAvatarUrl());
            saveUserVo.setGender(userInfo.getGender()); // //性别 0：未知、1：男、2：女
            saveUserVo.setNickname(userInfo.getNickName());
            saveUserVo.setUser_level_id(1);
            userService.save(saveUserVo);
            userVoByOpenId = userService.queryByOpenId(openId);
        }
        // 校验短信码
        SysSmsLogEntity smsLogVo = smsLogService.querySmsCodeByMobile(phone);
        if (null != smsLogVo) {
            if(!smsLogVo.getSmsCode().equals(smscode) || smsLogVo.getSendStatus() == 0){
                return toResponsFail("短信验证码错误");
            }
        }else{
            return toResponsFail("短信验证码错误");
        }
        if(userVoByOpenId != null){
            if(com.kmall.common.utils.StringUtils.isNotEmpty(userVoByOpenId.getMobile())){//openid绑定的用户信息已绑定手机号
                if(!phone.equalsIgnoreCase(userVoByOpenId.getMobile())){
                    return toResponsWxLoginFail("当前微信授权绑定的手机号为"+userVoByOpenId.getMobile()+"，与当前用户登录的手机号不一致，是否更新为当前登录手机号"+phone);
                }
            }else {//当前openid未绑定手机号，查询当前登录手机号是否有绑定其他账号
                //根据手机号查询用户信息
                List<UserVo> userVoList = userService.queryByMobile(phone);
                if(userVoList.size() == 0){//未绑定任何微信账号，则提示让用户注册（暂时没有注册，直接绑定）
                    UserVo userVo = new UserVo();
                    userVo.setId(userVoByOpenId.getId());
                    userVo.setMobile(phone);
                    userService.update(userVo);
//                    return toResponsFail("当前登录手机号用户暂未绑定当前授权微信用户，是否绑定？");
                }else{
                    UserVo userVo = userVoList.get(0);
                    //手机号绑定的用户微信openid，是否与当前授权的openid一致
                    if(!userVo.getWeixin_openid().equalsIgnoreCase(openId)){
                        return toResponsFail("当前登录手机号已绑定其他微信用户，请重新输入登录手机号");
                    }

                }
            }
        }

        Map<String, Object> tokenMap = tokenService.createAndUpdateToken(openId, storeId, userVoByOpenId.getId(), merchSn, "false");
        String token = MapUtils.getString(tokenMap, "token");

        if (null == userInfo || StringUtils.isNullOrEmpty(token)) {
            return toResponsFail("登录失败");
        }
        Map<String, Object> resultObj = Maps.newHashMap();
        resultObj.put("token", token);
        resultObj.put("userInfo", userInfo);
        resultObj.put("userId", userVoByOpenId.getId());
        return toResponsSuccess(resultObj);
    }

    @PostMapping("userLoginMobileUpdate")
    public Object userLoginMobileUpdate(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String openId = jsonParam.getString("openId");
        String phone = jsonParam.getString("phone");
        Long storeId = jsonParam.getLong("storeId");
        String merchSn = jsonParam.getString("merchSn");
        FullUserInfo fullUserInfo = null;
        if (null != jsonParam.get("userInfo")) {
            fullUserInfo = jsonParam.getObject("userInfo", FullUserInfo.class);
        }
        UserInfo userInfo = fullUserInfo.getUserInfo();
        if(userInfo == null){
            return toResponsFail("登录失败");
        }
        if (StringUtils.isNullOrEmpty(openId)) {
            return toResponsFail("登录失败");
        }
        UserVo userVoByOpenId = userService.queryByOpenId(openId);
        if(userVoByOpenId != null){
            UserVo userVo = new UserVo();
            userVo.setId(userVoByOpenId.getId());
            userVo.setMobile(phone);
            userService.update(userVo);
        }else{
            return toResponsFail("绑定失败");
        }
        Map<String, Object> tokenMap = tokenService.createAndUpdateToken(openId, storeId, userVoByOpenId.getId(), merchSn, "false");
        String token = MapUtils.getString(tokenMap, "token");

        if (null == userInfo || StringUtils.isNullOrEmpty(token)) {
            return toResponsFail("登录失败");
        }
        Map<String, Object> resultObj = Maps.newHashMap();
        resultObj.put("token", token);
        resultObj.put("userInfo", userInfo);
        resultObj.put("userId", userVoByOpenId.getId());
        return toResponsSuccess(resultObj);
    }

    /**
     * 注册用户，手机号、验证码
     * @param loginUser
     * @return
     */
    @PostMapping("registUser")
    public Object registUser(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        //
        String phone = jsonParam.getString("phone");
        String smscode = jsonParam.getString("smscode");
        List<UserVo> userVoList = userService.queryByMobile(phone);
        if(userVoList.size() == 0){
            return toResponsFail("该手机号用户不存在");
        }
        UserVo userVo = userVoList.get(0);
        // 校验短信码
        SysSmsLogEntity smsLogVo = smsLogService.querySmsCodeByMobile(phone);
        if (null != smsLogVo) {
            if(!smsLogVo.getSmsCode().equals(smscode) || smsLogVo.getSendStatus() == 0){
                return toResponsFail("短信验证码错误");
            }
        }
//        Map<String, Object> tokenMap = tokenService.createAndUpdateToken(userVo.getWeixin_openid(), storeId, getUserId(), merchSn, "false");
        return toResponsSuccess("注册成功");
    }

    /**
     * 根据用户id判断上次活体人脸核身时间是否在可调用范围内（待小程序开放人脸识别类目）
     * @param loginUser
     * @return
     */
    @PostMapping("checkFaceTimeByUserId")
    public Object checkFaceTimeByUserId(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Long userId = jsonParam.getLong("userId");
        Long storeId = jsonParam.getLong("storeId");
        Boolean isCheck = userService.checkFaceTimeByUserId(userId,storeId);
        return toResponsSuccess(isCheck);
    }
}
