package com.czg.controller;

import com.czg.account.entity.UserInfo;
import com.czg.account.service.UserInfoService;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 公众号 通知
 *
 * @author ww
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/notify")
public class NotifyController {

    private static final String SUCCESS = "SUCCESS";

    @Resource
    private UserInfoService userInfoService;
    private static final String TOKEN = "DZjyHBq3nTujF0NM1dnXikU8ZCvy";


    @RequestMapping(produces = MediaType.TEXT_PLAIN_VALUE)
    public String notify(HttpServletRequest request,
                         @RequestParam(required = false) String signature,
                         @RequestParam(required = false) String timestamp,
                         @RequestParam(required = false) String nonce,
                         @RequestParam(required = false) String echostr) {

        // 1. 处理 GET 请求（微信开发者验证）
        if ("GET".equals(request.getMethod())) {
            log.info("接收到微信验证请求 - signature: {}, timestamp: {}, nonce: {}, echostr: {}",
                    signature, timestamp, nonce, echostr);
            return echostr;
        }

        // 2. 处理 POST 请求（微信消息推送，如关注、消息等）
        else if ("POST".equals(request.getMethod())) {
            log.info("接收到微信 POST 消息请求 - signature: {}, timestamp: {}, nonce: {}",
                    signature, timestamp, nonce);
            // 1. 读取请求体中的 XML 数据
            String xmlData = readPostXml(request);
            if (xmlData.isEmpty()) {
                log.error("微信 POST 消息体为空");
                return "";
            }
            log.info("微信 POST 消息 XML 原始内容: {}", xmlData);

            // 2. 解析 XML 为 Map（便于获取字段）
            Map<String, String> messageMap;
            try {
                messageMap = parseXmlToMap(xmlData);
            } catch (DocumentException e) {
                log.error("XML 解析失败，原始内容: {}", xmlData, e);
                return "";
            }
            log.info("微信 POST 消息内容: {}", messageMap);
            // 获取消息类型（如 event）
            String msgType = messageMap.get("MsgType");
            // 获取事件类型（如 unsubscribe：用户取消关注  subscribe：用户关注）
            String event = messageMap.get("Event");
            // 获取用户 OpenID
            String openId = messageMap.get("FromUserName");
            //携带参数
            String eventKey = messageMap.get("EventKey");
            Long userId = null;
            log.info("解析结果 - 消息类型: {}, 事件类型: {}, 用户 OpenID: {} 携带参数: {}", msgType, event, openId, eventKey);
            if (eventKey != null && eventKey.startsWith("qrscene_")) {
                try {
                    // 截取 "qrscene_" 前缀后的字符串（长度为 8），并转为 Long
                    String numberStr = eventKey.substring("qrscene_".length());
                    userId = Long.parseLong(numberStr);
                } catch (NumberFormatException e) {
                    log.error("EventKey 后缀不是有效数字，eventKey: {}", eventKey, e);
                }
            }
            updateUserInfoIsAc(event, openId, userId);
            // 处理完成后，微信要求返回 "SUCCESS" 或空字符串（否则会重试推送）
            return SUCCESS;
        }
        return "";
    }

    //更新userInfo openId 以及 关注表示isAc
    private void updateUserInfoIsAc(String event, String openId, Long userId) {
        if ("subscribe".equals(event) && userId != null) {
            // 关注事件，更新用户关注状态为 1
            UserInfo userInfo = new UserInfo();
            userInfo.setIsAc(1);
            userInfo.setWechatAcOpenId(openId);
            userInfoService.update(userInfo, new QueryWrapper().eq(UserInfo::getId, userId));
        } else if ("unsubscribe".equals(event)) {
            // 取消关注事件，更新用户关注状态为 0
            UserInfo userInfo = new UserInfo();
            userInfo.setIsAc(0);
            userInfoService.update(userInfo, new QueryWrapper().eq(UserInfo::getWechatAcOpenId, openId));
        }
    }

    /**
     * 工具方法：读取 POST 请求体中的 XML 数据
     */
    private String readPostXml(HttpServletRequest request) {
        StringBuilder xmlSb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                xmlSb.append(line);
            }
        } catch (IOException e) {
            log.error("读取微信 POST 消息体失败", e);
        }
        return xmlSb.toString();
    }


    // 将 XML 字符串解析为 Map<String, String>
    private static Map<String, String> parseXmlToMap(String xmlData) throws DocumentException {
        Map<String, String> resultMap = new HashMap<>(16);
        Document document = DocumentHelper.parseText(xmlData);
        Element rootElement = document.getRootElement();

        // 遍历所有子节点，将节点名和文本值存入 Map
        Iterator<Element> elementIterator = rootElement.elementIterator();
        while (elementIterator.hasNext()) {
            Element childElement = elementIterator.next();
            resultMap.put(childElement.getName(), childElement.getTextTrim());
        }
        return resultMap;
    }
}
