package com.infoepoch.pms.dispatchassistant.domain.langchain.chat;


import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.common.utils.JsonUtils;
import com.infoepoch.pms.dispatchassistant.common.utils.RestTemplateUtils;
import com.infoepoch.pms.dispatchassistant.domain.basic.store.KeyValueStoreService;
import com.infoepoch.pms.dispatchassistant.domain.langchain.ChatConstants;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatRequest;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ChatService {

    @Autowired
    private RestTemplateUtils restTemplateUtils;

    @Autowired
    private KeyValueStoreService keyValueStoreService;

    /**
     * 与LLM模型对话
     *
     * @param request 请求
     * @return 请求结果字符串
     */
    public String chat(ChatRequest request) {
        // 从KEY_VALUE_STORE表中获取chat请求地址
        String url = keyValueStoreService.queryValueByKey(ChatConstants.URL_CHAT_CHAT);
        if (url == null)
            throw new ValidationException("请先配置chat请求地址");
        Map<String, Object> param = request.toMap();
        String result = restTemplateUtils.postForString(url, param);
        // 截取字符串
        result = subStringResult(result);
        // 判断请求结果是否报错
        judgeErrorResponse(result);
        return result;
    }

    /**
     * @param request
     * @return
     */
    public String knowledgeChat(KnowledgeBaseChatRequest request) {
        String url = keyValueStoreService.queryValueByKey(ChatConstants.URL_CHAT_KNOWLEDGE_BASE_CHAT);
        if (url == null)
            throw new ValidationException("请先配置知识库chat请求地址");
        Map<String, Object> param = request.toMap();
        String result = restTemplateUtils.postForString(url, param);
        // 截取字符串
        result = subStringResult(result);
        // 判断请求结果是否报错
        judgeErrorResponse(result);
        return result;
    }

    /**
     * 截取result结果字符串
     *
     * @param result
     * @return
     */
    private String subStringResult(String result) {
        if(result.startsWith("data")) {
            return result.substring(result.indexOf("data") + 5, result.length() - 1);
        } else {
            return result;
        }
    }

    /**
     * @param result
     */
    private void judgeErrorResponse(String result) {
        try {
            ErrorResponse response = JsonUtils.jsonToObject(result, ErrorResponse.class);
            if (response.getDetail() != null) {
                StringBuilder errorMessage = new StringBuilder();
                for (ErrorResponse.Detail detail : response.getDetail()) {
                    errorMessage.append(detail.getMsg()).append("；");
                }
                if (StringUtils.isNotBlank(errorMessage.toString())) {
                    throw new ValidationException(errorMessage.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
