package com.fs.his.service.impl;

import com.fs.aiChat.domain.InterestAiChatMsg;
import com.fs.aiChat.domain.InterestAiSession;
import com.fs.aiChat.domain.SessionRoleInfo;
import com.fs.aiChat.mapper.InterestAiChatSessionMapper;
import com.fs.aiChat.param.InterestAiMessage;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.fastgptApi.param.ChatParam;
import com.fs.fastgptApi.result.ChatDetailTStreamFResult;
import com.fs.fastgptApi.service.ChatService;
import com.fs.his.domain.FsInterestAiMsg;
import com.fs.his.domain.FsInterestAiRole;
import com.fs.his.domain.FsInterestAiSession;
import com.fs.his.mapper.FsInterestAiSessionMapper;
import com.fs.his.service.IHisInterestAiChatSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class InterestAiChatSessionServiceImpl implements IHisInterestAiChatSessionService {

    @Autowired
    FsInterestAiSessionMapper fsInterestAiSessionMapper;

//    @Autowired
//    FsInterestAiRoleMapper fsInterestAiRoleMapper;
//
//    @Autowired
//    FsInterestAiRoleWordsMapper fsInterestAiRoleWordsMapper;

    @Autowired
    InterestAiChatSessionMapper interestAiChatSessionMapper;

//    @Autowired
//    FsInterestAiMsgMapper fsInterestAiMsgMapper;

    @Autowired
    private ChatService chatService;


    /**
     * 根据当前用户获取用户的会话列表
     *
     * @param session
     * @return
     */
    @Override
    public List<InterestAiSession> getAllRolesListByUserId(InterestAiSession session) {

        Long userId = session.getUserId();

        List<InterestAiSession> list = interestAiChatSessionMapper.getSessionListByUserId(userId);

        return list;
    }


    /**
     * 根据角色id获取会话角色信息
     *
     * @param roleId
     * @return
     */
    @Override
    public SessionRoleInfo getSessionRoleInfoByRoleId(Long roleId) {
        SessionRoleInfo sessionRoleInfoByRoleId = interestAiChatSessionMapper.getSessionRoleInfoByRoleId(roleId);
        return sessionRoleInfoByRoleId;
    }

    /**
     * 根据会话id获取会话聊天记录
     *
     * @param sessionId
     * @return
     */
    @Override
    public List<InterestAiChatMsg> getSessionChatList(String sessionId) {
        List<InterestAiChatMsg> list = interestAiChatSessionMapper.getSessionChatList(sessionId);
        return list;
    }

    /**
     * 创建会话
     *
     * @param fsInterestAiSession
     * @return
     */
    @Override
    public FsInterestAiSession createSession(FsInterestAiSession fsInterestAiSession) {
        fsInterestAiSession.setCreateTime(DateUtils.getNowDate());
        fsInterestAiSession.setStatus(1);
        int sessionId = fsInterestAiSessionMapper.insertFsInterestAiSession(fsInterestAiSession);
        return fsInterestAiSession;
    }

    /**
     * 用户对话
     *
     * @param message
     * @return
     */
    @Override
    @Transactional
    public String chatByUser(InterestAiMessage message) {
        //判断message是否为空
        if (message == null) {
            return null;
        }

        if (null == message.getUserId()) {
            throw new CustomException("用户id不能为空");
        }

        if (null == message.getRoleId()) {
            throw new CustomException("角色id不能为空");
        }

        FsInterestAiSession session = interestAiChatSessionMapper.getInterestAiSessionByRoleIdAndUserId(message.getRoleId(), message.getUserId());
        // 对话构建
        if (null == session) {
            FsInterestAiSession fsInterestAiSession = new FsInterestAiSession();
            fsInterestAiSession.setCreateTime(DateUtils.getNowDate());
            fsInterestAiSession.setStatus(1);
            fsInterestAiSession.setRoleId(message.getRoleId());
            fsInterestAiSession.setRoleName(message.getRoleName());
            fsInterestAiSession.setUserId(message.getUserId());
            fsInterestAiSession.setNickName(message.getNickName());
            fsInterestAiSession.setAvatar(message.getAvatar());
            fsInterestAiSession.setChatId(UUID.randomUUID().toString());
            interestAiChatSessionMapper.insertFsInterestAiSession(fsInterestAiSession);
            message.setSessionId(fsInterestAiSession.getSessionId());
        } else {
            message.setSessionId(session.getSessionId());
        }

        //写入聊天记录
        FsInterestAiMsg fsInterestAiMsg = new FsInterestAiMsg();
        fsInterestAiMsg.setSessionId(message.getSessionId());
        fsInterestAiMsg.setUserId(message.getUserId().toString());
        fsInterestAiMsg.setContent(message.getMessage());
        fsInterestAiMsg.setSendType(1);
        fsInterestAiMsg.setRoleId(message.getRoleId());
        fsInterestAiMsg.setRoleName(message.getRoleName());
        fsInterestAiMsg.setCreateTime(DateUtils.getNowDate());
        fsInterestAiMsg.setNickName(message.getNickName());
        fsInterestAiMsg.setAvatar(message.getAvatar());
//        fsInterestAiMsgMapper.insertFsInterestAiMsg(fsInterestAiMsg);
        interestAiChatSessionMapper.insertFsInterestAiMsg(fsInterestAiMsg);

        String aiMsg = getAiMsg(fsInterestAiMsg);

        FsInterestAiMsg aiReceiveMsg = new FsInterestAiMsg();
        aiReceiveMsg.setSessionId(message.getSessionId());
        aiReceiveMsg.setUserId(message.getUserId().toString());
        aiReceiveMsg.setContent(aiMsg);
        aiReceiveMsg.setSendType(2);
        aiReceiveMsg.setRoleId(message.getRoleId());
        aiReceiveMsg.setRoleName(message.getRoleName());
        aiReceiveMsg.setCreateTime(DateUtils.getNowDate());
        aiReceiveMsg.setNickName(message.getNickName());
        aiReceiveMsg.setAvatar(message.getAvatar());
        interestAiChatSessionMapper.insertFsInterestAiMsg(aiReceiveMsg);

        return aiMsg;
    }


    private String getAiMsg(FsInterestAiMsg fsInterestAiMsg) {
        ChatParam param = new ChatParam();
        param.setChatId(fsInterestAiMsg.getSessionId().toString());
        param.setStream(false);
        param.setDetail(true);
        ChatParam.Variables variables = new ChatParam.Variables();
        Long roleId = fsInterestAiMsg.getRoleId();
        FsInterestAiRole role = interestAiChatSessionMapper.selectFsInterestAiRoleByRoleId(roleId);
        if (null == role) {
            return "请联系管理员";
        }
        variables.setUid(roleId.toString());
        variables.setName(role.getRoleName());
        param.setVariables(variables);
        List<ChatParam.Message> messageList = new ArrayList<ChatParam.Message>();
        ChatParam.Message message1=new ChatParam.Message();
        message1.setRole("user");
        message1.setContent(fsInterestAiMsg.getContent());
        messageList.add(message1);
        param.setMessages(messageList);
//        FastGptRole role = roleService.selectFastGptRoleByRoleId(doctor.getGptRoleId());
        if (role == null) {
            return "请联系配置Ai角色";
        }
        String appKey = role.getAppKey();
//        if (modeConfig == null || modeConfig.equals("")) {
//            return "请联系配置AiKey";
//        }
//        ModeConfig config = JSONUtil.toBean(modeConfig, ModeConfig.class);
//        addAiDoctorPromptWord(messageList, fsInterestAiMsg.getContent(), role.getReminderWords());
        R r = chatService.initiatingTakeChat(param, "http://154.8.194.176:3000/api", appKey);
        if (r.get("code").equals(200)) {
            ChatDetailTStreamFResult result = (ChatDetailTStreamFResult) r.get("data");
            String count = replace(result.getChoices().get(0).getMessage().getContent()).trim();
            return count;
        } else {
            return "请稍后再试";
        }


    }
    private static String replace(String s){
        if(org.springframework.util.StringUtils.isEmpty(s)) return "";
        String regex = "【[\\s\\S]*?】";
        // 创建 Pattern 对象
        Pattern pattern = Pattern.compile(regex);
        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(s);
        // 替换匹配到的内容
        return matcher.replaceAll("");
    }


    /**
     * 获取推荐角色列表
     * @return
     */
    @Override
    public List<SessionRoleInfo> getRecommendRoleList(String userId) {
        List<SessionRoleInfo>  roleList =  interestAiChatSessionMapper.getRecommendRoleList(userId);
        return roleList;
    }
}
