package com.ebo.module.utils;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

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

@Slf4j
public class GetAccessToken {
    /**
     * 以管理员身份跳过认证
     * @return
     */
    public static String getAccessToken() {
        String authUrl = "http://localhost:8659/sys/auth/login";
        String username = "guoxianhui";
        String password = "guoxianhui2002";
        String key = ""; // 如果有 key，填写对应的值
        String captcha = ""; // 如果有 captcha，填写对应的值

        HttpPost httpPost = new HttpPost(authUrl);
        httpPost.setHeader("Content-Type", "application/json");

        String json = String.format("{\"username\":\"%s\",\"password\":\"%s\",\"key\":\"%s\",\"captcha\":\"%s\"}",
                username, password, key, captcha);
        try (CloseableHttpClient httpClient = HttpClients.createDefault();){
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            try (CloseableHttpResponse response = httpClient.execute(httpPost);){
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String result = EntityUtils.toString(responseEntity);
                    log.info("Auth Response: " + result);

                    // 解析响应数据
                    Map<String, Object> responseMap = new Gson().fromJson(result, Map.class);
                    Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");

                    return dataMap.get("access_token").toString();
                }
            }
        } catch (IOException e) {
            log.error("Failed to get access token", e);
        }
        return null;
    }
}
