package com.cool.store.handler;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.PartnerUserWechatBindDAO;
import com.cool.store.dto.wechat.WechatUserInfoDTO;
import com.cool.store.service.wechat.WechatTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author suzhuhong
 * @Date 2025/10/14 14:56
 * @Version 1.0
 */
@Component
@Slf4j
public class WeChatHandler {

    @Resource
    PartnerUserWechatBindDAO partnerUserWechatBindDAO;
    @Resource
    WechatTemplateService wechatTemplateService;

    public Map<String, Object> parseXmlToMap(String xmlContent) throws Exception {
        Map<String, Object> result = new HashMap<>();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xmlContent)));

        NodeList nodes = document.getDocumentElement().getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                String tagName = node.getNodeName();
                String textContent = node.getTextContent();
                result.put(tagName, textContent);
            }
        }

        return result;
    }


    public String processMessage(Map<String, Object> messageMap) {
        String msgType = (String) messageMap.get("MsgType");
        String event = (String) messageMap.get("Event");

        switch (msgType) {
            case "event":
                return handleEvent(messageMap);

//            case "text":
//                return handleTextMessage(message);
//
//            case "image":
//                return handleImageMessage(message);

            default:
                // 其他类型的消息直接回复success
                return "success";
        }
    }

    private String handleEvent(Map<String, Object> messageMap) {
        String event = (String) messageMap.get("Event");
        String fromUserName = (String) messageMap.get("FromUserName");
        String toUserName = (String) messageMap.get("ToUserName");

        switch (event) {
            case "subscribe":
                // 关注事件 - 绑定用户
                return handleSubscribeEvent(fromUserName,toUserName);

            case "unsubscribe":
                // 取消关注事件 - 解绑用户
                return handleUnsubscribeEvent(fromUserName,toUserName);

            default:
                return buildWelcomeReply(fromUserName, toUserName);
        }
    }

    private String handleSubscribeEvent(String fromUserName,String toUserName) {
        try {

            //根据openId 获取用户信息
            WechatUserInfoDTO userInfo = wechatTemplateService.getUserInfo(fromUserName, null);

            log.info("handleSubscribeEvent: {}", JSONObject.toJSONString(userInfo));

            //根据unionId 更新服务号ID
            if (userInfo != null) {
                partnerUserWechatBindDAO.updateByUnionId(userInfo.getUnionid(),fromUserName);
            }

            // 立即回复欢迎消息
            return buildWelcomeReply(fromUserName, toUserName);

        } catch (Exception e) {
            // 即使处理失败也要返回success
            return buildWelcomeReply(fromUserName, toUserName);
        }
    }

    /**
     * 处理取消关注事件
     */
    private String handleUnsubscribeEvent(String fromUserName,String toUserName) {

        // 异步处理用户解绑
        //userBindingService.unbindOfficialAccountUser(openId);

        return "success";
    }

    private String buildSuccessReply(String fromUser, String toUser) {
        return String.format(
                "<xml>" +
                        "<ToUserName><![CDATA[%s]]></ToUserName>" +
                        "<FromUserName><![CDATA[%s]]></FromUserName>" +
                        "<CreateTime>%d</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[success]]></Content>" +
                        "</xml>",
                fromUser, toUser, System.currentTimeMillis() / 1000
        );
    }


    private String buildWelcomeReply(String fromUser, String toUser) {
        return String.format(
                "<xml>" +
                        "<ToUserName><![CDATA[%s]]></ToUserName>" +
                        "<FromUserName><![CDATA[%s]]></FromUserName>" +
                        "<CreateTime>%d</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[欢迎关注！您已成功绑定通知服务，可以接收小程序的重要消息通知。]]></Content>" +
                        "</xml>",
                fromUser, toUser, System.currentTimeMillis() / 1000
        );
    }

}
