package shop.alien.store.controller;


import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
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.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.client.RestTemplate;
import shop.alien.store.util.ai.AiAuthTokenUtil;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = {"ai聊天"})
@CrossOrigin
@RestController
@RequestMapping("/aiChat")
@RequiredArgsConstructor
@RefreshScope
public class AiChatController {

    private final AiAuthTokenUtil aiAuthTokenUtil;

    private final RestTemplate restTemplate;

    @Value("${third-party-ai-chat.base-url:http://124.93.18.180:9100/ai/life-manager/api/v1/question_classification/classify_and_route}")
    private String aiChatUrl;

    @Value("${third-party-ai-chat.history-url:http://124.93.18.180:9100/ai/life-manager/api/v1/chat_history}")
    private String aiHistoryChatUrl;

    /**
     * 调用 AI 服务，获取聊天结果
     *
     * @return 聊天结果
     */
    @RequestMapping("/aiChatResult")
    public ResponseEntity<String> aiChat(@RequestParam("question") String question){
        String accessToken = aiAuthTokenUtil.getAccessToken();
        JSONObject data = new JSONObject();
        if (!StringUtils.hasText(accessToken)) {
            data.put("fail","登录失败");
            return ResponseEntity.badRequest().body(data.toJSONString());
        }

        // 初始化请求体Map
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("question", question);
        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);
        aiHeaders.set("Authorization", "Bearer " + accessToken);
//        aiHeaders.set("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1cHN0b3JlQGFkbWluLmNvbSIsImlkIjo2LCJ0aW1lIjoxNzYyOTI1NDAzLjY1MTY5MjZ9.07lz8Ox2cGC28UCmqcKCt5R6Rfwtgs-Eiu0ttgWRxws");

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);

        try {
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(aiChatUrl, request, String.class);
            return stringResponseEntity;
        } catch (Exception e) {
            log.error("调用AI聊天接口 接口异常------", e);
        }
        return  ResponseEntity.badRequest().body(null);
    }

    /**
     * 调用 AI 服务，获取聊天结果
     *
     * @return 聊天结果
     */
    @RequestMapping("/aiChatHistory")
    public ResponseEntity<String> aiChatHistory(@RequestParam("user_id") String user_id,@RequestParam("page") String page,@RequestParam("rounds_per_page") String rounds_per_page){
        String accessToken = aiAuthTokenUtil.getAccessToken();
        JSONObject data = new JSONObject();
        if (!StringUtils.hasText(accessToken)) {
            data.put("fail","登录失败");
            return ResponseEntity.badRequest().body(data.toJSONString());
        }

        HttpHeaders aiHeaders = new HttpHeaders();
        aiHeaders.set("Authorization", "Bearer " + accessToken);
        HttpEntity<Void> request = new HttpEntity<>(aiHeaders);

        String url = UriComponentsBuilder.fromHttpUrl(aiHistoryChatUrl)
                .queryParam("user_id", user_id)
                .queryParam("page", page)
                .queryParam("rounds_per_page", rounds_per_page)
                .build()
                .toUriString();

        try {
            log.info("调用AI聊天历史接口(GET) url={}, user_id={}, page={}, rounds_per_page={}", url, user_id, page, rounds_per_page);
            ResponseEntity<String> stringResponseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
            return stringResponseEntity;
        } catch (HttpServerErrorException e) {
            String responseBody = e.getResponseBodyAsString();
            log.error("调用AI聊天历史接口 5xx异常 url={}, status={}, responseBody={}", url, e.getStatusCode(), responseBody, e);
            data.put("fail", "AI服务异常: " + e.getStatusCode() + ", " + (StringUtils.hasText(responseBody) ? responseBody : e.getStatusText()));
            return ResponseEntity.status(e.getStatusCode()).body(data.toJSONString());
        } catch (Exception e) {
            log.error("调用AI聊天历史接口 接口异常 url={}", url, e);
            data.put("fail", "调用AI服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(data.toJSONString());
        }
    }
}
