package bus.controller.biz;

import bus.model.RedisUtil;
import bus.model.dto.req.WxLoginReq;
import bus.model.vo.WXDecrypt;
import bus.model.vo.WxEncryptedData;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageSerializable;
import bus.model.dto.WChatUserDto;
import bus.model.dto.page.WChatUserPageDto;
import bus.model.vo.WChatUserVo;
import bus.service.WChatUserService;
import com.orcas.common.model.JsonResponse;
import com.orcas.common.sso.model.SsoUserAuthDto;
import com.qzwisdom.qzframework.core.tool.exception.BusinessException;
import com.sun.jndi.toolkit.url.UrlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.qzwisdom.qzframework.core.tool.base.controller.BaseController;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.AlgorithmParameters;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Program: bus
 * @Description: 描述
 * @Author: zy
 * @Date: 2025-02-28 16:46:43
 **/
@Slf4j
@CrossOrigin
@RestController
@Api(tags = "微信用户接口")
@RequestMapping(value="/wChatUser")
public class WChatUserController implements BaseController {

    @Autowired
    private WChatUserService wChatUserService;

   // private static final String appId = "wx93b327996c5a3839";
    private static final String appId = "wxf562a20ee4297f2d";

   // private static final String appSecret = "491d369f6ca0bc6b9b49ec2e61c3ef4b";
    private static final String appSecret = "ef150b4d2fe3f11d748f21d67823bae9";
    private static  final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final int TIME_OUT  = 3000;

    private static final String ERROR_CODE_STR = "errcode";





    @RequestMapping(value = "/auto/login", method = RequestMethod.POST)
    @ApiOperation(value = "小程序登陆调用")
    public SsoUserAuthDto wxLogin(HttpServletRequest request, HttpServletResponse response,
                                  @RequestBody WxLoginReq wxLoginReq){
        SsoUserAuthDto ssoUserAuthDto = wChatUserService.wxLogin(request, response, wxLoginReq);
        return ssoUserAuthDto;
    }

    @RequestMapping(value = "/getXcxOpenId", method = RequestMethod.GET)
    @ApiOperation(value = "微信小程序获取OpenId")
    public Map<String,String> getXcxOpenId(@RequestParam(required = true) String code){
        if(StrUtil.isBlank(code)){
            throw new BusinessException("code不能为空");
        }
        String params = "" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        String json = HttpUtil.get(OPENID_URL+params, TIME_OUT);
        if(StrUtil.isBlank(json)){
            throw new BusinessException("无法获取微信登录状态:JSON获取失败");
        }
        JSONObject jsonObj = new JSONObject(json);
        if(jsonObj.get(ERROR_CODE_STR)!=null && jsonObj.get(ERROR_CODE_STR,Integer.class)!=0){
            throw new BusinessException("小程序登录失败");
        }
        Map<String,String> map = new HashMap<>();
        String openId = (String)jsonObj.get("openid");
        String sessionKey = (String)jsonObj.get("session_key");
        Object unionId = jsonObj.get("unionid");
        map.put("openId",openId);
        map.put("sessionKey",sessionKey);
        map.put("unionId",unionId!=null?String.valueOf(unionId):"");
        return map;
    }

    @RequestMapping(value = "/getPhoneNumber", method = RequestMethod.POST)
    @ApiOperation(value = "新板本-获取微信小程序手机号")
    public String getPhoneNumber(@RequestParam(required = true) String code) {
        if (StrUtil.isBlank(code)) {
            throw new BusinessException("code不能为空");
        }

        String accessToken = wChatUserService.getAccessToken(appId,appSecret);
        String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber" +
                "?access_token=" + accessToken;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        String phoneJson = HttpUtil.post(phoneUrl, JSON.toJSONString(paramMap));

        JSONObject phoneObj = new JSONObject(phoneJson);
        if (phoneObj.get(ERROR_CODE_STR) != null && phoneObj.get(ERROR_CODE_STR, Integer.class) != 0) {
             throw new BusinessException("获取手机号失败:"+phoneJson);
        }
        return phoneJson;
    }

    @ApiOperation(value = "老板本-解密获取手机号")
    @RequestMapping(value = "/encryptedData", method = RequestMethod.POST)
    @ResponseBody
    public WXDecrypt encryptedData(@RequestBody WxEncryptedData wxEncryptedData) throws Exception {
        // 第一个，加密数据串（String）；
        // 第二个，session_key需要通过微信小程序的code获得（String）；
        // 第三个，数据加密时所使用的偏移量，解密时需要使用（String）；第四个，编码
        String encryptedData = wxEncryptedData.getEncryptedData();
        String sessionKey = wxEncryptedData.getSessionKey();
        String iv = wxEncryptedData.getIv();

        String result = decrypt(encryptedData, sessionKey, iv, "UTF-8");

        if (null != result && result.length() > 0) {
            // 将解密后的JSON格式字符串转化为对象
            WXDecrypt wxDecrypt = JSONUtil.toBean(result, WXDecrypt.class);
            return wxDecrypt;
        } else {
            return null;
        }
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @ApiOperation("详情")
    @GetMapping(value = "getDetailById")
    public WChatUserVo getDetailById(@RequestParam String id){
        return doSingle(wChatUserService.getDetailById(id),WChatUserVo::new);
    }



    /**
    * 列表
    * @param dto
    * @return
    */
    @ApiOperation("列表")
    @PostMapping(value = "list")
    public PageSerializable<WChatUserDto> list(@RequestBody WChatUserPageDto dto){
       PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
       return new PageSerializable<>(wChatUserService.list(dto));
    }

	/**
     * 删除
     * @param id
     * @return
     */
//    @ApiOperation("删除")
//    @GetMapping(value = "deleteById")
//    public String deleteById(@RequestParam String id){
//		wChatUserService.delete(id);
//        return "删除成功";
//    }

    /**
     * 解密
     * @param data
     * @param key
     * @param iv
     * @param encodingFormat
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, encodingFormat);
                return result;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
