package com.vetti.common.ai.gpt;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI ChatGPT 对话
 */
@Component
public class ChatGPTClient {

    // OpenAI API密钥，需要替换为你自己的密钥
    @Value("${chatGpt.apiKey}")
    private String apiKey;
    // API端点URL
    @Value("${chatGpt.apiUrl}")
    private String apiUrl;

    @Value("${chatGpt.model}")
    private String model;

    @Value("${chatGpt.modelQuestion}")
    private String modelQuestion;

    @Value("${chatGpt.modelCV}")
    private String modelCV;

    @Value("${chatGpt.modelJxCv}")
    private String modelJxCv;

    @Value("${chatGpt.modelJd}")
    private String modelJd;

    @Value("${chatGpt.modelIsq}")
    private String modelIsq;

    @Value("${chatGpt.modelRoleCv}")
    private String modelRoleCv;

    @Value("${chatGpt.modelCvJx}")
    private String modelCvJx;

    @Value("${chatGpt.modelCbqpf}")
    private String modelCbqpf;

    @Value("${chatGpt.modelAafx}")
    private String modelAnalyzedAttachment;

    @Value("${chatGpt.modelAaHb}")
    private String modelAaHb;

    @Value("${chatGpt.modelMarkdown}")
    private String modelMarkdown;

    @Value("${chatGpt.modelWebAiTq}")
    private String modelWebAiTq;

    @Value("${chatGpt.modelPpg}")
    private String modelPpg;

    @Value("${chatGpt.modelRLinkAl}")
    private String modelRLinkAl;


    @Value("${chatGpt.modelRLinkAl_1}")
    private String modelRLinkAl_1;

    @Value("${chatGpt.modelAiIntPf}")
    private String modelAiIntPf;

    @Value("${chatGpt.modelAiCvSr}")
    private String modelAiCvSr;

    @Value("${chatGpt.modelAiCac}")
    private String modelAiCac;

    @Value("${chatGpt.modelAiCiv}")
    private String modelAiCiv;

    @Value("${chatGpt.role}")
    private String role;

