package com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation;

import com.infoepoch.pms.dispatchassistant.common.component.SnowFlake;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.common.utils.DateTool;
import com.infoepoch.pms.dispatchassistant.common.utils.JsonUtils;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.RoleService;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import com.infoepoch.pms.dispatchassistant.domain.langchain.ChatMessage;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.ChatBaseRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.ChatResponse;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.line.ConversationLine;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.line.ConversationLineCriteria;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.line.IConversationLineRepository;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.line.QuestionRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.line.history.IConversationLineHistoryRepository;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class ConversationService {

    @Autowired
    private RoleService roleService;

    @Autowired
    private IConversationRepository repository;
    @Autowired
    private IConversationLineRepository conversationLineRepository;
    @Autowired
    private IConversationLineHistoryRepository conversationLineHistoryRepository;
    @Autowired
    private RestTemplate restTemplate;

    public Map<String, Object> pageList(ConversationCriteria criteria) {
        List<Conversation> list;
        int totalCount;
        if (criteria.byPage()) {
            list = repository.selectByCriteriaPage(criteria, criteria.getPageIndex(), criteria.getPageSize());
            totalCount = repository.selectByCriteriaCount(criteria);
        } else {
            list = repository.selectByCriteria(criteria);
            totalCount = list.size();
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", list);
        resultMap.put("totalCount", totalCount);
        return resultMap;
    }

    public List<Conversation> list(ConversationCriteria criteria) {
        return repository.selectByCriteria(criteria);
    }

    /**
     * 保存
     *
     * @param conversation
     * @param user
     */
    public void save(Conversation conversation, User user) {
        if (StringUtils.isBlank(conversation.getId())) {
            conversation.create(
                    user.getId(),
                    user.getFullname()
            );
            repository.insert(conversation);
        } else {
            Conversation old = repository.selectById(conversation.getId());
            if (old == null)
                throw new ValidationException("历史会话不存在");
            if (!roleService.hasRole(user.getId(), "管理员")) {
                // 非管理员只能修改自己的会话
                if (!old.getUserId().equals(user.getId())) {
                    throw new ValidationException("当前用户无法修改其他用户的会话");
                }
            }
            old.modifyLastChatTime(new Date());
            repository.update(conversation);
        }
    }

    /**
     * 保存对话信息
     *
     * @param chatMessage
     * @param request
     * @param response
     * @param result
     */
    public void saveLine(ChatMessage chatMessage, ChatBaseRequest request, ChatResponse response, String result) {
        Conversation conversation = repository.selectById(chatMessage.getConversationId());
        if (conversation == null) {
            throw new ValidationException("请先创建会话");
        }
        ConversationLine line = null;
        if (request instanceof ChatRequest) {
            ChatRequest chatRequest = (ChatRequest) request;
            line = new ConversationLine(
                    SnowFlake.instant().nextId().toString(),
                    conversation.getId(),
                    chatMessage.getType(),
                    chatMessage.getMessage(),
                    chatRequest.getStream(),
                    chatRequest.getModelName(),
                    chatRequest.getTemperature(),
                    chatRequest.getMaxTokens(),
                    chatRequest.getPromptName(),
                    chatRequest.getHistoryLen(),
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new Date(),
                    result,
                    false,
                    null,
                    response.getAnswer()
            );
        } else if (request instanceof KnowledgeBaseChatRequest) {
            KnowledgeBaseChatRequest knowledgeBaseChatRequest = (KnowledgeBaseChatRequest) request;
            line = new ConversationLine(
                    SnowFlake.instant().nextId().toString(),
                    conversation.getId(),
                    chatMessage.getType(),
                    chatMessage.getMessage(),
                    knowledgeBaseChatRequest.getStream(),
                    knowledgeBaseChatRequest.getModelName(),
                    knowledgeBaseChatRequest.getTemperature(),
                    knowledgeBaseChatRequest.getMaxTokens(),
                    knowledgeBaseChatRequest.getPromptName(),
                    null,
                    null,
                    null,
                    null,
                    null,
                    knowledgeBaseChatRequest.getKnowledgeBaseName(),
                    knowledgeBaseChatRequest.getTopK(),
                    knowledgeBaseChatRequest.getScoreThreshold(),
                    null,
                    new Date(),
                    result,
                    false,
                    null,
                    response.getAnswer()
            );
        }
        if (line != null) {
            conversationLineRepository.insert(line);
        }
    }

    /**
     * @param conversationId
     * @return
     */
    public List<ConversationLine> queryConversationHistory(String conversationId) {
        return queryConversationHistory(conversationId, null);
    }


    /**
     * @param conversationId
     * @param length
     * @return
     */
    public List<ConversationLine> queryConversationHistory(String conversationId, Integer length) {
        ConversationLineCriteria criteria = new ConversationLineCriteria();
        criteria.setConversationId(conversationId);
        List<ConversationLine> list;
        if (length == null) {
            list = conversationLineRepository.selectByCriteria(criteria);
        } else {
            criteria.setPageIndex(1);
            criteria.setPageSize(length);
            list = conversationLineRepository.selectByCriteriaPage(criteria, criteria.getPageIndex(), criteria.getPageSize());
        }
        return list;
    }



    //调用智宇平台信息
    public String queryAnswer(String question) {
        String responseEntity="";
        QuestionRequest questionRequest=new QuestionRequest();
        questionRequest.setKeyword(question);
       // (yyyyMMddHHmmssSSS)+6位随机数;
        Random random = new Random();
        Integer min = 100000; // 最小值（6位起始）
        Integer max = 999999; // 最大值（6位结束）
        // 生成范围：min <= num <= max
        Integer randomNum = random.nextInt(max - min + 1) + min;
        String currentDay = DateTool.format(new Date(), "yyyyMMddHHmmssSSS");
        questionRequest.setRequestId(currentDay+randomNum.toString());
        questionRequest.setDialogId(currentDay+randomNum.toString());
        String paramString = JsonUtils.objectToJson(questionRequest);
        HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.setContentType(MediaType.APPLICATION_JSON_UTF8);
        requestHeader.add("AuthToken", "4009fe23e6b648539792330c14f5ed8e");
        HttpEntity<String> requestEntity = new HttpEntity<String>(paramString, requestHeader);
         responseEntity = restTemplate.postForObject("http://10.32.41.35:40517/scene_gateway/agent/6809d0895428476bb6789ad70c525c97", requestEntity, String.class);
        return responseEntity;
    }


}
