package com.css.simulation.resource.scheduler.infra.feign.algorithm;

import api.common.util.HttpUtil;
import api.common.util.JsonUtil;
import api.common.util.ObjectUtil;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AlgorithmPlatform {

    private static final String TOKEN_KEY = "ALGPLATFORM:TOKEN";

    @Resource
    OauthParameter oauthParameter;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 获取算法文件临时下载地址
     * @param algorithmId 算法 id
     * @return 算法文件临时下载地址
     */
    @SneakyThrows
    public String getAlgorithmFile(String algorithmId) {
        //取得token
        String token = getToken();
        String algorithmAddressUrl = oauthParameter.getAlgorithmListUri()
                + "?access_token=" + token
                + "&id=" + algorithmId;
        return HttpUtil.get(algorithmAddressUrl);
    }


    @SneakyThrows
    private String getToken() {

        String token = stringRedisTemplate.opsForValue().get(TOKEN_KEY);
        if (ObjectUtil.isNull(token)) {//token失效重新获取
            String tokenUri = oauthParameter.getTokenUri();
            String appid = oauthParameter.getAppid();
            String secret = oauthParameter.getSecret();
            String URI = tokenUri + "&appid=" + appid + "&secret=" + secret;
            String result = HttpUtil.get(HttpUtil.getHttpClient(), HttpUtil.getRequestConfig(), URI);
            JsonNode jsonNode = JsonUtil.readTree(result);
            JsonNode dataNode = jsonNode.path("data");
            if (ObjectUtil.isNotNull(dataNode)) {
                token = dataNode.path("access_token").asText();
                if (ObjectUtil.isNotNull(token)) {
                    int expiresSec = dataNode.path("expires_in_sec").asInt();
                    stringRedisTemplate.opsForValue().set(TOKEN_KEY, token, expiresSec / 60);
                }
            }
        }
        return token;
    }
}
