package org.enfi.common.api;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import org.enfi.config.WXConfig;

import java.util.Map;

public class TemplateMsgApi {
    private static String sendApiUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

    public static ApiResult send(Map params) {
        // String post = HttpUtil.post(sendApiUrl + getToken(), JSONObject.toJSONString(params));
        AccessTokenApi.removeAccessToken();
        String post = HttpUtils.post(sendApiUrl + AccessTokenApi.getAccessToken().getAccessToken(), JSONObject.toJSONString(params));
        if (((Integer) new ApiResult(post).get("errcode")) != 0) {
            AccessTokenApi.refreshAccessToken(ApiConfigKit.getApiConfig());
            post = HttpUtils.post(sendApiUrl + AccessTokenApi.getAccessToken().getAccessToken(), JSONObject.toJSONString(params));
        }
        return new ApiResult(post);
    }

    public static String getToken() {
        String json = HttpUtils.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential", ParaMap.create("appid", WXConfig.getAppId()).put("secret", WXConfig.getAppSecret()).getData());
        AccessToken accessToken = new AccessToken(json);
        System.out.println(accessToken);
        return accessToken.getAccessToken();
    }
}
