package com.muyu.server.controller;
import com.muyu.common.wechat.domain.TextMessage;
import com.muyu.domain.Articles;
import com.muyu.domain.NewsMessage;
import com.muyu.server.util.WordUtil;
import com.thoughtworks.xstream.XStream;
import io.swagger.v3.oas.annotations.tags.Tag;
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.util.StringUtils;
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.*;

/**
 * 微信公众号控制层
 * @Author：蓬叁
 * @Package：com.muyu.wxapplication.controller
 * @Project：WXApplication
 * @name：WXController
 * @Date：2024/9/17 下午8:27
 */
@RestController
@Tag(name = "微信公众号")
public class WXController {

    @GetMapping("/hello")
    public String hello(){
        return "Hello Wechat";
    }

    @GetMapping("/wechat")
    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 = "Psan";
        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));
            }
            System.out.println("signature:"+signature);
            System.out.println("sum:"+sum);
//        3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
            if (!StringUtils.isEmpty(signature)&&signature.equals(sum.toString())){
                return echostr;
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();

//        查看发送信息类型
//        byte[] bytes = new byte[1024];
//        int len = 0;
//        while ((len = inputStream.read(bytes)) != -1) {
//            System.out.println(new String(bytes, 0, len));
//        }

        HashMap<String, String> map = new HashMap<>();
        // xstream工具类
        SAXReader reader = new SAXReader();
        try {
            //读取request输入流，获取Document对象
            Document document = reader.read(inputStream);
            //获取root节点
            Element rootElement = document.getRootElement();
            //获取所有子节点
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                map.put(element.getName(), element.getStringValue());
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        System.out.println(map);
        String massage = null;
        if ("图文".equals(map.get("Content"))) {
            massage = getReplyNewsMessage(map);
        } else {
            massage = getReplyMessage(map);
        }
//        String massage = getReplyMessageByWord(map);
        return massage;
    }

    /**
     * 获得回复的信息内容
     * @param map
     * @return xml格式的字符串
     */
    private String getReplyMessage(HashMap<String, String> map) {
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(map.get("FromUserName"));
        textMessage.setFromUserName(map.get("ToUserName"));
        textMessage.setMsgType("text");
        textMessage.setContent("你好吖");
        textMessage.setCreateTime(System.currentTimeMillis()/1000);

        //XStream将java对象转换为xml字符串
        XStream xStream = new XStream();
        xStream.processAnnotations(TextMessage.class);
        String xml = xStream.toXML(textMessage);
        return xml;
    }

    /**
     * 获得同义词
     * @param map
     * @return xml格式的字符串
     */
    private String getReplyMessageByWord(HashMap<String, String> map) {
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(map.get("FromUserName"));
        textMessage.setFromUserName(map.get("ToUserName"));
        textMessage.setMsgType("text");
        textMessage.setContent(WordUtil.getWords(map.get("Content")));
        textMessage.setCreateTime(System.currentTimeMillis()/1000);

        //XStream将java对象转换为xml字符串
        XStream xStream = new XStream();
        xStream.processAnnotations(TextMessage.class);
        String xml = xStream.toXML(textMessage);
        return xml;
    }

    /**
     * 获得回复的图文信息内容
     * @param map
     * @return
     */
    private String getReplyNewsMessage(HashMap<String, String> map) {
        NewsMessage newsMessage = new NewsMessage();
        newsMessage.setToUserName(map.get("FromUserName"));
        newsMessage.setFromUserName(map.get("ToUserName"));
        newsMessage.setMsgType("news");
        newsMessage.setCreateTime(System.currentTimeMillis()/1000);
        newsMessage.setArticleCount(1);
        List<Articles> articles = new ArrayList<>();
        Articles article = new Articles();
        article.setTitle("蓬叁测试公众号");
        article.setDescription("来自蓬叁");
        article.setUrl("http://www.psan.com");
        article.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/ZR9F78J7iasww9HxBJRjsBMInrZ78YbXzKvgwy6iabyfZCiaM0CJKzOIS3fUAboIbh07s8icPfYW7RMiajLmx2opticw/0");
        articles.add(article);
        newsMessage.setArticles(articles);

        //XStream将java对象转换为xml字符串
        XStream xStream = new XStream();
        xStream.processAnnotations(NewsMessage.class);
        String xml = xStream.toXML(newsMessage);
        return xml;
    }

}
