package com.qiankun.controller.mdp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
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.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();
    }

    @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());
            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());
                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);
    }

}
