package com.ruoyi.excel.wecom.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.excel.wecom.model.WecomConfig;
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;

/**
 * 企业微信基础服务类
 */
public class WecomBaseService {
    private WecomConfig wecomConfig;

    public WecomBaseService(WecomConfig wecomConfig) {
        this.wecomConfig = wecomConfig;
    }

    /**
     * 获取accessToken
     *
     * @return accessToken
     * @throws IOException IO异常
     */
    public String getAccessToken() throws IOException {
        if (!wecomConfig.isAccessTokenExpired()) {
            return wecomConfig.getAccessToken();
        }

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + wecomConfig.getCorpId() + "&corpsecret=" + wecomConfig.getCorpSecret();
        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");
            wecomConfig.setAccessToken(accessToken);
            wecomConfig.setAccessTokenExpireTime(System.currentTimeMillis() + (expiresIn - 60) * 1000);
            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();
        }
    }

    public WecomConfig getWecomConfig() {
        return wecomConfig;
    }

    public void setWecomConfig(WecomConfig wecomConfig) {
        this.wecomConfig = wecomConfig;
    }
}