    /**
     * 处理 AI 聊天
     *
     * @param promptText 文字提示信息
     * @return
     */
    public String handleAiChat(String promptText,String type) {
        String resultText = "";
        // 创建ChatGPT客户端
        // HTTP客户端
        HttpClient client =  HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(30))
                .build();
        // JSON处理工具
        ObjectMapper objectMapper = new ObjectMapper();;
        // 单轮对话返回结果
        try {
            if("CV".equals(type)){
                resultText = sendMessage(promptText, modelCV,objectMapper,client,role);
            }else if("QA".equals(type)){
                resultText = sendMessage(promptText, modelQuestion,objectMapper,client,role);
            } else if("PF".equals(type)){
                resultText = sendMessage(promptText, model,objectMapper,client,role);
            }else if("JX".equals(type)){
                resultText = sendMessage(promptText, modelJxCv,objectMapper,client,role);
            }else if("JD".equals(type)){
                resultText = sendMessage(promptText, modelJd,objectMapper,client,role);
            }else if("ISQ".equals(type)){
                resultText = sendMessage(promptText, modelIsq,objectMapper,client,role);
            }else if("ROLECV".equals(type)){
                resultText = sendMessage(promptText, modelRoleCv,objectMapper,client,role);
            }else if("CVJX".equals(type)){
                //简历解析
                resultText = sendMessage(promptText, modelCvJx,objectMapper,client,role);
            }else if("CBQPF".equals(type)){
                resultText = sendMessage(promptText, modelCbqpf,objectMapper,client,role);
            }else if("AAFX".equals(type)){
                //附件分析
                resultText = sendMessage(promptText, modelAnalyzedAttachment,objectMapper,client,role);
            }else if("AAHB".equals(type)){
                //附件分析信息合并
                resultText = sendMessage(promptText, modelAaHb,objectMapper,client,role);
            }else if("MARKDOWN".equals(type)){
                //生成最终的Markdown格式简历
                resultText = sendMessage(promptText, modelMarkdown,objectMapper,client,role);
            }else if("WEBAITQ".equals(type)){
                //网站AI信息提取
                resultText = sendMessage(promptText, modelWebAiTq,objectMapper,client,role);
            }else if("PPG".equals(type)){
                //个人简介生成器
                resultText = sendMessage(promptText, modelPpg,objectMapper,client,role);
            }else if("RLINKAL".equals(type)){
                //招聘链接信息分析补全-第一阶段
                resultText = sendMessage(promptText, modelRLinkAl,objectMapper,client,role);
            }else if("RLINKAL_1".equals(type)){
                //招聘链接信息分析补全-第二阶段
                resultText = sendMessage(promptText, modelRLinkAl_1,objectMapper,client,role);
            }else if("AIINTPF".equals(type)){
                //候选人AI面试分析
                resultText = sendMessage(promptText, modelAiIntPf,objectMapper,client,role);
            }else if("AICVSR".equals(type)){
                //招聘者AI简历评分和排名系统
                resultText = sendMessage(promptText, modelAiCvSr,objectMapper,client,role);
            }else if("AICAC".equals(type)){
                //招聘者查看候选人匹配度
                resultText = sendMessage(promptText, modelAiCac,objectMapper,client,role);
            }else if("AICIV".equals(type)){
                //候选人面试综合评估
                resultText = sendMessage(promptText, modelAiCiv,objectMapper,client,role);
            }else {
                resultText = sendMessage(promptText, modelQuestion,objectMapper,client,role);
            }

        } catch (IOException | InterruptedException e) {
            System.err.println("单轮对话出错: " + e.getMessage());
        }
        return resultText;
    }


    /**
     * 发送单轮对话请求
     * @param prompt 用户输入的提示词
     * @param model 使用的模型，例如"gpt-3.5-turbo"或"gpt-4"
     * @return 模型返回的响应
     * @throws IOException 网络或IO异常
     * @throws InterruptedException 线程中断异常
     */
    private String sendMessage(String prompt, String model,ObjectMapper objectMapper,HttpClient client,String role) throws IOException, InterruptedException {
        // 创建消息列表
        List<Map> messages = JSONUtil.toList(prompt, Map.class);

//        Map<String, String> message = new HashMap<>();
//        message.put("role", role);
//        message.put("content", prompt);
//        messages.add(message);

        return sendChatRequest(messages, model, 0.7,objectMapper,client);
    }

    /**
     * 发送多轮对话请求
     * @param messages 消息列表，包含历史对话
     * @param model 使用的模型
     * @param temperature 创造性参数，0-1之间
     * @return 模型返回的响应
     * @throws IOException 网络或IO异常
     * @throws InterruptedException 线程中断异常
     */
    private String sendChatRequest(List<Map> messages, String model, double temperature,ObjectMapper objectMapper,HttpClient client)
            throws IOException, InterruptedException {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);
        requestBody.put("messages", messages);
        requestBody.put("temperature", temperature);
        // 转换为JSON字符串
        String jsonBody = objectMapper.writeValueAsString(requestBody);
        // 构建HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiUrl))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();
        // 发送请求并获取响应
        HttpResponse<String> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofString()
        );
        // 解析响应
        return parseResponse(response.body(),objectMapper);
    }

    /**
     * 解析API响应，提取回复内容
     * @param responseBody 响应体字符串
     * @return 提取的回复内容
     * @throws IOException JSON解析异常
     */
    private String parseResponse(String responseBody,ObjectMapper objectMapper) throws IOException {
        JsonNode rootNode = objectMapper.readTree(responseBody);
        // 检查是否有错误
        if (rootNode.has("error")) {
            String errorMessage = rootNode.get("error").get("message").asText();
            throw new IOException("API Error: " + errorMessage);
        }
        // 提取回复内容
        return rootNode.get("choices")
                .get(0)
                .get("message")
                .get("content")
                .asText();
    }

}
