package com.dgtly.wxportal.config;

import com.alibaba.fastjson.JSONObject;
import com.dgtly.common.utils.http.HttpUtils;
import com.dgtly.wxportal.exception.ESignException;
import com.dgtly.wxportal.utils.ESign.ESignUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Formatter;


@Component
public class ESignConfig {
    private final Logger log = LoggerFactory.getLogger(ESignConfig.class);

    public static ESignConfig eSignConfig;
    @Value(value = "${esign.appId:none}")
    private String appId;

    @Value(value = "${esign.appSecret:none}")
    private String appSecret;

    @Value(value = "${esign.serviceUrl:none}")
    private String eSignServiceUrl ;

    private ESignUrl eSignUrl;

    private String accessToken;

    /**
     * 过期时间
     */
    private long expires;
    /**
     * 过期时间
     */
    private String  refreshToken;


    @Value(value = "${esign.personNotifyUrl:none}")
    private String personNotifyUrl ;

    @Value(value = "${esign.organNotifyUrl:none}")
    private String organNotifyUrl ;

    @Value(value = "${esign.signSuccessUrl:none}")
    private String signSuccessUrl ;
    @Value(value = "${esign.fileUrl:none}")
    private String fileUrl;

    /**
     * 获取access_token
     * @return
     */
    public String getAccessToken() {
        JSONObject json;
        String url;

        try {
            //token未过期使用缓存的token
            long currentTiem = new Date().getTime();
            log.info("线程id{}",Thread.currentThread().getId());
            log.info("过期时间为{}",this.expires);
            log.info("当前时间为{}",currentTiem);
            if(this.accessToken!=null &&(currentTiem)<(this.expires-10000)){
                log.info("本身的token为{}",this.accessToken);
                return this.accessToken;
            }
            //获取请求地址
            url = this.getUrl(ESignUrl.AccessToken);
            log.info("开始请求E签宝接口：url==>",url);
            json = JSONObject.parseObject(HttpUtils.sendGet(url));
            log.info("结果返回==》",json);
        }catch (Exception e){
            reSetToken();
            log.error("获取E签宝token错误",e);
            throw e;
        }
        Integer code = json.getInteger("code");
        if(code!=0){
            reSetToken();
            throw new ESignException(code,url,json.getString("message"));
        }
        JSONObject data = json.getJSONObject("data");
        this.expires = data.getLong("expiresIn");
        this.accessToken = data.getString("token");
        this.refreshToken = data.getString("refreshToken");

        return this.accessToken;
    }

    public void reSetToken() {
        log.info("清除ESigntoken缓存");
        accessToken =null;
        expires = 0;
        refreshToken = null;

    }

    public String getAppId() {
        return appId;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public String geteSignServiceUrl() {
        return eSignServiceUrl;
    }

    public String getPersonNotifyUrl() {
        return personNotifyUrl;
    }

    public String getOrganNotifyUrl() {
        return organNotifyUrl;
    }

    public String getSignSuccessUrl() {
        return signSuccessUrl;
    }

    public String getFileUrl(){
        return fileUrl;
    }


    public String getUrl(ESignUrl eSignUrl,Object ... args){
        String str = this.eSignServiceUrl+eSignUrl.url;
        switch (eSignUrl){
            case AccessToken:
                str= new Formatter().format(str, this.appId,this.appSecret).toString();
                break;
            default:
                str= new Formatter().format(str, args).toString();
                break;
        }
        return str;
    }


}
