package shop.alien.storeplatform.util;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * AI 服务鉴权配置
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class AiAuthTokenUtil {

    private final RestTemplate restTemplate;

    @Value("${third-party-login.base-url}")
    private String loginUrl;

    @Value("${third-party-user-name-admin.base-url}")
    private String userName;

    @Value("${third-party-pass-word.base-url}")
    private String passWord;

    /**
     * 登录 AI 服务，获取 token
     *
     * @return accessToken
     */
    public String getAccessToken() {
        log.info("登录Ai服务获取token...{}", loginUrl);
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("username", userName);
        formData.add("password", passWord);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

        ResponseEntity<String> response;
        try {
            log.info("请求Ai服务登录接口===================>");
            response = restTemplate.postForEntity(loginUrl, requestEntity, String.class);
        } catch (Exception e) {
            log.error("请求AI服务登录接口失败", e);
            return null;
        }

        if (response != null && response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            log.info("请求Ai服务登录成功 postForEntity.getBody()\t{}", body);
            if (StringUtils.hasText(body)) {
                JSONObject jsonObject = JSONObject.parseObject(body);
                if (jsonObject != null) {
                    JSONObject dataJson = jsonObject.getJSONObject("data");
                    if (dataJson != null) {
                        return dataJson.getString("access_token");
                    }
                }
            }
            log.warn("AI服务登录响应解析失败 body: {}", body);
            return null;
        }

        log.error("请求AI服务 登录接口失败 http状态：{}", response != null ? response.getStatusCode() : null);
        return null;
    }
}


