package com.ruoyi.common.wxMessage;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class WeChatMessageSender {
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    public static final String WX_GET_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=LANG";
    //通过code获取网站授权 access_token
    private static final String WZ_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    // Step 1: 获取access_token
    public static String getAccessToken() throws Exception {
        //String url = TOKEN_URL.replace("{}", WxMpPropertiesConfig.getAppId()).replace("{}", WxMpPropertiesConfig.getSecret());
        String url = TOKEN_URL.replace("APPID", "wxe91077cda5699d3b").replace("APPSECRET", "258749dd19cb6acc8bbc28ededbd7e97");
        HttpGet request = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = httpClient.execute(request, httpResponse ->
                EntityUtils.toString(httpResponse.getEntity()));
        // 解析JSON获取access_token，这里假设已经通过某种方式（如Jackson, Gson）解析
        // 这里简单用String.split()模拟解析
        String[] parts = result.split(",");
        for (String part : parts) {
            if (part.contains("access_token")) {
                String[] tokenParts = part.split(":");
                return tokenParts[1].trim().replace("\"", "");
            }
        }
        return null;
    }


    // Step 1: 通过code获取网站授权 access_token (非公众号access_token)
    public static HashMap<String, Object> getWzAccessToken(String code) throws Exception {
        //String url = TOKEN_URL.replace("{}", WxMpPropertiesConfig.getAppId()).replace("{}", WxMpPropertiesConfig.getSecret());
        String url = WZ_TOKEN_URL.replace("APPID", WxMpPropertiesConfig.getAppId()).replace("SECRET", WxMpPropertiesConfig.getSecret()).replace("CODE", code);
        //获取用户openid
        RestTemplate restTemplate = new RestTemplate();
        //解决乱码,以utf-8编码格式获取,不加这个会乱码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        // 解析JSON
        String body = forEntity.getBody();
        Gson gson = new Gson();
        HashMap<String, Object> jsonObject = gson.fromJson(body, HashMap.class);
        return jsonObject;
    }

    // Step 2: 发送消息
    public static void sendMessage(Map<String,Object> mesgMap) throws Exception {
        String accessToken = getAccessToken();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String url = MESSAGE_URL + accessToken;
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            StringEntity entity = new StringEntity(JSONObject.toJSONString(mesgMap), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *	获取用户昵称
     */
    public static Map<String,Object> getWxUserInfo(String code) throws Exception {
        Map<String,Object> wxUserMap = new HashMap<>();
        // 获取Access_Token
        HashMap<String, Object> jsonObject = getWzAccessToken(code);
        String openid = String.valueOf(jsonObject.get("openid"));
        String accessToken = String.valueOf(jsonObject.get("access_token"));
        String url = WX_GET_INFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid).replace("LANG", "zh_CN");
        RestTemplate restTemplate = new RestTemplate();
        //解决乱码,以utf-8编码格式获取,不加这个会乱码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        // 解析JSON
        String body = forEntity.getBody();
        Gson gson = new Gson();
        wxUserMap = gson.fromJson(body, HashMap.class);
        return wxUserMap;
    }


    public static void main(String[] args) throws Exception {
        Map<String,Object> mesgMap = new HashMap<>();
        mesgMap.put("touser", "oBUfy7KYW8z61QrBbJ5mwebvbfd8");
        mesgMap.put("template_id", "aAtYCooyrG5I1j-ofeQuEye_71ZH5SXZnv-tNoC1BgU");
        mesgMap.put("url", "https://zxygdhf.qs163.cn/work/pages/detail?id=17479811779881459");
        Map<String,Object> dMap = new HashMap<>();
        Map<String,Object> dMap1 = new HashMap<>();
        dMap1.put("value","17479811779881459");
        dMap.put("character_string1",dMap1);

        Map<String,Object> dMap2 = new HashMap<>();
        dMap2.put("value","张三");
        dMap.put("thing7",dMap2);

        Map<String,Object> dMap3 = new HashMap<>();
        dMap3.put("value","18112341234");
        dMap.put("phone_number8", dMap3);

        Map<String,Object> dMap4 = new HashMap<>();
        dMap4.put("value","2025-06-04 17:41:41");
        dMap.put("time9",dMap4);

        mesgMap.put("data",dMap);
        WeChatMessageSender.sendMessage(mesgMap);
        //WeChatMessageSender.getWxUserInfo("081dvf0w3zS4453z1G3w3UktlG3dvf0y");
    }

}