package com.kiisoo.ic.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.base.entity.BasicConfigDO;
import com.kiisoo.ic.base.mapper.BasicConfigDOMapper;
import com.kiisoo.ic.common.BaseController;
import com.kiisoo.ic.common.utils.httpClientUtil.HttpClientUtil;
import com.kiisoo.ic.common.utils.httpClientUtil.HttpResult;
import com.kiisoo.ic.wx.service.QWMailListManageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import org.springframework.beans.factory.annotation.Autowired;
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.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController extends BaseController {


    @Autowired
    private BasicConfigDOMapper basicConfigDOMapper;
    @Autowired
    private QWMailListManageService qwMailListManageService;


    @RequestMapping("/openId")
    @ResponseBody
    public Map<String, Object> openId(String code) { // 小程序端获取的CODE
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        try {
            QueryWrapper<BasicConfigDO> baseParams1 = new QueryWrapper<>();
            baseParams1.eq("code", "MINIPROGRAM_CONF");
            baseParams1.eq("conf_key", "APPID");
            BasicConfigDO basicConfigDO1 = basicConfigDOMapper.selectOne(baseParams1);
            QueryWrapper<BasicConfigDO> baseParams2 = new QueryWrapper<>();
            baseParams2.eq("code", "MINIPROGRAM_CONF");
            baseParams2.eq("conf_key", "SECRET");
            BasicConfigDO basicConfigDO2 = basicConfigDOMapper.selectOne(baseParams2);


            boolean check = (StringUtils.isEmpty(code)) ? true : false;
            if (check) {
                throw new Exception("参数异常");
            }
            StringBuilder urlPath = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session"); // 微信提供的API，这里最好也放在配置文件
            urlPath.append(String.format("?appid=%s", basicConfigDO1.getConfValue()));
            urlPath.append(String.format("&secret=%s", basicConfigDO2.getConfValue()));
            urlPath.append(String.format("&js_code=%s", code));
            urlPath.append(String.format("&grant_type=%s", "authorization_code")); // 固定值

            HttpResult data = HttpClientUtil.httpGet(urlPath.toString());
            //http返回参数
            if (data.getCode() == 200) {
                if(data.getMessage().contains("errcode")){
                    // sessionkey已过期
                    return fail("0012");
                }
                String openid = JSONObject.parseObject(data.getMessage()).get("openid").toString();
                String sessionKey = JSONObject.parseObject(data.getMessage()).get("session_key").toString();

                String unionid = "";
                if (JSONObject.parseObject(data.getMessage()).get("unionid") != null) {
                    unionid = JSONObject.parseObject(data.getMessage()).get("unionid").toString();
                }


                result.put("openId", openid);
                result.put("sessionKey", sessionKey);
                result.put("unionid", unionid);
            }
            return data(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fail();
    }


    @RequestMapping("/code2Session")
    @ResponseBody
    public Map<String, Object> qwcode2Session(String code) { // 小程序端获取的CODE
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        try {
            boolean check = (StringUtils.isEmpty(code)) ? true : false;
            if (check) {
                throw new Exception("参数异常");
            }

            Map<String, String> codeInfo = qwMailListManageService.getCpUserIdByCode(code);

            return data(codeInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fail();
    }

    /**
     * 解密并且获取用户手机号码
     *
     * @param encrypdata
     * @param ivdata
     * @param sessionkey
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "encode", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object>  deciphering(@RequestParam("encrypdata") String encrypdata, @RequestParam("ivdata") String ivdata, @RequestParam("sessionkey")String sessionkey) {

        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String str = "";
        try {
            str = decrypt(sessionKey, ivData, encrypData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("phone", str);
        return data(map);

    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串  
        return new String(cipher.doFinal(encData), "UTF-8");
    }
}
