package com.bcxin.signature.components;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@Component
public class JTLZComponent {
    private static final Logger logger = LoggerFactory.getLogger(JTLZComponent.class);
    private static final String LICENSE_LOGIN = "/license-app/v1/security/login";
    private static final String LICENSE_ISSUE= "/license-app/v1/license/{item_code}/issue?access_token=";
    private static final String LICENSE_ABOLISH= "/license-app/v1/license/{item_code}/abolish?access_token=";
    private static Map<String, Instant> tokenMap = new HashMap<>();
    private final String ip_address;
    private final String app_key;
    private final String app_secret;
    private final String account;
    private final String password;
    public JTLZComponent(@Value("${myapps.signature.license.ip_address}") String ip_address,
                         @Value("${myapps.signature.license.app_key}") String app_key,
                         @Value("${myapps.signature.license.app_secret}") String app_secret,
                         @Value("${myapps.signature.license.account}") String account,
                         @Value("${myapps.signature.license.password}") String password) {
        this.ip_address = ip_address;
        this.app_key = app_key;
        this.app_secret = app_secret;
        this.account = account;
        this.password = password;
    }

    private String generateToken() {
        // 生成 token 的逻辑
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Exception lastException = null;
        String token = "";
        try {
            JSONObject json = new JSONObject();
            json.put("app_key", app_key);
            json.put("app_secret", app_secret);
            json.put("account", account);
            json.put("password", password);
            String ret = HttpUtil.post(ip_address + LICENSE_LOGIN, json.toJSONString());
            if (org.apache.commons.lang3.StringUtils.isEmpty(ret)) {
                return token;
            }
            JSONObject result = JSONObject.parseObject(ret);
            String ack_code = result.getString("ack_code");
            token = result.getString("access_token");
            if (!"SUCCESS".equals(ack_code) || StringUtils.isEmpty(token)) {
                return token;
            }

            // 记录 token 的生成时间
            tokenMap = new HashMap<>();
            tokenMap.put(token, Instant.now());
            return token;
        } catch (Exception e) {
            lastException = e;
            return token;
        } finally {
            stopWatch.stop();
            logger.error("====> {} 京通靓证获取token.license_login. 耗时 {} 秒", (lastException == null ? "success" : "failed"), lastException, stopWatch.getTotalTimeSeconds());
        }
    }

    public String getLicenseToken() {
        // 获取当前时间
        Instant now = Instant.now();
        // 检查 Map 中是否有 token
        if (tokenMap.isEmpty()) {
            // 如果没有 token，生成新的 token
            return generateToken();
        }

        // 获取最新的 token 及其生成时间
        String latestToken = null;
        Instant latestTime = null;
        for (Map.Entry<String, Instant> entry : tokenMap.entrySet()) {
            if (latestTime == null || entry.getValue().isAfter(latestTime)) {
                latestToken = entry.getKey();
                latestTime = entry.getValue();
            }
        }

        // 检查 token 是否过期
        Duration duration = Duration.between(latestTime, now);
        if (duration.toHours() >= 6) {
            // 如果 token 过期，生成新的 token
            return generateToken();
        } else {
            // 如果 token 没有过期，直接返回
            return latestToken;
        }
    }

    public String license_issue(String item_code,String body) {
        String pathApi = null;
        try {
            // 生成 token 的逻辑
            String token = this.getLicenseToken();

            pathApi = ip_address + LICENSE_ISSUE.replace("{item_code}", item_code) + token;
            String ret = HttpUtil.post(pathApi, body);
            return ret;
        } catch (Exception e) {
            logger.error("====> 2.fail to JTLZ schedule task job.license_issue.err：(item_code={},pathAPI={})}", item_code, pathApi, e);
            return "{\"ack_code\":\"FAILURE\",\"errors\":[{\"code\":\"12409\",\"severity\":\"ERROR\",\"message\":\"" + e.getMessage() + "\",\"innerCode\":\"\"}],\"sign\":null,\"sign_method\":null,\"timestamp\":null,\"correlation_id\":null,\"response_id\":\"a40e028c-d566-44fc-a2fa-ee4b8df715dc\",\"data\":null}";
        }
    }

    public String license_issue_fz(String item_code,String body){
        // 生成 token 的逻辑
        Exception lastException = null;
        String ret = null;
        String pathApi = null;
        try {
            pathApi = ip_address + LICENSE_ABOLISH.replace("{item_code}", item_code) + getLicenseToken();
            ret = HttpUtil.post(pathApi, body);
            return ret;
        } catch (Exception e) {
            lastException = e;
            return "{\"ack_code\":\"FAILURE\",\"errors\":[{\"code\":\"12409\",\"severity\":\"ERROR\",\"message\":\"" + e.getMessage() + "\",\"innerCode\":\"\"}],\"sign\":null,\"sign_method\":null,\"timestamp\":null,\"correlation_id\":null,\"response_id\":\"a40e028c-d566-44fc-a2fa-ee4b8df715dc\",\"data\":null}";
        } finally {
            logger.error("===> {} 京通靓证信息废止定时任务.license_issue_fz.返回报文(api=>{},body={}):{}",
                    (lastException == null ? "成功" : "异常"),
                    pathApi,
                    body,
                    ret, lastException);
        }
    }
}
