package com.fs.store.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.store.dto.ClientCredGrantReqDTO;
import com.fs.store.dto.MiniGramSubsMsgResultDTO;
import com.fs.store.dto.TemplateMessageSendRequestDTO;
import com.fs.store.dto.WeXinAccessTokenDTO;
import com.hc.openapi.tool.fastjson.JSON;
import com.hc.openapi.tool.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MiniProgramHttp {

    /**
     * 微信小程序-发送订阅消息地址
     */
    private static final String BASE_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";

    /**
     * 微信小程序-获取accessToken地址
     */
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/stable_token";


    /**
     * 发送微信订阅消息 (使用 Hutool)
     * @param accessToken token
     * @param param 请求数据
     * @return String
     */
    public MiniGramSubsMsgResultDTO sendSubscribeMessage(String accessToken, TemplateMessageSendRequestDTO param) {
        String url = BASE_URL + "?access_token=" + accessToken;

        log.info("发送小程序订阅消息, 请求 URL: {}", url);

        String requestBody = JSON.toJSONString(param);
        log.info("发送小程序订阅消息, 请求参数: {}", requestBody);

        try {
            String response = HttpUtil.post(url, requestBody);
            log.info("发送小程序订阅消息, HTTP 请求 URL: {}", url);
            log.info("发送小程序订阅消息, HTTP 请求体: {}", requestBody);
            log.info("发送小程序订阅消息, HTTP 响应: {}", response);

            MiniGramSubsMsgResultDTO result = JSONObject.parseObject(response, MiniGramSubsMsgResultDTO.class);
            if(ObjectUtil.notEqual(result.getErrcode(),0)){
                throw new RuntimeException("发送小程序订阅消息失败, " + result.getErrmsg());
            }
            log.info("发送小程序订阅消息, 解析结果: {}", JSON.toJSONString(result));
            return result;

        } catch (Exception e) {
            log.error("发送小程序订阅消息失败: {}", e.getMessage());
            throw e;
        }
    }


    /**
     * 获取微信 Stable Access Token
     * @return WeXinAccessTokenDTO
     */
    public WeXinAccessTokenDTO getStableAccessToken(ClientCredGrantReqDTO param) {
        String requestBody = JSONObject.toJSONString(param);
        log.info("获取微信 Stable Access Token, 请求参数: {}", requestBody); // 打印请求参数

        try {
            String responseJson =
            HttpRequest.post(TOKEN_URL).contentType("application/json").body(requestBody).execute().body();
            log.info("获取微信 Stable Access Token, HTTP 请求 URL: {}", TOKEN_URL);
            log.info("获取微信 Stable Access Token, HTTP 请求体: {}", requestBody);
            log.info("获取微信 Stable Access Token, HTTP 响应: {}", responseJson);

            if(StringUtils.isBlank(responseJson)){
                throw new RuntimeException("获取微信 Stable Access Token 失败,response为空");
            }
            WeXinAccessTokenDTO result = JSONObject.parseObject(responseJson, WeXinAccessTokenDTO.class);
            log.info("获取微信 Stable Access Token, 解析结果: {}", JSONObject.toJSONString(result)); //记录解析结果
            if(result == null || StringUtils.isBlank(result.getAccessToken())){
                throw new RuntimeException("获取微信 Stable Access Token 失败, accessToken为空");
            }
            return result;

        } catch (Exception e) {
            log.error("获取微信 Stable Access Token 失败", e);
            throw e;
        }
    }
}
