package com.fs.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.fs.app.service.QwDataCallbackService;
import com.fs.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

@Api("企业微信产生会话回调事件测试接口")
@RestController
@RequestMapping
@Slf4j
public class QwTestController {
    @Autowired
    private QwDataCallbackService qwDataCallbackService;

    @PostMapping("/qw/callback/{corpId}")
    public AjaxResult handleCallback(@PathVariable String corpId,
                                     @RequestBody String requestBody,
                                     @RequestParam("msg_signature") String msg_signature,
                                     @RequestParam("timestamp") String timestamp,
                                     @RequestParam("nonce") String nonce) {
    return qwDataCallbackService.msgCallBack(corpId,requestBody,msg_signature,timestamp,nonce);
    }

    /**
     * 验证企业微信回调URL的有效性（接收企业微信发送的回调验证请求）
     * @param
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echoStr 回调验证字符串
     * @return 回调验证结果
     */
    @GetMapping("/qw/callback/{corpId}")
    public ResponseEntity<String> verifyCallback( @PathVariable String corpId,
                                                  @RequestParam("msg_signature") String msgSignature,
                                                  @RequestParam("timestamp") String timestamp,
                                                  @RequestParam("nonce") String nonce,
                                                  @RequestParam("echostr") String echoStr)  {
        try {
            String check = qwDataCallbackService.check(corpId,msgSignature, timestamp, nonce, echoStr);
            System.out.println("echostr:"+check);
            return ResponseEntity.ok(check); // 返回 echoStr，验证通过
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 解密企业微信的加密消息
     * @param encryptedData
     * @param encodingAesKey
     * @return
     * @throws Exception
     */
    private String decryptAES(String encryptedData, String encodingAesKey) throws Exception {
        // 1. Base64 解码 EncodingAESKey，获取 32 字节密钥
        byte[] keyBytes = Base64.getDecoder().decode(encodingAesKey + "="); // 企业微信的密钥可能缺 `=`
        System.out.println("EncodingAESKey 长度: " + encodingAesKey.length());
        // 2. 取前 32 字节作为 AES 密钥
        byte[] aesKey = Arrays.copyOfRange(keyBytes, 0, 32);

        // 3. 取前 16 字节作为 IV（初始化向量）
        byte[] ivBytes = Arrays.copyOfRange(aesKey, 0, 16);

        // 4. 创建 AES/CBC/PKCS7Padding 解密器（企业微信使用 PKCS7Padding）
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        // 5. 初始化解密模式
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);

        // 6. Base64 解码加密的数据
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);

        // 7. 解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 8. 返回解密后的字符串
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }


    public void processChatMessage(String jsonData) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonData);  // 使用 fastjson 解析
            String msgType = jsonObject.getString("msgtype");
            String fromUser = jsonObject.getString("from");
            String toUser = jsonObject.getString("to");
            String content = jsonObject.getString("content");

            System.out.println("消息类型：" + msgType);
            System.out.println("发送者：" + fromUser);
            System.out.println("接收者：" + toUser);
            System.out.println("内容：" + content);
        } catch (Exception e) {
            e.printStackTrace(); // 捕获解析异常
        }
    }






    /**
     * SHA1 签名计算
     * @param str 输入的字符串
     * @return 签名结果
     */
    /*private String sha1(String str) {
        try {
            Mac sha1 = Mac.getInstance("HmacSHA1");
            sha1.init(new SecretKeySpec(TOKEN.getBytes(), "HmacSHA1"));
            byte[] hash = sha1.doFinal(str.getBytes());
            return bytesToHex(hash);
        } catch (Exception e) {
            throw new RuntimeException("SHA1 signature generation failed", e);
        }
    }*/

    /**
     * 将字节数组转换为十六进制字符串
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     * 校验签名
     * @param msgSignature 签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param
     * @return 校验结果
     */
    /*private boolean validateSignature(String msgSignature, String timestamp, String nonce, String check) {
        // 签名生成规则：先对 token, timestamp, nonce 进行字典排序，再拼接并进行 SHA1 签名计算
        String[] array = new String[]{TOKEN, timestamp, nonce,check};
        Arrays.sort(array);
        String combined = array[0] + array[1] + array[2]+array[3];
        String calculatedSignature = sha1(combined);

        // 比较企业微信返回的 msg_signature 和我们计算出来的签名
        return calculatedSignature.equals(msgSignature);
    }*/

     /*private String gerMsg(String sReqMsgSig ,String sReqTimeStamp,String sReqNonce,String sReqData) throws AesException {
        WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, S_CORP_ID);

    }*/

    // 计算 msg_signature
    /*public static String calculateMsgSignature(String timestamp, String nonce, String encryptedMessage) {
        try {
            // 1. 拼接 token、timestamp、nonce 和 encryptedMessage
            String[] array = new String[]{TOKEN, timestamp, nonce, encryptedMessage};
            Arrays.sort(array);  // 按字典排序

            // 2. 拼接排序后的字符串
            StringBuilder sb = new StringBuilder();
            for (String str : array) {
                sb.append(str);
            }

            // 3. 使用 SHA1 进行加密
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(sb.toString().getBytes("UTF-8"));

            // 4. 将结果转为 16 进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }*/

    /*public static void main(String[] args) throws com.fs.app.util.AesException {
        // 假设的加密数据（这是一个示例，实际情况中你需要替换成收到的加密数据）
        String encryptedMessage = "4dPA6z4AAkVm3/+/PfVPQdclKzbNnGaRk+nrr8lhLAHZQuQtvIF5YUkO+Xgn+VlU7hoNbgom1nBucIp+4c4IWCFaoMjqRVS6GOAInTzbNdnGVdC5rNS/Phyl+ZDgNibCm/Ipj9Jw+lIPgadh8tpvLa8t0uUjynQ11PhuxwVCgo70dTiJ8HcDBYqZgAEqMBdFN1x7vn0lbTN4zhgeK+LUE1nK3tduWAqZih/q7/9ava0SKFUIk4IRVP/B8b49auWyvbVpBW7Ec6st5YzYRVsXFdtU6iSJZJlyHOiCyxbWVbOmwf02ZB6JMqVtExerGLECcYqFXc/QF7uROXKB3URygV1AMWM75eS/THeotqBkjy8S1hRVCjRIyAOUsLTkbzj3fv3l7szSTDkMo/FrHHJfvknC5x279nWNqDbTs8Q2e+bxHgc+TOmZGMShJeHyLZa4cbexdhwIJskRBzDCK2MkSg==";  // 替换成你收到的加密消息
        String sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[这是一个测试]]></Content><MsgId>1234567890123456</MsgId><AgentID>ww51717e2b71d5e2d3</AgentID></xml>";
        String timestamp = "1409659813";  // 替换成你收到的时间戳
        String nonce = "1372623149";  // 替换成你收到的随机字符串
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(TOKEN, ENCODING_AES_KEY, S_CORP_ID);
        // 计算 msg_signature
        //String msgSignature = wxcpt.EncryptMsg(sRespData,timestamp, nonce);
        String s = calculateMsgSignature(timestamp, nonce, encryptedMessage);
        System.out.println("msg_signature"+s);
        //System.out.println("encryptedMessage: " + msgSignature);
    }*/
}
