package com.heyu.api.controller.vv;


import com.heyu.api.data.utils.WeChatCallbackUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/app/weixin/customer")
public class AppWeiXinCustomerNotifyController {



    public static String token = "9Iosbni8qAU8Kcmy8tgRLw";


    public static String encodingAESKey = "miBhTSRiwCgn9aYoa8d1TDu62GYFV2aE03vXl2Rrgv6";


    /**
     * 验证回调 URL (GET 请求)
     */
    // https://api.1024api.com/api-interface/app/weixin/customer/verify?msg_signature=5392430904602161909&timestamp=1737681600&nonce=1234567890&echostr=1234567890

    // https://api.1024api.com/api-interface/app/weixin/customer/verify

    @GetMapping("/verify")
    public String verify(@RequestParam("msg_signature") String msgSignature,
                         @RequestParam("timestamp") String timestamp,
                         @RequestParam("nonce") String nonce,
                         @RequestParam("echostr") String echostr) {
        try {
            // 验证并解密
            String result = WeChatCallbackUtil.verifyURL(
                    token, timestamp, nonce, msgSignature, echostr, encodingAESKey
            );
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "验证失败";
        }
    }




    /**
     * 接收回调消息 (POST 请求)
     */
    // /app/weixin/customer/receiveMessage
    @PostMapping("/receiveMessage")
    public String receiveMessage(@RequestParam("msg_signature") String msgSignature,
                                 @RequestParam("timestamp") String timestamp,
                                 @RequestParam("nonce") String nonce,
                                 HttpServletRequest request)  {
        try {
            // 读取请求体
            String encryptedMessage = getRequestBody(request);

            // 验证签名
            if (!verifySignature(msgSignature, timestamp, nonce, encryptedMessage)) {
                return "签名验证失败";
            }

            // 解密消息
            String decryptedMessage = WeChatCallbackUtil.decrypt(
                    encryptedMessage, encodingAESKey
            );

            // 解析 XML 消息
            // TODO: 解析消息内容并处理

            // 返回成功响应
            return "success";

        } catch (Exception e) {
            e.printStackTrace();
            return "处理失败";
        }
    }

    /**
     * 验证签名
     */
    private boolean verifySignature(String msgSignature, String timestamp,
                                    String nonce, String encryptedMessage) {
        try {
            String signature = WeChatCallbackUtil.generateSignature(
                    token, timestamp, nonce, encryptedMessage
            );
            return signature.equals(msgSignature);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取请求体内容
     */
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (java.io.BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
}

