package com.ruoyi.system.yyinterface;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ruoyi.system.response.AccessTokenResponse;
import com.ruoyi.system.response.GenericResponse;
import com.ruoyi.system.response.SignHelper;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author jiuli
 * @Date 2024/2/20
 */
@Component
public class TokenUtils {

    private final static Logger logger = LoggerFactory.getLogger(TokenUtils.class);

    @Value("${config.appKey}")
    private String appKey;

    @Value("${config.secret}")
    private String sec;

    @Value("${config.openApiUrl}")
    private String url;

    @Value("${config.apiurl}")
    private String apiUrl;

    private static String key;

    private static String secret;

    private static String openApiUrl;

    @Getter
    private static String devUrl;

    @PostConstruct
    public void setKey() {
        TokenUtils.key = this.appKey;
    }

    @PostConstruct
    public void setSecret() {
        TokenUtils.secret = this.sec;
    }

    @PostConstruct
    public void setOpenApiUrl() {
        TokenUtils.openApiUrl = this.url;
    }

    @PostConstruct
    public String getApiUrl() {
        return TokenUtils.devUrl = this.apiUrl;
    }

    public static AccessTokenResponse getAccessToken() throws IOException, InvalidKeyException, NoSuchAlgorithmException {
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("appKey", key);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        // 计算签名
        String signature = SignHelper.sign(params, secret);
        params.put("signature", signature);
        // 请求

        String requestUrl = openApiUrl + "/open-auth/selfAppAuth/getAccessToken";
        GenericResponse<AccessTokenResponse> response = RequestTool.doGet(requestUrl, params, new TypeReference<GenericResponse<AccessTokenResponse>>() {
        });
        if (response.isSuccess()) {
            return response.getData();
        }
        logger.info("data:" + response.getData());
        logger.error("请求开放平台接口失败，code: {}, message: {}", response.getCode(), response.getMessage());
        throw new RuntimeException("请求开放平台接口失败, code: " + response.getCode() + ", message: " + response.getMessage());
    }

}
