package com.css.simulation.resource.common.infra.acl.algorithm;

import api.common.pojo.common.ResponseBodyVO;
import api.common.pojo.constants.DictConstants;
import api.common.pojo.param.RedisParameter;
import api.common.util.HttpUtil;
import api.common.util.JsonUtil;
import api.common.util.ObjectUtil;
import com.css.simulation.resource.common.adapter.controller.RedisController;
import com.css.simulation.resource.common.infra.config.alg_platform.ClientDetail;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

@Service
public class AlgorithmExpandAcl {

    @Resource
    private RedisController redisController;

    @Resource
    private ClientDetail clientDetail;

    /**
     * String urlParam = "";
     * if (StringUtil.isNotEmpty(algorithmId)) {
     * urlParam = urlParam + "&algorithmId=" + algorithmId;
     * }
     * if (StringUtil.isNotEmpty(algorithmName)) {
     * urlParam = urlParam + "&algorithmName=" + algorithmName;
     * }
     * if (StringUtil.isNotEmpty(description)) {
     * urlParam = urlParam + "&description=" + description;
     * }
     * if (StringUtil.isNotEmpty(page)) {
     * urlParam = urlParam + "&page=" + page;
     * }
     * if (StringUtil.isNotEmpty(size)) {
     * urlParam = urlParam + "&size=" + size;
     * }
     * urlParam = urlParam + "&sort=" + sort;
     *
     * @param param 参数
     * @return 结果
     */
    public ResponseBodyVO<String> getAlgorithmList(@RequestBody String param) {
        //取得token
        String token = getToken();
        if (ObjectUtil.isNull(token)) {
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "获取算法平台token失败。");
        }
        String algorithmListUri = clientDetail.getAlgorithmListUri() + "?access_token=" + token + param;
        String result = HttpUtil.get(HttpUtil.getHttpClient(), HttpUtil.getRequestConfig(), algorithmListUri);


        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, "请求成功！", result);
    }

    @SneakyThrows
    public ResponseBodyVO<String> selectAlgorithmNameByAlgorithmId(@RequestBody String algorithmId) {
        //取得token
        String token = getToken();
        if (ObjectUtil.isNull(token)) {
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "获取算法平台token失败。");
        }
        String algorithmListUri = clientDetail.getAlgorithmListUri()
                + "?algorithmId=" + algorithmId
                + "&page=1&size=10&sort=algorithmId-desc&access_token=" + token;
        String httpResponseString = HttpUtil.get(HttpUtil.getHttpClient(), HttpUtil.getRequestConfig(), algorithmListUri);
        String algorithmName = new ObjectMapper().readTree(httpResponseString).path("data").path("content").get(0).path("algorithmName").asText();

        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, "请求成功！", algorithmName);
    }

    /**
     * 从缓存中获取token，没有才发送请求
     *
     * @return
     */
    private String getToken() {
        RedisParameter redisParameter = new RedisParameter();
        redisParameter.setKey(DictConstants.ALGORITHM_PLATFORM_TOKEN_CACHE_KEY);
        ResponseBodyVO<String> responseBodyVO = redisController.get(redisParameter);
        String token = responseBodyVO.getInfo();
        if (ObjectUtil.isNull(token)) {//token失效重新获取
            String tokenUri = clientDetail.getTokenUri();
            String appid = clientDetail.getAppid();
            String secret = clientDetail.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();
                    redisParameter.setMinutes(expiresSec / 60);
                    redisParameter.setValue(token);
                    redisController.set(redisParameter);
                }
            }
        }
        return token;
    }


    //TODO 可以把调度程序下载算法包改为访问这个接口
    public void download(String algorithmId) {
//        try {
//            //1 获取 token
//            String tokenUrl = clientDetail.getTokenUri() + "?grant_type=client_credential&appid=" + clientDetail.getAppid() + "&secret=" + clientDetail.getSecret();
//            String tokenJson = HttpUtil.get(tokenUrl);
//            String token = new ObjectMapper().readTree(tokenJson).path("data").path("access_token").asText();
//            //2 获取 下载地址
//            String idOfAlgorithm = algorithmExpandMapper.selectIdByAlgorithmId(AlgorithmExpandEntity.builder().algorithmId(algorithmId).build());
//            String downloadUrl = clientDetail.getAlgorithmAddrUri() + "?access_token=" + token + "&id=" + idOfAlgorithm;
//            //3 下载算法包
//            String downloadUrlJson = HttpUtil.get(downloadUrl);
//            String tempDownloadUrl = new ObjectMapper().readTree(downloadUrlJson).path("data").asText();
////                log.info("索为算法" + algorithmId + "下载地址为：" + tempDownloadUrl);
//            InputStream inputStream = HttpUtil.getInputStream(tempDownloadUrl);
//            FileUtil.writeInputStreamToLocalFile(inputStream, algorithmTarLinuxTempPath);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
    }
}
