package cn.iocoder.yudao.module.system.controller.admin.wx;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.service.wx.WechatBusinessService;
import cn.iocoder.yudao.module.system.util.WechatUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

import static cn.iocoder.yudao.module.system.util.WechatUtils.getRequestBody;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class WeChatMessageController {

    private final String TOKEN = "c0e8bd5a238af15dc0f9b229560b163b"; // 配置的Token


    @Autowired
    private WechatBusinessService wechatBusinessService;

    /**
     * 验证微信服务器（GET请求）
     * 用于首次配置服务器URL时验证
     */
    @GetMapping("/mp/callback")
    @PermitAll
    public String verifyServer(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) {

        log.info("微信服务器验证请求：signature={}, timestamp={}, nonce={}, echostr={}",
                signature, timestamp, nonce, echostr);

        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }

        // 3. 将加密后的字符串与signature对比
        String encrypted = WechatUtils.sha1(content.toString());

        if (encrypted != null && encrypted.equals(signature)) {
            log.info("微信服务器验证成功");
            return echostr; // 验证成功返回echostr
        } else {
            log.error("微信服务器验证失败");
            return "error";
        }
    }

    @PostMapping("/mp/callback")
    @PermitAll
    public String receiveMessage(
            HttpServletRequest request,
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "openid", required = false) String openid,
            @RequestParam(value = "encrypt_type", required = false) String encryptType,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {

        try {
            // 获取请求体中的XML数据
            String requestBody = getRequestBody(request);
            log.info("接收到的微信公众号消息：{}", requestBody);

            // 验证消息签名（安全模式需要）
            if (signature != null && !signature.isEmpty()) {
                if (!WechatUtils.checkSignature(TOKEN, timestamp, nonce, signature)) {
                    log.info("微信公众号消息签名验证失败");
                    return "error";
                }
            }

            String eventType = WechatUtils.parseEventType(requestBody);

            log.info("收到事件: {}, OpenID: {}", eventType, openid);

            // 只处理关注事件
            if (requestBody.contains("<Event><![CDATA[subscribe]]></Event>")) {
                log.info("用户关注公众号: {}", openid);

                // 异步获取用户UnionID
                wechatBusinessService.handleUserSubscribe(openid);

                //
                return "success";
            } else if ("unsubscribe".equals(eventType)) {
                log.info("用户取消关注: {}", openid);
//                weChatUserService.handleUserUnsubscribe(openId);
                return "success";
            } else {
                // 暂时忽略其他事件
                log.debug("忽略其他事件: {}", eventType);
                return "success";
            }
        } catch (Exception e) {
            log.error("处理微信消息时发生异常", e);
            return "success"; // 发生异常也要返回success，否则微信会重试
        }
    }


    @GetMapping("/mp/message/send")
    @PermitAll
    public CommonResult<String> sendTemplateMessage(@RequestParam(required = false) String openId) {
        wechatBusinessService.pushBillMessage(openId);
        return CommonResult.success("发送成功");
    }

}
