package com.fs.his.service.impl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.json.JSONUtil;
import com.fs.aiChat.domain.DoctorAiChatLog;
import com.fs.aiChat.domain.DoctorAiChatMsg;
import com.fs.aiChat.domain.DoctorAiChatSession;
import com.fs.aiChat.mapper.DoctorAiChatLogMapper;
import com.fs.aiChat.param.Message;
import com.fs.aiChat.vo.DoctorAiVO;
import com.fs.common.annotation.Excel;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.fastGpt.config.ModeConfig;
import com.fs.fastGpt.domain.FastGptRole;
import com.fs.fastGpt.service.IFastGptRoleService;
import com.fs.fastgptApi.param.ChatParam;
import com.fs.fastgptApi.result.ChatDetailTStreamFResult;
import com.fs.fastgptApi.service.ChatService;
import com.fs.his.domain.FsDoctor;
import com.fs.his.mapper.DoctorAiChatMsgMapper;
import com.fs.his.mapper.DoctorAiChatSessionMapper;
import com.fs.his.mapper.FsDoctorMapper;
import com.fs.his.service.IHisDoctorAiChatSessionService;
import com.fs.qw.domain.QwExternalContactInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 对话关系Service业务层处理
 *
 * @author fs
 * @date 2024-12-30
 */
@Service
public class DoctorAiChatSessionServiceImpl implements IHisDoctorAiChatSessionService
{
    @Autowired
    private DoctorAiChatSessionMapper doctorAiChatSessionMapper;
    @Autowired
    private DoctorAiChatMsgMapper doctorAiChatMsgMapper;
    @Autowired
    private DoctorAiChatLogMapper doctorAiChatLogMapper;
    @Autowired
    private ChatService chatService;
    @Autowired
    private FsDoctorMapper fsDoctorMapper;

    @Autowired
    private IFastGptRoleService roleService;
    /**
     * 查询对话关系
     *
     * @param sessionId 对话关系主键
     * @return 对话关系
     */
    @Override
    public DoctorAiChatSession selectDoctorAiChatSessionBySessionId(Long sessionId)
    {
        return doctorAiChatSessionMapper.selectDoctorAiChatSessionBySessionId(sessionId);
    }

    @Override
    public List<DoctorAiChatMsg> selectDoctorAiChatSessionListByUser(DoctorAiVO doctorAiChatSession) {
        List<DoctorAiChatMsg> doctorAiChatMsgs = doctorAiChatMsgMapper.selectDoctorAiChatSessionListByUser(doctorAiChatSession);
        return doctorAiChatMsgs;
    }

    /**
     * 查询对话关系列表
     *
     * @param doctorAiChatSession 对话关系
     * @return 对话关系
     */
    @Override
    public List<DoctorAiChatSession> selectDoctorAiChatSessionList(DoctorAiChatSession doctorAiChatSession)
    {
        return doctorAiChatSessionMapper.selectDoctorAiChatSessionList(doctorAiChatSession);
    }

    @Override
    public DoctorAiChatSession selectChatSessionCVOBySessionId(Long sessionId) {
        DoctorAiChatSession doctorAiChatSession = doctorAiChatSessionMapper.selectDoctorAiChatSessionBySessionId(sessionId);
        return doctorAiChatSession;
    }

    /**
     * 新增对话关系
     *
     * @param doctorAiChatSession 对话关系
     * @return 结果
     */
    @Override
    public int insertDoctorAiChatSession(DoctorAiChatSession doctorAiChatSession)
    {
        doctorAiChatSession.setCreateTime(DateUtils.getNowDate());
        return doctorAiChatSessionMapper.insertDoctorAiChatSession(doctorAiChatSession);
    }

    /**
     * 修改对话关系
     *
     * @param doctorAiChatSession 对话关系
     * @return 结果
     */
    @Override
    public int updateDoctorAiChatSession(DoctorAiChatSession doctorAiChatSession)
    {
        doctorAiChatSession.setUpdateTime(DateUtils.getNowDate());
        return doctorAiChatSessionMapper.updateDoctorAiChatSession(doctorAiChatSession);
    }

    /**
     * 批量删除对话关系
     *
     * @param sessionIds 需要删除的对话关系主键
     * @return 结果
     */
    @Override
    public int deleteDoctorAiChatSessionBySessionIds(Long[] sessionIds)
    {
        return doctorAiChatSessionMapper.deleteDoctorAiChatSessionBySessionIds(sessionIds);
    }

    /**
     * 删除对话关系信息
     *
     * @param sessionId 对话关系主键
     * @return 结果
     */
    @Override
    public int deleteDoctorAiChatSessionBySessionId(Long sessionId)
    {
        return doctorAiChatSessionMapper.deleteDoctorAiChatSessionBySessionId(sessionId);
    }

