package com.ruoyi.api.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonArray;
import com.ruoyi.api.domain.WeChatMessage;
import com.ruoyi.api.service.IWeChatMessageService;
import com.ruoyi.api.util.HttpUtils;
import com.ruoyi.api.util.MessageUtil;
import com.ruoyi.base.domain.BaseConfig;
import com.ruoyi.base.service.IBaseConfigService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员卡Service业务层处理
 *
 * @author vinjor-m
 * @date 2025-03-17
 */
@Service
public class WeChatMessageServiceImpl implements IWeChatMessageService {


    @Value("${wx-app.appId}")
    private String appId;

    @Value("${wx-app.appSecret}")
    private String appSecret;

    @Value("${wx-app.token}")
    private String token;

    @Resource
    private IBaseConfigService configService;

    /**发送消息url*/
    private static String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send";

    /**获取accessTokenUrl*/
    private String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";



    /**
     * 校验签名
     *
     * @param message {@link WeChatMessage}
     * @return java.lang.String
     * @author PQZ
     * @date 12:08 2025/4/25
     **/
    @Override
    public String checkSignature(WeChatMessage message) {
        String signature = message.getSignature();
        String timestamp = message.getTimestamp();
        String nonce = message.getNonce();
        //必须与请求参数中的token一致
        List<String> list = new ArrayList<>();
        list.add(token);
        list.add(timestamp);
        list.add(nonce);
        // 排序跟使用hutool工具类 进行字典排序跟加密
        String str = list.stream().sorted().collect(Collectors.joining());
        String tmpStr = SecureUtil.sha1(str);
        if (signature.equals(tmpStr)) {
            return message.getEchostr();
        } else {
            return "shibai";
        }
    }

    /**
     * 发送消息返回
     *
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return java.lang.String
     * @author PQZ
     * @date 12:52 2025/4/25
     **/
    @Override
    public String acceptMessage(HttpServletRequest request, HttpServletResponse response) {
        //返回值
        String result = "success";
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            // 发送者的openid
            String fromUserName = requestMap.get("FromUserName");
            // 小程序的原始ID
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 文本消息内容
            String content = requestMap.get("Content");
            // 事件类型
            String event = requestMap.get("Event");
            StringBuilder contentMessage = new StringBuilder();
            String contentStr = "嗨，欢迎加入通告快接，您想咨询那个问题，请点击选择";
            String tgzHtml = "https://www.ddtg.site/pages/mine/member/member-card?userType=01";
            String bzHtml = "https://www.ddtg.site/pages/mine/member/member-card?userType=02";
            String jzqHtml = "https://www.ddtg.site/pages/mine/coupon/my-coupon";
            String tgzStr = "<a href=\""+tgzHtml+"\">1、通告主卡</a>";
            String bzStr = "<a href=\""+bzHtml+"\">2、博主VIP</a>";
            String jzqStr = "<a href=\""+jzqHtml+"\">3、急招券</a>";
            contentMessage.append(contentStr).append("\n")
                    .append(tgzStr).append("\n")
                    .append(bzStr).append("\n")
                    .append(jzqStr).append("\n");
            if (msgType.equals("event")) {
                sendCustomerTextMessage(fromUserName, contentMessage.toString(), getAccessToken());
            } else if (msgType.equals("text")) {
                if (content.equals("0")) {
                    return switchCustomerService(fromUserName, toUserName);
                } else {
                    sendCustomerTextMessage(fromUserName, contentMessage.toString(), getAccessToken());
                }
            } else {
                sendCustomerTextMessage(fromUserName, contentMessage.toString(), getAccessToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void sendCustomerTextMessage(String openid, String text, String accessToken) throws IOException {
        HashMap<String, Object> map_content = new HashMap<>();
        map_content.put("content", text);
        HashMap<String, Object> map = new HashMap<>();
        map.put("touser", openid);
        map.put("msgtype", "text");
        map.put("text", map_content);
        String content = JSON.toJSONString(map);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(map, headers);
        HttpUtils.sendPostRequest(SEND_URL + "?access_token=" + accessToken, HttpMethod.POST, httpEntity);
    }

    /**
     * 人工服务
     *
     * @param fromUserName
     * @param toUserName
     * @return
     */
    public String switchCustomerService(String fromUserName, String toUserName) {
        return "<xml>\n" +
                "    <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "    <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "    <CreateTime>" + System.currentTimeMillis() / 1000 + "</CreateTime>\n" +
                "    <MsgType><![CDATA[transfer_customer_service]]></MsgType>\n" +
                "</xml>";
    }

    /**
     * 获取accessToken
     * @author PQZ
     * @date 16:12 2025/4/25
     * @return java.lang.String
    **/
    public String getAccessToken() {
        //拼接url【传入appId和secret】
        url = url.replace("APPID", appId).replace("APPSECRET", appSecret);
        String str = HttpUtils.sendGetRequest(url);
        JSONObject jsonObject = JSONObject.parseObject(str);
        return jsonObject.getString("access_token");
    }


}
