package com.muyu.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.muyu.domain.Message;
import com.muyu.domain.SubscribedUser;

import com.muyu.service.xyrService;
import com.muyu.util.OkHttpUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @className: xyrServiceImpl  ️✈️
 * @author: Yang 鹏  🦅
 * @date: 2024/9/18 12:05 ⏰
 * @Version: 1.0
 * @description:
 */
@Service
public class xyrServiceImpl implements xyrService {


    /**
     * 处理信息
     * @param request
     * @return
     */
    @Override
    public String handleMessage(HttpServletRequest request) {
        ServletInputStream inputStream = null;

        HashMap<String, String> map = new HashMap<>();
        try {
            inputStream = request.getInputStream();


            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(inputStream);
            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 replyMessage = getReplyMessage(map);

        System.out.println("返回消息:"+replyMessage);
        return replyMessage;
    }

    @Override
    public String getSignUpUserInfo(String code) {
        String appId = TokenUtil.APP_ID;
        String appSecret = TokenUtil.APP_SECRET;
        String url=  String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",appId,appSecret,code);

        String request = OkHttpUtils.sendGetRequest(url);
        String accessToken = JSONObject.parseObject(request).getString("access_token");
        String openId = JSONObject.parseObject(request).getString("openid");

        String userInfoUrl=  String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",accessToken,openId);

        String userInfo = OkHttpUtils.sendGetRequest(userInfoUrl);
        SubscribedUser subscribedUser = JSONObject.parseObject(userInfo, SubscribedUser.class);
        System.out.println(subscribedUser);
        //TODO
        // 添加数据库

        WechatUtil.send(openId,"授权成功");

        return "恭喜你,信息被盗取了";
    }

    /**
     * 获得回复的消息内容
     * @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);
        String appId = TokenUtil.APP_ID;
        String appSecret = TokenUtil.APP_SECRET;
        String redirectDomain = TokenUtil.REDIRECT_DOMAIN;

        //获取用户授权的url
        String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect",appId,
                "http://"+redirectDomain+"/getSignUpUserInfo","snsapi_userinfo") ;


        message.setContent("点击给公众号授权链接 <a href=\""+url+"\">授权</a>");
        XStream xStream =new XStream();
        xStream.processAnnotations(Message.class);
        String xml = xStream.toXML(message);
        return xml;
    }

}