    @Override
    @Transactional
    public String chatByUser(Message message) {
        if (message == null){
            return null;
        }
        if (message.getUserId()==null){
            throw new CustomException("用户id不能为空");
        }
        if (message.getDoctorId()==null){
            throw new CustomException("医生id不能为空");
        }
        DoctorAiChatSession sess = doctorAiChatSessionMapper.selectDoctorAiChatSessionByUserIdAndPatIdAndDoctorId(message.getUserId(), message.getPatientId(), message.getDoctorId());
        if (sess==null){
            //创建会话
            DoctorAiChatSession doctorAiChatSession = new DoctorAiChatSession();
            doctorAiChatSession.setUserId(message.getUserId());
            doctorAiChatSession.setDoctorId(message.getDoctorId());
            doctorAiChatSession.setStatus(1);
            doctorAiChatSession.setPatientId(message.getPatientId());
            doctorAiChatSession.setIsLook(1);
            doctorAiChatSession.setUserType(4);
            doctorAiChatSession.setCreateTime(DateUtils.getNowDate());
            doctorAiChatSessionMapper.insertDoctorAiChatSession(doctorAiChatSession);
            message.setSessionId(doctorAiChatSession.getSessionId());
        }else {
            message.setSessionId(sess.getSessionId());
        }

        DoctorAiChatMsg doctorAiChatMsg = new DoctorAiChatMsg();
        doctorAiChatMsg.setSessionId(message.getSessionId());
        doctorAiChatMsg.setUserId(message.getUserId());
        doctorAiChatMsg.setPatientId(message.getPatientId());
        doctorAiChatMsg.setDoctorId(message.getDoctorId());
        doctorAiChatMsg.setContent(message.getMessage());
        doctorAiChatMsg.setCreateTime(DateUtils.getNowDate());
        doctorAiChatMsg.setMsgType(1);
        doctorAiChatMsg.setStatus(0);
        doctorAiChatMsg.setUserType(4);
        doctorAiChatMsgMapper.insertDoctorAiChatMsg(doctorAiChatMsg);
        //将对话发送给ai获得回复

        String aiMsg = getAiMsg(doctorAiChatMsg);

        DoctorAiChatMsg doctorAiChatMsgByai = new DoctorAiChatMsg();
        doctorAiChatMsgByai.setSessionId(message.getSessionId());
        doctorAiChatMsgByai.setUserId(message.getUserId());
        doctorAiChatMsgByai.setDoctorId(message.getDoctorId());
        doctorAiChatMsgByai.setContent(aiMsg);
        doctorAiChatMsgByai.setPatientId(message.getPatientId());
        doctorAiChatMsgByai.setCreateTime(DateUtils.getNowDate());
        //ai发送
        doctorAiChatMsgByai.setMsgType(2);
        doctorAiChatMsgByai.setStatus(0);
        doctorAiChatMsgMapper.insertDoctorAiChatMsg(doctorAiChatMsgByai);
        //对话记录
        DoctorAiChatLog doctorAiChatLog = new DoctorAiChatLog();
        doctorAiChatLog.setLogsType(1);
        doctorAiChatLog.setContent(message.getMessage());
        doctorAiChatLog.setMsgId(doctorAiChatMsg.getMsgId());
        doctorAiChatLog.setAiContent(aiMsg);
        doctorAiChatLogMapper.insertDoctorAiChatLog(doctorAiChatLog);
        return aiMsg;
    }

    private String getAiMsg(DoctorAiChatMsg doctorAiChatMsg) {
        ChatParam param=new ChatParam();
        param.setChatId(doctorAiChatMsg.getSessionId().toString());
        param.setStream(false);
        param.setDetail(true);
        ChatParam.Variables variables=new ChatParam.Variables();
        Long doctorId = doctorAiChatMsg.getDoctorId();
        FsDoctor doctor = fsDoctorMapper.selectFsDoctorByDoctorId(doctorId);
        if (doctor==null){
            return "请联系医生";
        }
        variables.setUid(doctorId.toString());
        variables.setName(doctor.getDoctorName());
        param.setVariables(variables);
        List<ChatParam.Message> messageList=new ArrayList<ChatParam.Message>();
        param.setMessages(messageList);
        FastGptRole role=roleService.selectFastGptRoleByRoleId(doctor.getGptRoleId());
        if (role==null){
            return "请联系医生配置Ai";
        }
        String modeConfig=role.getModeConfigJson();
        if(modeConfig==null||modeConfig.equals("")){
            return "请联系医生配置AiKey";
        }
        ModeConfig config= JSONUtil.toBean(modeConfig,ModeConfig.class);
        addAiDoctorPromptWord(messageList,doctorAiChatMsg.getContent(),role.getReminderWords());
        R r = chatService.initiatingTakeChat(param,"http://154.8.194.176:3000/api",config.getAPPKey());
        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 void addAiDoctorPromptWord(List<ChatParam.Message> messageList,String count,String words){
        String  str="";
        QwExternalContactInfo info = new QwExternalContactInfo();
        str="【用户状态信息\n";
        Field[] fields = info.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Excel annotation = field.getAnnotation(Excel.class);
            if (annotation != null) {
                String name = field.getName();
                String fieldName = annotation.name();
                String[] split = "".split(",");
                for (String zName : split) {

                    if (zName.equals(name)) {
                        Object value = null;
                        try {
                            value = field.get(info);
                        } catch (IllegalAccessException e) {
                        }
                        if (value != null) {
                            str += fieldName + ": " + value.toString() + "\n";
                        }else {
                            str += fieldName + ":  \n";
                        }
                    }
                }
            }
        }

        str+="】\n";
        if (words!=null&&!"".equals(words)){
            str+="【你的角色信息：以下内容为你的信息状态的补充而非用户信息，相当于放在角色任务里面，问到了需要知晓，但是如果无关的时候请无视此段内容 "+words+"】\n";
        }
        if (count!=null&&!"".equals(count)){
            str+="【用户说的话内容（之前的内容仅仅为背景，你知道即可，以下才是用户真实说的话的内容）\n" +
                    count+"\n" +
                    "】";
        }
        ChatParam.Message message1=new ChatParam.Message();
        message1.setRole("user");
        message1.setContent(str);
        messageList.add(message1);
        System.out.println("用户ai输入："+str);
    }
    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("");
    }
}
