package com.fs.fastGpt.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.Excel;
import com.fs.common.annotation.RateLimiter;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.DateUtils;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.service.IFsCourseLinkService;
import com.fs.fastGpt.config.ModeConfig;
import com.fs.fastGpt.domain.FastGptChatMsg;
import com.fs.fastGpt.domain.FastGptChatSession;
import com.fs.fastGpt.domain.FastGptRole;
import com.fs.fastGpt.mapper.FastGptChatSessionMapper;
import com.fs.fastGpt.mapper.FastgptChatVoiceHomoMapper;
import com.fs.fastGpt.param.FastGptChatSessionParam;
import com.fs.fastGpt.param.SendHookAIParam;
import com.fs.fastGpt.service.IFastGptChatMsgService;
import com.fs.fastGpt.service.IFastGptChatSessionService;
import com.fs.fastGpt.service.IFastGptRoleService;
import com.fs.fastGpt.vo.FastGptChatSessionCVO;
import com.fs.fastGpt.vo.FastGptChatSessionListCVO;
import com.fs.fastgptApi.param.ChatParam;
import com.fs.fastgptApi.result.ChatDetailTStreamFResult;
import com.fs.fastgptApi.service.ChatService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwExternalContactInfo;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwExternalContactInfoMapper;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.IQwContactWayService;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwJsApiService;
import com.fs.qw.service.IQwUserService;
import com.fs.qwApi.service.QwApiService;
import com.fs.qwHookApi.param.QwHookSendMsgParam;
import com.fs.qwHookApi.vo.QwHookMsgVO;
import com.fs.sop.domain.QwSopLogs;
import com.fs.sop.mapper.QwSopLogsMapper;
import com.fs.sop.service.IQwSopLogsService;
import com.fs.sop.service.impl.QwSopLogsServiceImpl;
import com.fs.sop.vo.QwSopLogsDoSendListTVO;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 对话关系Service业务层处理
 *
 * @author fs
 * @date 2024-10-10
 */
@Service
public class FastGptChatSessionServiceImpl implements IFastGptChatSessionService
{
   private static final Logger log = LoggerFactory.getLogger(FastGptChatSessionServiceImpl.class);
    @Autowired
    private FastGptChatSessionMapper fastGptChatSessionMapper;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private QwUserMapper qwUserMapper;
    @Autowired
    private IQwSopLogsService qwSopLogsService;
    @Autowired
    private QwExternalContactInfoMapper qwExternalContactInfoMapper;
    @Autowired
    private IQwExternalContactService qwExternalContactService;
    @Autowired
    private IFastGptRoleService roleService;
    @Autowired
    private ChatService chatService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IFastGptChatMsgService fastGptChatMsgService;

    @Autowired
    private QwSopLogsMapper qwSopLogsMapper;

    @Autowired
    QwApiService qwApiService;
    @Autowired
    QwCompanyMapper qwCompanyMapper;
    @Autowired
    FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    FsUserCourseVideoMapper fsUserCourseVideoMapper;
    @Autowired
    FsCourseWatchLogMapper   watchLogMapper;
    @Autowired
    IQwJsApiService qwGetJsapiTicketService;

    @Autowired
    FastgptChatVoiceHomoMapper fastgptChatVoiceHomoMapper;
    @Autowired
    RedisCache redisCache;
    @Autowired
    private IQwUserService qwUserService;

    /**
     * 查询对话关系
     *
     * @param sessionId 对话关系主键
     * @return 对话关系
     */
    @Override
    public FastGptChatSession selectFastGptChatSessionBySessionId(Long sessionId)
    {
        return fastGptChatSessionMapper.selectFastGptChatSessionBySessionId(sessionId);
    }

    /**
     * 查询对话关系列表
     *
     * @param fastGptChatSession 对话关系
     * @return 对话关系
     */
    @Override
    public List<FastGptChatSession> selectFastGptChatSessionList(FastGptChatSession fastGptChatSession)
    {
        return fastGptChatSessionMapper.selectFastGptChatSessionList(fastGptChatSession);
    }

