package com.kingdee.eas.custom.beisen.utils;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class TokenExample {
    public static void main(String[] args) {
        // 创建 Token Manager 实例（单例模式）
        BeisenTokenManager tokenManager = new BeisenTokenManager(
                BeisenTokenManager.Config.APP_KEY,
                BeisenTokenManager.Config.APP_SECRET,
                BeisenTokenManager.Config.TOKEN_URL
        );

        try {
            // 获取 Access Token
            String accessToken = tokenManager.getAccessToken();
            System.out.println("Access Token: " + accessToken);

            // 使用 Token 调用北森API示例
            callItenetApi(accessToken);

        } catch (RuntimeException e) {
            // 处理 Token 获取失败的情况
            System.err.println("Failed to get access token: " + e.getMessage());
            e.printStackTrace();
            // 这里可以触发告警或降级逻辑
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void callItenetApi(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://openapi.italent.cn/your_api_endpoint")
                .header("Authorization", "Bearer " + accessToken)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("API Response: " + response.body().string());
            } else {
                System.err.println("API Call Failed: " + response.code());
            }
        } catch (IOException e) {
            System.err.println("API Request Failed: " + e.getMessage());
        }
    }
}