package com.muyu.wxController;

import com.muyu.message.Article;
import com.muyu.message.NewMessage;
import com.muyu.message.TextMessage;
import com.muyu.util.TokenUtil;
import com.muyu.util.WechatUtil;
import com.thoughtworks.xstream.XStream;
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.*;

/**
 * @ClassName WxController
 * @Description 描述
 * @Author YiBo.Liu
 * @Date 2024/9/17 16:59
 */
@RestController("/wx")
public class WxController {

    @GetMapping("/wxTest")
    public String test() {
        return "Hello wechat";
    }

    /**
     * 完成微信消息验证 判断是否是微信消息
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/")
    public String check(String signature, String timestamp, String nonce, String echostr) {
        //1）将token、timestamp、nonce三个参数进行字典序排序
        String token = "lybjava";
        List<String> list = Arrays.asList(token, timestamp, nonce);
        //排序
        Collections.sort(list);
        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder stringBuilder = new StringBuilder();
        for (String string : list) {
            stringBuilder.append(string);
        }
        //加密
        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;
    }


    /**
     * 用户发送消息，回复消息
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request) throws IOException {

            ServletInputStream inputStream = request.getInputStream();
            Map<String, String> map = new HashMap<>();

        try {
            SAXReader reader = new SAXReader();
            //读取request的输入流，获得Document对象
            Document document = reader.read(inputStream);
            //获得root节点
            Element root = document.getRootElement();
            //获得root的子节点
            List<Element> elements = root.elements();
            for (Element element : elements) {
                map.put(element.getName(), element.getStringValue());
            }
        }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);

        }
        System.out.println("回复给用户的消息:"+message);
        return message;
    }

    /**
     * 获得回复的消息内容
     * @param map
     * @return xml格式的字符串
     */
    private String getReplyMessage(Map<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;
    }

    /**
     * 获取Access_token
     * @return
     */
    @GetMapping("/getToken")
    public String  getToken() {
        String accessToken = TokenUtil.getAccessToken();
        return accessToken;
    }

    /**
     * 回复图文消息
     * @param map
     * @return
     */
    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("一个图文消息");
        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;
    }


    @GetMapping("/send")
    public void send(@RequestParam("openId") String openId,@RequestParam("content")String content) {
        WechatUtil.send(openId,content);
    }





}