    /**
     * 新增对话关系
     *
     * @param fastGptChatSession 对话关系
     * @return 结果
     */
    @Override
    public int insertFastGptChatSession(FastGptChatSession fastGptChatSession)
    {
        fastGptChatSession.setCreateTime(DateUtils.getNowDate());
        return fastGptChatSessionMapper.insertFastGptChatSession(fastGptChatSession);
    }

    /**
     * 修改对话关系
     *
     * @param fastGptChatSession 对话关系
     * @return 结果
     */
    @Override
    public int updateFastGptChatSession(FastGptChatSession fastGptChatSession)
    {
        fastGptChatSession.setUpdateTime(DateUtils.getNowDate());
        return fastGptChatSessionMapper.updateFastGptChatSession(fastGptChatSession);
    }

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

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

    @Override
    public List<FastGptChatSessionListCVO> selectFastGptChatSessionListCVO(FastGptChatSessionParam param) {
        return fastGptChatSessionMapper.selectFastGptChatSessionListCVO(param);
    }

    @Override
    public FastGptChatSessionCVO selectFastGptChatSessionCVOBySessionId(Long sessionId) {
        FastGptChatSession map = new FastGptChatSession();
        map.setSessionId(sessionId);
        map.setIsLook(1L);
        fastGptChatSessionMapper.updateFastGptChatSession(map);

        return fastGptChatSessionMapper.selectFastGptChatSessionCVOBySessionId(sessionId);
    }
    @Async
    @Override
    public void sendAiTouch(QwSopLogsDoSendListTVO log,String CorpId) {
        String externalUserId = log.getExternalUserId();
        String qwUserid = log.getQwUserid();
        QwUser user=qwUserMapper.selectQwUserByQwUseridAndCorpId(qwUserid,CorpId);
        QwExternalContact qwExternalContacts = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(externalUserId, CorpId,qwUserid);
        if(user!=null&&qwExternalContacts!=null){
            FastGptChatSession ss = fastGptChatSessionMapper.selectFastGptChatSessionByQwExternalContactsAndUserId(qwExternalContacts.getId(), user.getId());
            QwExternalContactInfo info = qwExternalContactInfoMapper.selectQwExternalContactInfoByExternalContactId(qwExternalContacts.getId());
            JSONObject jsonObject = JSON.parseObject(log.getContentJson());
            String msg = (String)jsonObject.get("aiTouch");
            if (info!=null){
                QwExternalContactInfo extInfo = new QwExternalContactInfo();
                extInfo.setTalk(msg);
                extInfo.setId(info.getId());
                qwExternalContactInfoMapper.updateQwExternalContactInfo(extInfo);
            }else {
                QwExternalContactInfo extInfo = new QwExternalContactInfo();
                extInfo.setTalk(msg);
                extInfo.setExternalContactId(qwExternalContacts.getId());
                extInfo.setCreateTime(new Date());
                qwExternalContactInfoMapper.insertQwExternalContactInfo(extInfo);
            }
            QwSopLogs qwSopLogs=new QwSopLogs();
            qwSopLogs.setId(log.getId());
            qwSopLogs.setSendStatus(1L);
            qwSopLogsService.updateQwSopLogsSendType(qwSopLogs);
            if (ss!=null){
                if (msg!=null&&msg.contains("交流状态")){
                    ChatParam param=new ChatParam();
                    param.setChatId(ss.getChatId());
                    param.setStream(false);
                    param.setDetail(true);
                    ChatParam.Variables variables=new ChatParam.Variables();
                    variables.setUid(ss.getKfId().toString());
                    variables.setName("test");
                    param.setVariables(variables);
                    List<ChatParam.Message> messageList=new ArrayList<ChatParam.Message>();
                    param.setMessages(messageList);
                    FastGptRole role=roleService.selectFastGptRoleByRoleId(Long.parseLong(ss.getKfId()) );
                    String modeConfig=role.getModeConfigJson();
                    ModeConfig config=JSONUtil.toBean(modeConfig,ModeConfig.class);
                    addPromptWord(messageList,"用户触达了",ss.getQwExtId(),role.getReminderWords(), role.getContactInfo());
                    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();
                        QwHookSendMsgParam sendMsgParam=new QwHookSendMsgParam();
                        QwHookSendMsgParam.QwHookSendMsgData sendMsgData=new QwHookSendMsgParam.QwHookSendMsgData();
                        sendMsgParam.setType(101003);
                        sendMsgData.setMsg(count);
                        sendMsgData.setSendId(ss.getUserId());
                        sendMsgData.setSyncKey("1");
                        sendMsgParam.setData(sendMsgData);
                        SendHookAIParam sendAIParam = new SendHookAIParam();
                        sendAIParam.setCmd("aiReplyMsg");
                        sendAIParam.setData(JSONUtil.toJsonStr(sendMsgParam));
                        sendAIParam.setKey(user.getAppKey());
                        redisTemplate.opsForList().leftPush("AiMsg:"+user.getAppKey(), JSON.toJSONString(sendAIParam));
                        FastGptChatSession fastGptChatSession = new FastGptChatSession();
                        fastGptChatSession.setSessionId(ss.getSessionId());
                        fastGptChatSession.setRemindCount(0);
                        fastGptChatSession.setRemindStatus(1);
                        Calendar calendar = Calendar.getInstance(); // 获取当前时间
                        calendar.add(Calendar.MINUTE, 30); // 增加30分钟
                        fastGptChatSession.setRemindTime(calendar.getTime());
                        fastGptChatSessionMapper.updateFastGptChatSession(fastGptChatSession);
                        FastGptChatMsg fastGptChatMsg = new FastGptChatMsg();
                        fastGptChatMsg.setContent(count);
                        fastGptChatMsg.setSessionId(fastGptChatSession.getSessionId());
                        fastGptChatMsg.setRoleId(role.getRoleId());
                        fastGptChatMsg.setSendType(1);
                        fastGptChatMsg.setCompanyId(user.getCompanyId());
                        fastGptChatMsg.setCompanyUserId(user.getCompanyUserId());
                        fastGptChatMsg.setUserType(1);
                        fastGptChatMsg.setMsgType(1);
                        fastGptChatMsg.setStatus(0);
                        fastGptChatMsg.setUserId(qwExternalContacts.getId().toString());
                        fastGptChatMsg.setAvatar(qwExternalContacts.getAvatar());
                        fastGptChatMsg.setNickName(qwExternalContacts.getName());
                        fastGptChatMsg.setCreateTime(new Date());
                        fastGptChatMsg.setExtId(qwExternalContacts.getExternalUserId());
                        fastGptChatMsgService.insertFastGptChatMsg(fastGptChatMsg);
                        addUserInfo(result.getChoices().get(0).getMessage().getContent(), ss.getQwExtId(),ss);
                    }

                }
        }



        }

    }

    @Async
    @Override
    public void addAiMsgBySopByStatus(String id) {
        QwSopLogs msgVO = qwSopLogsMapper.selectQwSopLogsById(id);
        if (msgVO!=null){
                QwExternalContact qwExternalContact = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(msgVO.getExternalUserId(), msgVO.getCorpId(), msgVO.getQwUserid());
                if (qwExternalContact!=null){
                    if (qwExternalContact.getQwUserId()!=null){
                        QwUser qwUser = qwUserMapper.selectQwUserById(qwExternalContact.getQwUserId());
                        if (qwUser!=null&&qwUser.getFastGptRoleId()!=null){
                            FastGptChatSession fastGptChatSession = fastGptChatSessionMapper.selectFastGptChatSessionByQwExternalContactsAndUserId(qwExternalContact.getId(), qwUser.getId());
                            if (fastGptChatSession==null){
                                fastGptChatSession = new FastGptChatSession();
                                String chatId = UUID.randomUUID().toString();
                                fastGptChatSession.setChatId(chatId);
                                fastGptChatSession.setKfId(qwUser.getFastGptRoleId().toString());
                                fastGptChatSession.setStatus(0);
                                fastGptChatSession.setRemindCount(0);
                                fastGptChatSession.setRemindStatus(0);
                                fastGptChatSession.setCreateTime(new Date());
                                fastGptChatSession.setQwExtId(qwExternalContact.getId());
                                fastGptChatSession.setQwUserId(qwUser.getId());
                                fastGptChatSession.setIsArtificial(0);
                                fastGptChatSession.setAvatar(qwExternalContact.getAvatar());
                                fastGptChatSession.setNickName(qwExternalContact.getName());
                                fastGptChatSession.setCompanyId(qwUser.getCompanyId());
                                fastGptChatSessionMapper.insertFastGptChatSession(fastGptChatSession);
                                QwExternalContactInfo info = qwExternalContactInfoMapper.selectQwExternalContactInfoByExternalContactId(qwExternalContact.getId());
                                if (qwExternalContact.getGender()!=0){
                                    if (info!=null){
                                        info.setSex(qwExternalContact.getGender()==1?"男":"女");
                                        qwExternalContactInfoMapper.updateQwExternalContactInfo(info);
                                    }else {
                                        QwExternalContactInfo qwExternalContactInfo = new QwExternalContactInfo();
                                        qwExternalContactInfo.setExternalContactId(qwExternalContact.getId());
                                        qwExternalContactInfo.setSex(qwExternalContact.getGender()==1?"男":"女");
                                        qwExternalContactInfo.setCreateTime(new Date());
                                        qwExternalContactInfoMapper.insertQwExternalContactInfo(qwExternalContactInfo);
                                    }
                                }
                            }
                            FastGptChatMsg fastGptChatMsg = new FastGptChatMsg();
                            fastGptChatMsg.setContent(msgVO.getContentJson());
                            fastGptChatMsg.setSessionId(fastGptChatSession.getSessionId());
                            fastGptChatMsg.setSendType(3);
                            fastGptChatMsg.setCompanyId(qwUser.getCompanyId());
                            fastGptChatMsg.setCompanyUserId(qwUser.getCompanyUserId());
                            fastGptChatMsg.setUserType(1);
                            fastGptChatMsg.setMsgType(1);
                            fastGptChatMsg.setStatus(0);
                            fastGptChatMsg.setExtId(qwExternalContact.getExternalUserId());
                            fastGptChatMsg.setUserId(qwExternalContact.getId().toString());
                            fastGptChatMsg.setAvatar(qwExternalContact.getAvatar());
                            fastGptChatMsg.setNickName(qwExternalContact.getName());
                            fastGptChatMsg.setCreateTime(new Date());
                            fastGptChatMsgService.insertFastGptChatMsg(fastGptChatMsg);
                        }
                    }
                }
            }

    }
    @Override
    public Integer selectFastGptChatSessionArtificialType(FastGptChatSessionParam sessionParam) {
        QwUser qwUser = qwExternalContactService.getQwUserByRedis(sessionParam.getCorpId().trim(), sessionParam.getQwUserId().trim());
        if(qwUser != null && qwUser.getId() != null){
            FastGptChatSession chatSession = fastGptChatSessionMapper.selectFastGptChatSessionByQwExternalContactsAndUserId(sessionParam.getQwExtId(), qwUser.getId());
            if(chatSession != null && chatSession.getIsArtificial() != null){
                return chatSession.getIsArtificial();
            }else{
                return null;
            }
        }
        return null;
    }

    @Override
    public void qwHookNotifyAddMsg(QwHookMsgVO vo) {
        QwUser sendUser=qwUserService.selectQwUserByAppKey(vo.getKey());
        if (sendUser!=null){
            FastGptChatSession fastGptChatSession = fastGptChatSessionMapper.selectFastGptChatSessionByUserIdAndKfId(vo.getReceiver(), sendUser.getId());
            if (fastGptChatSession!=null){
                saveQwUserMsg(fastGptChatSession,2,vo.getContent());
            }else {
                QwExternalContact qwExternalContacts = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(vo.getReceiver_openid(), sendUser.getCorpId(),sendUser.getQwUserId());
                if(qwExternalContacts!=null&&qwExternalContacts.getType()!=null&&qwExternalContacts.getType()==1){
                    if(sendUser.getFastGptRoleId()!=null){
                        fastGptChatSession = new FastGptChatSession();
                        String chatId = UUID.randomUUID().toString();
                        fastGptChatSession.setChatId(chatId);
                        fastGptChatSession.setUserId(vo.getReceiver());
                        fastGptChatSession.setKfId(sendUser.getFastGptRoleId().toString());
                        fastGptChatSession.setStatus(1);
                        fastGptChatSession.setRemindCount(0);
                        fastGptChatSession.setRemindStatus(1);
                        fastGptChatSession.setCreateTime(new Date());
                        fastGptChatSession.setQwExtId(qwExternalContacts.getId());
                        fastGptChatSession.setQwUserId(sendUser.getId());
                        Calendar calendar = Calendar.getInstance(); // 获取当前时间
                        calendar.add(Calendar.MINUTE, 30); // 增加30分钟
                        fastGptChatSession.setRemindTime(calendar.getTime());
                        fastGptChatSession.setIsArtificial(0);
                        fastGptChatSession.setAvatar(qwExternalContacts.getAvatar());
                        fastGptChatSession.setNickName(qwExternalContacts.getName());
                        fastGptChatSession.setCompanyId(sendUser.getCompanyId());
                        fastGptChatSession.setLastTime(new Date());
                        fastGptChatSession.setIsReply(0);
                        fastGptChatSessionMapper.insertFastGptChatSession(fastGptChatSession);
                        addUserSex(qwExternalContacts);
                        saveQwUserMsg(fastGptChatSession,2,vo.getContent());
                    }
                }
            }
        }
    }
