package com.ruoyi.excel.wecom.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.excel.wecom.domain.CorpInfo;
import org.apache.http.HttpEntity;
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 java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信基础服务类
 */
public class WecomBaseService {
    /**
     * Redis key 前缀：wecom_access_token:{corpId}
     */
    private static final String ACCESS_TOKEN_KEY_PREFIX = "wecom_access_token:";

    /**
     * 获取accessToken（根据当前企业上下文动态获取）
     *
     * @return accessToken
     * @throws IOException IO异常
     */
    public String getAccessToken(String corpId) throws IOException {
        // 2. 从 Redis 获取缓存的 access_token
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        String cacheKey = ACCESS_TOKEN_KEY_PREFIX + corpId;
        String cachedToken = redisCache.getCacheObject(cacheKey);
        if (cachedToken != null && !cachedToken.trim().isEmpty()) {
            return cachedToken;
        }

        // 3. 缓存不存在或已过期，从数据库查询企业信息
        ICorpInfoService corpInfoService = SpringUtils.getBean(ICorpInfoService.class);
        CorpInfo corpInfo = corpInfoService.selectCorpInfoByCorpId(corpId);
        if (corpInfo == null) {
            throw new RuntimeException("企业信息不存在: " + corpId);
        }

        // 4. 调用企业微信API获取新的 access_token
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpInfo.getCorpId() + "&corpsecret=" + corpInfo.getSecret();
        String response = doGet(url);
        JSONObject jsonObject = JSON.parseObject(response);

        if (jsonObject.getInteger("errcode") == 0) {
            String accessToken = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getInteger("expires_in");

            // 5. 将 access_token 缓存到 Redis（提前60秒过期）
            redisCache.setCacheObject(cacheKey, accessToken, expiresIn - 60, TimeUnit.SECONDS);

            return accessToken;
        } else {
            throw new RuntimeException("获取accessToken失败: " + jsonObject.getString("errmsg"));
        }
    }

    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return 响应结果
     * @throws IOException IO异常
     */
    public String doGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } finally {
            response.close();
            httpClient.close();
        }
    }

    /**
     * 发送POST请求
     *
     * @param url  请求URL
     * @param data 请求数据
     * @return 响应结果
     * @throws IOException IO异常
     */
    public String doPost(String url, String data) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(data, "UTF-8"));
        httpPost.setHeader("Content-Type", "application/json");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } finally {
            response.close();
            httpClient.close();
        }
    }


}