package com.customization.yll.liuzhoucitycollege.api;

import cn.hutool.core.util.StrUtil;
import com.customization.yll.common.web.util.ApiCallManager;
import com.customization.yll.liuzhoucitycollege.config.JinzhiConfiguraton;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yaolilin
 * @desc 金智接口请求管理
 * @date 2024/12/2
 **/
public class JinzhiApiManager {
    private final JinzhiTokenManager tokenManager = new JinzhiTokenManager();
    private final ApiCallManager apiCallManager = new ApiCallManager();
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 调用金智接口，如果请求失败会返回空字符串
     * @param apiUrl 接口地址，需要完整路径
     * @param body 请求体
     * @return 返回结果
     */
    public String callApi(String apiUrl, String body) {
        Map<String, String> header = getHeader();
        try (Response response = apiCallManager.post( apiUrl, body, header)) {
            if (response.code() == 401) {
                // token 失效，使用新的token请求
                header.put("token", tokenManager.getNewToken());
                return apiCallManager.postGetBody( apiUrl, body, header);
            }
            if (!response.isSuccessful()) {
                log.error("接口请求失败：" + response);
            }
            return response.body() == null ? "" : response.body().string();
        } catch (IOException e) {
            log.error("接口请求失败", e);
            return "";
        }
    }

    @NotNull
    private Map<String, String> getHeader() {
        // 公共请求头
        Map<String, String> header = new HashMap<>(2);
        header.put("appId", JinzhiConfiguraton.getAppId());
        header.put("accessToken", tokenManager.getToken());
        return header;
    }

    private String getToken(boolean newToken) {
        String token;
        if (newToken) {
            token = tokenManager.getNewToken();
        } else {
            token = tokenManager.getToken();
        }
        if (StrUtil.isEmpty(token)) {
            log.error("获取token为空");
        }
        return token;
    }

}
