package com.foreverwin.mesnac.common.util;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.modular.core.exception.BusinessException;
import org.jsoup.Connection.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 获取企业微信AccessToken
 *
 * @author Leon
 * @since 2021-06-07
 */
@Component
@ConditionalOnProperty(prefix = "wechat", name = {"corpId","secret","accessTokenUrl"})
public class TokenSingleton {

    @Value("${wechat.corpId}")
    private String corpId;
    @Value("${wechat.secret}")
    private String secret;
    @Value("${wechat.accessTokenUrl}")
    private String accessTokenUrl;

    private Map<String, String> map = new HashMap<>();

    private TokenSingleton() {
    }

    private static TokenSingleton single = null;

    // 静态工厂方法
    public static TokenSingleton getInstance() {
        if (single == null) {
            single = new TokenSingleton();
        }
        return single;
    }

    public static void setSingle(TokenSingleton single) {
        TokenSingleton.single = single;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public Map<String, String> getMap() throws Exception {
        Long nowDate = new Date().getTime();

        String time = map.get("time");
        String accessToken = map.get("access_token");

        //判断token是否存在，并是否有效
        if (accessToken != null && time != null && nowDate - Long.parseLong(time) < 6000 * 1000) {
            //------------------------------------------
        } else {
            accessToken = getAccessToken();

            //失效之后，重新赋值
            map.put("time", nowDate + "");
            map.put("access_token", accessToken);
        }

        return map;
    }


    /**
     * 发送Https请求，获取accessToken
     * 1.首次调用需要获取
     * 2上次获取的失效后
     *
     * @return
     * {
     *     "errcode":0 ,
     *     "errmsg":"ok" ,
     *     "access_token": "xxxxxx",
     *     "expires_in": 7200
     * }
     */
    public String getAccessToken() throws Exception {
        String accessToken = null;

        accessTokenUrl = accessTokenUrl.replace("ID", corpId);
        accessTokenUrl = accessTokenUrl.replace("SECRET", secret);
        Response response = HttpUtils.get(accessTokenUrl);
        //如果请求成功
        if (null != response) {
            String body = response.body();
            JSONObject jsonObject = (JSONObject) JSONObject.parse(body);
            int errCode = jsonObject.getInteger("errcode");
            if (errCode != 0) {
                throw BusinessException.build(jsonObject.getString("errmsg"));
            }

            accessToken = jsonObject.getString("access_token");
        }

        return accessToken;
    }
}