package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sonic.frog.domain.entity.AiUserExt;
import com.sonic.frog.enums.ToastResultCode;
import com.sonic.frog.service.AiUserExtService;
import com.sonic.frog.service.ChatService;
import com.sonic.pigeon.lib.client.ImMessageClient;
import com.sonic.pigeon.lib.input.HistoryMessageInput;
import com.sonic.pigeon.lib.input.SendAiCustomerMessageInput;
import com.sonic.pigeon.lib.input.SendAiTextMessageInput;
import com.sonic.pigeon.lib.output.HistoryMessageOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: mzc
 * @date: 2025-08-29 17:52
 **/
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ImMessageClient imMessageClient;
    @Autowired
    private AiUserExtService aiUserExtService;

    @Override
    public void sendDialoguePrologueMessage(Long aiId, Long userId) {
        AiUserExt aiUserExt = aiUserExtService.getAiUserExtByAiId(aiId);
        ToastResultCode.SYS_PERMISSION_DENIED.check(aiUserExt == null);
        //查看之前有没有发送过消息
        List<HistoryMessageOutput> historyMessageList = getHistoryMessageOutputs(aiId, userId);
        //为空，没发送过才发送
        if (CollectionUtils.isEmpty(historyMessageList)) {
            //发送开场白消息
            SendAiTextMessageInput sendAiTextMessageInput = SendAiTextMessageInput.builder()
                    .fromUserId(aiId)
                    .toUserId(userId)
                    .content(aiUserExt.getDialoguePrologue())
                    .build();
            imMessageClient.sendAiToUserTextMessage(sendAiTextMessageInput);
        }
    }

    /**
     * ai与用户是否已经聊天过
     *
     * @param aiId
     * @param userId
     * @return
     */
    private List<HistoryMessageOutput> getHistoryMessageOutputs(Long aiId, Long userId) {
        HistoryMessageInput historyMessageInput = new HistoryMessageInput();
        historyMessageInput.setFromUserId(aiId);
        historyMessageInput.setToUserId(userId);
        historyMessageInput.setLimit(2);
        historyMessageInput.setDescending(true);
        List<HistoryMessageOutput> historyMessageList = imMessageClient.getAiToUserHistoryMessage(historyMessageInput);
        return historyMessageList;
    }

    @Override
    public Boolean isHaveChatted(Long aiId, Long userId) {
        List<HistoryMessageOutput> historyMessageOutputs = getHistoryMessageOutputs(aiId, userId);
        return CollectionUtils.isNotEmpty(historyMessageOutputs) ? true : false;
    }
}