//
//    @Async
//    @Override
//    public void addAiMsgBySop(List<QwSopLogsDoSendListTVO> sendJsApiList,String corpId) {
//        for (QwSopLogsDoSendListTVO msgVO : sendJsApiList) {
//            log.info("开始添加聊天记录:"+msgVO.getContentJson());
//            QwExternalContact qwExternalContact = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(msgVO.getExternalUserId(), corpId, msgVO.getQwUserid());
//
//            if (qwExternalContact!=null){
//                log.info("外部联系人："+qwExternalContact.getName());
//                if (qwExternalContact.getQwUserId()!=null){
//                    QwUser qwUser = qwUserMapper.selectQwUserById(qwExternalContact.getQwUserId());
//                    log.info("企微用户:"+qwUser);
//                    if (qwUser!=null&&qwUser.getFastGptRoleId()!=null){
//                        log.info("企微客服:"+qwUser.getFastGptRoleId());
//                        FastGptChatSession fastGptChatSession = fastGptChatSessionMapper.selectFastGptChatSessionByQwExternalContactsAndUserId(qwExternalContact.getId(), qwExternalContact.getQwUserId());
//                        if (fastGptChatSession==null){
//                            log.info("新增session");
//                            fastGptChatSession = new FastGptChatSession();
//                            String chatId = UUID.randomUUID().toString();
//                            fastGptChatSession.setChatId(chatId);
//                            fastGptChatSession.setKfId(qwUser.getFastGptRoleId().toString());
//                            fastGptChatSession.setStatus(0);
//                            fastGptChatSession.setRemindCount(0);
//                            fastGptChatSession.setRemindStatus(0);
//                            fastGptChatSession.setCreateTime(new Date());
//                            fastGptChatSession.setQwExtId(qwExternalContact.getId());
//                            fastGptChatSession.setQwUserId(qwUser.getId());
//                            fastGptChatSession.setIsArtificial(0);
//                            fastGptChatSession.setAvatar(qwExternalContact.getAvatar());
//                            fastGptChatSession.setNickName(qwExternalContact.getName());
//                            fastGptChatSession.setCompanyId(qwUser.getCompanyId());
//                            fastGptChatSessionMapper.insertFastGptChatSession(fastGptChatSession);
//                            log.info("新增session完成");
//                            QwExternalContactInfo info = qwExternalContactInfoMapper.selectQwExternalContactInfoByExternalContactId(qwExternalContact.getId());
//                            if (qwExternalContact.getGender()!=0){
//                                if (info!=null){
//                                    info.setSex(qwExternalContact.getGender()==1?"男":"女");
//                                    qwExternalContactInfoMapper.updateQwExternalContactInfo(info);
//                                }else {
//                                    QwExternalContactInfo qwExternalContactInfo = new QwExternalContactInfo();
//                                    qwExternalContactInfo.setExternalContactId(qwExternalContact.getId());
//                                    qwExternalContactInfo.setSex(qwExternalContact.getGender()==1?"男":"女");
//                                    qwExternalContactInfoMapper.insertQwExternalContactInfo(qwExternalContactInfo);
//                                }
//                            }
//
//                        }
//                        FastGptChatMsg fastGptChatMsg = new FastGptChatMsg();
//                        fastGptChatMsg.setContent(msgVO.getContentJson());
//                        fastGptChatMsg.setSessionId(fastGptChatSession.getSessionId());
//                        fastGptChatMsg.setSendType(3);
//                        fastGptChatMsg.setCompanyId(qwUser.getCompanyId());
//                        fastGptChatMsg.setCompanyUserId(qwUser.getCompanyUserId());
//                        fastGptChatMsg.setUserType(1);
//                        fastGptChatMsg.setMsgType(1);
//                        fastGptChatMsg.setStatus(0);
//                        fastGptChatMsg.setExtId(qwExternalContact.getExternalUserId());
//                        fastGptChatMsg.setUserId(qwExternalContact.getId().toString());
//                        fastGptChatMsg.setAvatar(qwExternalContact.getAvatar());
//                        fastGptChatMsg.setNickName(qwExternalContact.getName());
//                        fastGptChatMsg.setCreateTime(new Date());
//                        fastGptChatMsgService.insertFastGptChatMsg(fastGptChatMsg);
//                        log.info("聊天记录新增完成:");
//                    }
//                }
//
//            }
//
//        }
//    }




    private void addPromptWord(List<ChatParam.Message> messageList, String count, Long extId, String words, String countInfo){
        // 这里获取后台的提示词进行匹配
        QwExternalContactInfo info = qwExternalContactInfoMapper.selectQwExternalContactInfoByExternalContactId(extId);
        if(info==null){
            info=new QwExternalContactInfo();
        }
        String  str="";
        if (info!=null){
            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 = countInfo.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.setDataId("66f8ef2f6d4b94fbb4f5d40d");
        message1.setContent(str);
        System.out.println(str);
        messageList.add(message1);

    }
    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("");
    }
    private void addUserInfo(String word,Long extId,FastGptChatSession fastGptChatSession)  {
        Pattern pattern = Pattern.compile("【用户状态信息(.*?)】", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(word);
        while  (matcher.find()) {
            String trim = matcher.group(1).trim();
            String[] zd = trim.split("\n");
            boolean b=false;

            QwExternalContactInfo info = qwExternalContactInfoMapper.selectQwExternalContactInfoByExternalContactId(extId);
            if (info==null){
                info=new QwExternalContactInfo();
                b=true;
            }
            Field[] fields = info.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Excel annotation = field.getAnnotation(Excel.class);
                if (annotation != null) {
                    //中文名称
                    String fieldName = annotation.name();
                    String valueName ="";
                    Object value = null;
                    try {
                        value = field.get(info);
                    } catch (IllegalAccessException e) {
                    }
                    if (value != null) {
                        valueName= value.toString();
                    }
                    for (String s : zd) {
                        String[] zdName=null;
                        if (s.contains(":")){
                            zdName = s.split(":");
                        }
                        if (s.contains("：")){
                            zdName = s.split("：");
                        }
                        if (zdName!=null&&zdName.length==2){
                            String name1 = zdName[0];
                            String name2 = zdName[1];
                            if (name1.trim().equals(fieldName)){
                                String name2Trim = name2.trim();
                                if (!name2Trim.isEmpty()){
                                    if(name1.equals("交流状态")){
                                        if (name2Trim.equals("非首次交流")){
                                            if (fastGptChatSession.getRemindStatus()!=null&&fastGptChatSession.getRemindStatus()==1){
                                                FastGptChatSession s1 = new FastGptChatSession();
                                                s1.setSessionId(fastGptChatSession.getSessionId());
                                                s1.setRemindStatus(0);
                                                s1.setRemindCount(0);
                                                fastGptChatSessionMapper.updateFastGptChatSession(s1);
                                            }
                                        }
                                    }
                                    if (!valueName.trim().equals(name2Trim)){
                                        if(name1.equals("学习到的章节")||name1.equals("今日课程完成情况")){
                                            System.out.println("跳出");
                                            continue;
                                        }

                                        if (name2Trim.contains("delete")&&name2Trim.contains("；")){
                                            name2Trim = name2Trim.replaceAll("delete.*?；", "");
                                        }else if (name2Trim.contains("delete")){
                                            name2Trim=" ";
                                        }
                                        try {
                                            // 允许修改私有属性
                                            field.setAccessible(true);
                                            // 修改 name 属性的值
                                            field.set(info, name2Trim);
                                            System.out.println("插入值"+name2Trim);
                                            b=true;
                                        } catch (Exception e) {
                                            System.out.println("修改错误");
                                        }
                                    }


                                }
                            }
                        }
                    }
                }
            }
            if (b){
                if (info.getId()!=null){
                    qwExternalContactInfoMapper.updateQwExternalContactInfo(info);
                }else {
                    info.setExternalContactId(extId);
                    info.setCreateTime(new Date());
                    qwExternalContactInfoMapper.insertQwExternalContactInfo(info);
                }
            }
            System.out.println("系统更改后的内容"+info);
        }
    }
    private void saveQwUserMsg(FastGptChatSession fastGptChatSession,Integer sendType,String content) {
        content = replaceWxEmo(content);
        if(content.isEmpty()){
            return;
        }
        FastGptChatMsg fastGptChatMsgAi = new FastGptChatMsg();
        fastGptChatMsgAi.setContent(content);
        fastGptChatMsgAi.setSessionId(fastGptChatSession.getSessionId());
        fastGptChatMsgAi.setRoleId(Long.parseLong(fastGptChatSession.getKfId()));
        fastGptChatMsgAi.setSendType(sendType);
        fastGptChatMsgAi.setCompanyId(fastGptChatSession.getCompanyId());
        fastGptChatMsgAi.setCompanyUserId(fastGptChatSession.getQwUserId());
        fastGptChatMsgAi.setUserId(fastGptChatSession.getUserId());
        fastGptChatMsgAi.setUserType(1);
        fastGptChatMsgAi.setMsgType(1);
        fastGptChatMsgAi.setStatus(0);
        fastGptChatMsgAi.setAvatar(fastGptChatSession.getAvatar());
        fastGptChatMsgAi.setNickName(fastGptChatSession.getNickName());
        fastGptChatMsgAi.setCreateTime(new Date());
        fastGptChatMsgAi.setExtId(fastGptChatSession.getQwExtId()+"");
        try {
            fastGptChatMsgService.insertFastGptChatMsg(fastGptChatMsgAi);
        }catch (Exception e){
            log.info("新增报错:"+fastGptChatMsgAi);
        }

    }
    private static String replaceWxEmo(String s){

        if(org.springframework.util.StringUtils.isEmpty(s)) return "";
        return s.replaceAll("\\[.*?]", "");
    }

    private void addUserSex(QwExternalContact qwExternalContacts) {

        QwExternalContactInfo info = qwExternalContactInfoMapper.selectQwExternalContactInfoByExternalContactId(qwExternalContacts.getId());
        if (qwExternalContacts.getGender()!=0){
            if (info!=null){
                info.setSex(qwExternalContacts.getGender()==1?"男":"女");
                qwExternalContactInfoMapper.updateQwExternalContactInfo(info);

            }else {
                QwExternalContactInfo qwExternalContactInfo = new QwExternalContactInfo();
                qwExternalContactInfo.setExternalContactId(qwExternalContacts.getId());
                qwExternalContactInfo.setSex(qwExternalContacts.getGender()==1?"男":"女");
                qwExternalContactInfo.setCreateTime(new Date());
                qwExternalContactInfoMapper.insertQwExternalContactInfo(qwExternalContactInfo);

            }
        }



    }

}
