package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.*;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.common.utils.UnionUtils;
import com.hai.config.UnionUserConfig;
import com.hai.entity.HighUser;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.HighUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

@Controller
@RequestMapping(value = "/user")
@Api(value = "用户共用接口")
public class HighUserCommonController {

    private static final Logger log = LoggerFactory.getLogger(WechatController.class);

    @Resource
    private HighUserService highUserService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UnionUserConfig unionUserConfig;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "登录接口【用户不存在会自动注册】")
    public ResponseData login(@RequestParam(value = "phone", required = true) String phone,
                              @RequestParam(value = "code", required = true) String code,
                              @RequestParam(value = "openId", required = false) String openId,
                              @RequestParam(value = "popularizeUserId", required = false) Long popularizeUserId,
                              @RequestParam(value = "regionId", required = false) String regionId,
                              HttpServletRequest request, HttpServletResponse response) {
        try {

            // 获取手机号验证码
            String phoneSmsCode = (String) redisUtil.get("SMS_"+phone);
            // 校验验证码
            if (StringUtils.isBlank(phoneSmsCode) || !Objects.equals(phoneSmsCode,code)) {
                log.error("HighUserController --> bindUserPhone() error!", "验证码错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");
            }
            redisUtil.del("SMS_"+phone);

            HighUser user = highUserService.findByPhone(phone);



            if(user == null) {
                user = new HighUser();
                user.setName("用户" + IDGenerator.nextId(5));
                user.setPhone(phone);
                user.setRegTime(new Date());
                user.setGold(0);
                user.setOpenIdH5(openId);
                user.setStatus(1);
                // 用户信息完整状态
                // 0：完整
                // 1：需要填写用户信息
                // 2：需要填写手机号
                user.setInfoCompleteStatus(1);

                highUserService.insertUser(user , popularizeUserId , regionId);
            } else {
                user.setOpenIdH5(openId);
                highUserService.updateUser(user);
            }

            HighUserModel highUserModel = new HighUserModel();
            HighUser detailData = highUserService.getDetailDataByUser(user.getId());
            detailData.setPassword(null);
            highUserModel.setHighUser(detailData);
            SessionObject so = new SessionObject(user.getPhone(), 1 , highUserModel);
            userCenter.save(request, response, so);
            return ResponseMsgUtil.success(so);
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/unionPhoneLogin", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "银联授权手机号登录接口")
    public ResponseData unionPhoneLogin(@RequestParam(value = "code", required = true) String code,
                                        @RequestParam(value = "popularizeUserId", required = false) Long popularizeUserId,
                                        @RequestParam(value = "regionId", required = false) String regionId,
                              HttpServletRequest request, HttpServletResponse response) {
        try {

            // 获取应用访问令牌
            String backendToken = unionUserConfig.getBackendToken();

            // 获取授权访问令牌
            JSONObject token = unionUserConfig.getAccessToken(backendToken, code);
            if (token == null || !token.getString("resp").equals("00")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, token.getString("msg"));
            }

            // 获取用户手机号
            JSONObject userMobile = unionUserConfig.getUserMobile(backendToken, token.getJSONObject("params").getString("accessToken"), token.getJSONObject("params").getString("openId"));
            if (userMobile == null || !userMobile.getString("resp").equals("00")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, userMobile.getString("msg"));
            }
            // 解密，获取手机号
            String mobile = UnionUtils.getDecryptedValue(userMobile.getJSONObject("params").getString("mobile"), unionUserConfig.getRsaKey());
            HighUser user = highUserService.findByPhone(mobile);
            if(user == null) {
                user = new HighUser();
                user.setName("用户" + IDGenerator.nextId(5));
                user.setPhone(mobile);
                user.setRegTime(new Date());
                user.setGold(0);
                user.setUnionOpenId(token.getJSONObject("params").getString("openId"));
                user.setUnionUnionId(token.getJSONObject("params").getString("unionId"));
                user.setStatus(1);
                // 用户信息完整状态
                // 0：完整
                // 1：需要填写用户信息
                // 2：需要填写手机号
                user.setInfoCompleteStatus(1);
                highUserService.insertUser(user , popularizeUserId , regionId);
            } else {
                user.setUnionOpenId(token.getJSONObject("params").getString("openId"));
                user.setUnionUnionId(token.getJSONObject("params").getString("unionId"));
                highUserService.updateUser(user);
            }

            HighUserModel highUserModel = new HighUserModel();
            HighUser detailData = highUserService.getDetailDataByUser(user.getId());
            detailData.setPassword(null);
            highUserModel.setHighUser(detailData);
            SessionObject so = new SessionObject(user.getPhone(), 1 , highUserModel);
            userCenter.save(request, response, so);
            return ResponseMsgUtil.success(so);
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "退出登录")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 用户信息
            HighUserModel sessionModel = userCenter.getSessionModel(HighUserModel.class);
            if (sessionModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到用户信息");
            }
            userCenter.remove(request, response);
            return ResponseMsgUtil.success("退出成功");
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

}


