package com.qiankun.controller.mdp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.qiankun.annotation.Auth;
import com.qiankun.config.WxMaConfiguration;
import com.qiankun.config.WxMaProperties;
import com.qiankun.entity.User;
import com.qiankun.service.UserService;
import com.qiankun.utils.JwtTokenUtil;
import com.qiankun.utils.UserUtils;
import com.qiankun.vo.DecryptedDataVo;
import com.qiankun.vo.PaperIdLoginVo;
import com.qiankun.vo.UserVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.ResourceBundle;

@RestController
@RequestMapping("/wx/mdp")
public class MdpController {
    private final Logger logger = LoggerFactory.getLogger(MdpController.class);
    @Autowired
    private JwtTokenUtil tokenUtil;
    @Autowired
    private WxMaProperties propertis;
    @Autowired
    private UserService userService;
    private ResourceBundle rb = ResourceBundle.getBundle("system");
    private String getAppid(){
        return propertis.getConfigs().get(1).getAppid();
    }
    private Map<String,String> wxSessionKeyCache = Maps.newConcurrentMap();

    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public Map<String,Object> login(@RequestParam String code) throws Exception {
        if (StringUtils.isBlank(code)) {
            return null;
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(getAppid());

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            wxSessionKeyCache.put(session.getOpenid(),session.getSessionKey());
            Map<String,Object> result = Maps.newConcurrentMap();

            User userInfo = userService.findByOpenid(session.getOpenid());
            if (userInfo != null){
                String sKey = tokenUtil.generateToken(userInfo.getOpenid());
                result.put("sKey",sKey);
                result.put("userInfo", UserUtils.converToVo(userInfo));
            }else {
                result.put("sKey","");
                result.put("userInfo","");
                result.put("openid",session.getOpenid());
            }

            return result;
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage(),e);
        }
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value ="/loginByPaperId",method = RequestMethod.POST)
    public Map<String,Object> loginByPaperId(@RequestBody PaperIdLoginVo vo){
        User user = userService.findByPaperId(vo.getPaperId(),vo.getPaperType());
        Map<String,Object> result = Maps.newConcurrentMap();
        if (user == null){
            //新用户
            result.put("isExist",false);
        }else {
            //老用户
            if (!user.getName().equals(vo.getName())){
                result.put("errorMsg","姓名与库中信息不符，请核实后重新提交");
            }else {
                user.setOpenid(vo.getOpenid());
                if (!Strings.isNullOrEmpty(vo.getPhone())){
                    //更新微信绑定的手机号
                    user.setMobile(vo.getPhone());
                }
                userService.save(user);
                result.put("sKey",tokenUtil.generateToken(user.getOpenid()));
                result.put("userInfo",UserUtils.converToVo(user));
            }
            result.put("isExist",true);
        }
        return result;
    }

    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public UserVo getUserInfo(@RequestHeader String sKey){
        if (Strings.isNullOrEmpty(sKey)){
            throw new IllegalArgumentException("请求参数错误");
        }
        String openid = tokenUtil.getUsernameFromToken(sKey);
        User user = userService.findByOpenid(openid);
        return UserUtils.converToVo(user);
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/decryptedData",method = RequestMethod.POST)
    public Map<String,Object> decryptedData(@RequestBody DecryptedDataVo dataVo){
        Map<String,Object> result = Maps.newConcurrentMap();
        final WxMaService wxService = WxMaConfiguration.getMaService(getAppid());
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(dataVo.getCode());
            WxMaUserService wxUserService = wxService.getUserService();
            WxMaPhoneNumberInfo phoneInfo = wxUserService.getPhoneNoInfo(session.getSessionKey(),dataVo.getEncryptedData(),dataVo.getIv());
            result.put("status","ok");
            result.put("phoneInfo",phoneInfo);
        } catch (WxErrorException e) {
            result.put("status","error");
            result.put("errorMsg","微信登陆失败");
        }
        return result;
    }

}
