package com.srs.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.srs.common.config.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.Formatter;

@Component
public class WeChatUtil {

    @Autowired
    private WeChatConfig weChatConfig;

    private String cachedAccessToken;
    private long tokenExpireTime;

    private String cachedJsapiTicket;
    private long ticketExpireTime;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取 access_token
     */
    public String getAccessToken() {
        long now = System.currentTimeMillis();
        if (cachedAccessToken != null && tokenExpireTime > now) {
            return cachedAccessToken;
        }

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="
                + weChatConfig.getCorpId() + "&corpsecret=" + weChatConfig.getSecret();

        try {
            String response = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(response);

            if (jsonObject.containsKey("access_token")) {
                cachedAccessToken = jsonObject.getString("access_token");
                int expiresIn = jsonObject.getIntValue("expires_in");
                tokenExpireTime = now + expiresIn * 1000 - 60000; // 提前1分钟过期
                return cachedAccessToken;
            } else {
                throw new RuntimeException("获取 access_token 失败：" + jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("请求 access_token 出错", e);
        }
    }

    /**
     * 获取 jsapi_ticket
     */
    public String getJsapiTicket(String type) {
        long now = System.currentTimeMillis();
        if (cachedJsapiTicket != null && ticketExpireTime > now) {
            return cachedJsapiTicket;
        }

        try {
            String accessToken = getAccessToken();
            String url = "";
            //如果type为corpId，则使用corpId，否则使用agentId
            if (type.equals("corpId")) {
                url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + accessToken;
            }else if (type.equals("agentId")){
                url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=" + accessToken + "&type=agent_config";
            }


            String response = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(response);

            if (jsonObject.containsKey("ticket")) {
                cachedJsapiTicket = jsonObject.getString("ticket");
                int expiresIn = jsonObject.getIntValue("expires_in");
                ticketExpireTime = now + expiresIn * 1000 - 60000; // 提前1分钟过期
                return cachedJsapiTicket;
            } else {
                throw new RuntimeException("获取 jsapi_ticket 失败：" + jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("请求 jsapi_ticket 出错", e);
        }
    }

    /**
     * 生成签名：企业签名
     */
    public JSONObject generateSignature(String type, String url) {
        String jsapiTicket = getJsapiTicket(type);
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();

        // 确保 URL 只包含 # 之前的部分
        url = url.split("#")[0];

        String string1 = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            String signature = byteToHex(crypt.digest());

            JSONObject result = new JSONObject();
            result.put("nonceStr", nonceStr);
            result.put("timestamp", timestamp);
            result.put("signature", signature);
            result.put("url", url); // 返回 URL，方便调试

            return result;
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }


    private String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private String createNonceStr() {
        return Long.toString(System.currentTimeMillis(), 36);
    }

    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    /**
     * 发送企业微信文本消息   知无涯
     */
    /**
     * 发送企业微信文本消息
     * @param toUser 接收消息的用户  下方"代填"部分，例如：2023001 多个数据使用""包装，例如："2023001|2023002|2023003"
     * @param content 消息内容
     */

    // todo  发送企业微信文本消息
    public void sendTextMessage(String toUser, String content) {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject msg = new JSONObject();
        msg.put("touser", toUser);
        msg.put("msgtype", "text");
        msg.put("agentid", weChatConfig.getAgentId());

        JSONObject text = new JSONObject();
        text.put("content", content);
        msg.put("text", text);

        try {
            String response = restTemplate.postForObject(url, msg, String.class);
            JSONObject jsonResponse = JSONObject.parseObject(response);
            if (jsonResponse.getIntValue("errcode") != 0) {
                throw new RuntimeException("发送消息失败: " + jsonResponse.getString("errmsg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("请求发送消息出错", e);
        }
    }

    /**
     * 发送企业微信 Markdown 消息
     * @param toUser 接收用户，'|' 分隔
     * @param markdown Markdown 内容
     */
    public void sendMarkdownMessage(String toUser, String markdown) {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject msg = new JSONObject();
        msg.put("touser", toUser);
        msg.put("msgtype", "markdown");
        msg.put("agentid", weChatConfig.getAgentId());

        JSONObject md = new JSONObject();
        md.put("content", markdown);
        msg.put("markdown", md);

        try {
            String response = restTemplate.postForObject(url, msg, String.class);
            JSONObject jsonResponse = JSONObject.parseObject(response);
            if (jsonResponse.getIntValue("errcode") != 0) {
                throw new RuntimeException("发送Markdown消息失败: " + jsonResponse.getString("errmsg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("请求发送Markdown消息出错", e);
        }
    }
}
