package com.muyu.wechat.controller;


import com.muyu.wechat.domain.Message;
import com.muyu.wechat.message.Article;
import com.muyu.wechat.message.NewMessage;
import com.muyu.wechat.util.TokenUtil;
import com.thoughtworks.xstream.XStream;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: YZL
 * @Created: 2024/9/19 20:26
 */
@RestController
public class WxTestController {


    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request) {
        ServletInputStream inputStream = null;
        HashMap<String, String> map = new HashMap<>();
        try {
            inputStream = request.getInputStream();
            SAXReader saxReader = new SAXReader();
            //读取request输入流，获得Document对象
            Document document = saxReader.read(inputStream);
            //获得root结点
            Element rootElement = document.getRootElement();
            //获取所有的子节点
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                map.put(element.getName(), element.getStringValue());
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        System.out.println(map);
        //回复消息
        String message = "";
        if ("图文".equals(map.get("Content"))) {
            message = getReplyNewsMessage(map);
        } else {
            message = getReplyMessage(map);

        }
        return message;
    }

    /**
     * 获得回复的消息内容
     *
     * @param map
     * @return
     */
    private String getReplyMessage(HashMap<String, String> map) {
        Message message = new Message();
        message.setToUserName(map.get("FromUserName"));
        message.setFromUserName(map.get("ToUserName"));
//        message.setMsgType(map.get("MsgType"));
        message.setMsgType("text");
        message.setCreateTime(System.currentTimeMillis() / 1000);
        message.setContent("官方回复:您好");
        //XStream将java对象转换为xml字符串
        XStream xStream = new XStream();
        xStream.processAnnotations(Message.class);
        String xml = xStream.toXML(message);
        return xml;
    }


    @GetMapping("/")
    public String check(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                        @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {

        //1.将token、timestamp、nonce三个参数进行字典排序
        String token = "asdasd";
        List<String> list = Arrays.asList(token, timestamp, nonce);
        //排序
        Collections.sort(list);
        //2.将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list) {
            stringBuilder.append(s);
        }
        //加密
        try {
            MessageDigest instance = MessageDigest.getInstance("sha1");
            //使用sha1进行加密,获得byte数组
            byte[] digest = instance.digest(stringBuilder.toString().getBytes());
            StringBuilder sum = new StringBuilder();
            for (byte b : digest) {
                sum.append(Integer.toHexString((b >> 4) & 15));
                sum.append(Integer.toHexString(b & 15));
            }
            //3.开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if (!StringUtils.isEmpty(signature) && signature.contentEquals(sum)) {
                return echostr;
            }

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @PostMapping("/test")
    public void test() {
        String accessToken = TokenUtil.getAccessToken();
        System.out.println(accessToken);
    }

    private String getReplyNewsMessage(Map<String, String> map) {
        NewMessage newsMessage = new NewMessage();
        newsMessage.setToUserName(map.get("FromUserName"));
        newsMessage.setFromUserName(map.get("ToUserName"));
        newsMessage.setMsgType("news");
        newsMessage.setCreateTime(System.currentTimeMillis() / 1000);
        newsMessage.setArticleCount(1);
        List<Article> articles = new ArrayList<>();
        Article article = new Article();
        article.setTitle("oneone哦恩恩");
        article.setDescription("详细描述--------------信息");
        article.setUrl("https://www.baidu.com");
        article.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/RiaWwmABEMmkFKQMeQZLLYaxknlzE9CxSozVSH42iaXiaQcia5hPPUicuNYbS8dG99zsMZ1ic266ialM42Mbn8SkN54kA/0");
        articles.add(article);
        newsMessage.setArticles(articles);
        //XStream将java对象转换为xml字符串
        XStream xStream = new XStream();
        xStream.processAnnotations(NewMessage.class);
        String xml = xStream.toXML(newsMessage);
        return xml;
    }
}
