package com.fs.qw.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.his.config.FsSysConfig;
import com.fs.his.utils.ConfigUtil;
import com.fs.qw.Bean.MsgBean;
import com.fs.qw.domain.*;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwMsgMapper;
import com.fs.qw.mapper.QwSessionMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwMsgSendParam;
import com.fs.qw.param.QwSessionParam;
import com.fs.qw.service.IQwMsgService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.QwContactListVO;
import com.fs.qw.vo.QwMessageListVO;
import com.fs.qwHookApi.vo.QwHookMsgVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企微聊天记录Service业务层处理
 *
 * @author fs
 * @date 2024-12-17
 */
@Service
public class QwMsgServiceImpl extends ServiceImpl<QwMsgMapper, QwMsg> implements IQwMsgService {
    @Autowired
    private QwMsgMapper qwMsgMapper;
    @Autowired
    private IQwUserService qwUserService;
    @Autowired
    private QwSessionMapper qwSessionMapper;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private ConfigUtil configUtil;

    /**
     * 查询企微聊天记录
     *
     * @param msgId 企微聊天记录主键
     * @return 企微聊天记录
     */
    @Override
    public QwMsg selectQwMsgByMsgId(Long msgId) {
        return qwMsgMapper.selectQwMsgByMsgId(msgId);
    }

    /**
     * 查询企微聊天记录列表
     *
     * @param qwMsg 企微聊天记录
     * @return 企微聊天记录
     */
    @Override
    public List<QwMsg> selectQwMsgList(QwMsg qwMsg) {
        return qwMsgMapper.selectQwMsgList(qwMsg);
    }

    /**
     * 新增企微聊天记录
     *
     * @param qwMsg 企微聊天记录
     * @return 结果
     */
    @Override
    public int insertQwMsg(QwMsg qwMsg) {
        qwMsg.setCreateTime(DateUtils.getNowDate());
        return qwMsgMapper.insertQwMsg(qwMsg);
    }

    /**
     * 修改企微聊天记录
     *
     * @param qwMsg 企微聊天记录
     * @return 结果
     */
    @Override
    public int updateQwMsg(QwMsg qwMsg) {
        return qwMsgMapper.updateQwMsg(qwMsg);
    }

    /**
     * 批量删除企微聊天记录
     *
     * @param msgIds 需要删除的企微聊天记录主键
     * @return 结果
     */
    @Override
    public int deleteQwMsgByMsgIds(Long[] msgIds) {
        return qwMsgMapper.deleteQwMsgByMsgIds(msgIds);
    }

    /**
     * 删除企微聊天记录信息
     *
     * @param msgId 企微聊天记录主键
     * @return 结果
     */
    @Override
    public int deleteQwMsgByMsgId(Long msgId) {
        return qwMsgMapper.deleteQwMsgByMsgId(msgId);
    }

    @Override
    public R addQwMsg(QwHookMsgVO msgVo) {
        //查询接收者企微用户
        QwUser qwuser = qwUserService.selectQwUserByAppKey(msgVo.getKey());
        if (qwuser != null) {
            //查询发送者外部联系人
            QwExternalContact qwExternalContact = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(msgVo.getSender_openid(), qwuser.getCorpId(), qwuser.getQwUserId());
            if(qwExternalContact!=null){

                //查询会话
                QwSession qwSession = qwSessionMapper.selectQwSessionByExtIdAndQwUserId(qwExternalContact.getId(), qwuser.getId());
                if (qwSession == null) {
                    qwSession = new QwSession();
                    String chatId = UUID.randomUUID().toString();
                    qwSession.setChatId(chatId);
                    qwSession.setCorpId(qwuser.getCorpId());
                    qwSession.setQwExtWxId(msgVo.getSender());
                    qwSession.setQwExtId(qwExternalContact.getId().toString());
                    qwSession.setQwUserId(qwuser.getId().toString());
                    qwSession.setStatus(1);
                    qwSession.setAvatar(qwExternalContact.getAvatar());
                    qwSession.setNickName(qwExternalContact.getRemark());
                    qwSession.setCompanyId(qwuser.getCompanyId());
                    qwSession.setCompanyUserId(qwuser.getCompanyUserId());
                    qwSession.setCreateTime(new Date());
                    qwSession.setUpdateTime(new Date());
                    qwSessionMapper.insertQwSession(qwSession);
                }else {
                    qwSession.setUpdateTime(new Date());
                    qwSession.setNickName(qwExternalContact.getRemark());
                    qwSessionMapper.updateQwSession(qwSession);
                }
                QwMsg qwMsg = new QwMsg();
                qwMsg.setContent(msgVo.getContent());
                qwMsg.setSessionId(qwSession.getSessionId());
                qwMsg.setSendType(1);
                qwMsg.setCompanyId(qwuser.getCompanyId());
                qwMsg.setCompanyUserId(qwuser.getCompanyUserId());
                qwMsg.setMsgType(1);
                qwMsg.setStatus(0);
                qwMsg.setQwUserId(qwSession.getQwUserId());
                qwMsg.setQwExtId(qwSession.getQwExtId());
                qwMsg.setAvatar(qwExternalContact.getAvatar());
                qwMsg.setNickName(qwExternalContact.getRemark());
                qwMsg.setCreateTime(new Date());
                if (qwMsgMapper.insertQwMsg(qwMsg) > 0) {
                    //发送socket
                    QwMessageListVO msg = new QwMessageListVO();
                    msg.setId(qwMsg.getMsgId().toString());
                    msg.setToContactId(qwMsg.getSessionId().toString());
                    msg.setType("text");
                    msg.setStatus("succeed");
                    msg.setContent(msgVo.getContent());
                    msg.setSendTime(qwMsg.getCreateTime().getTime());
                    QWFromUser qwFromUser = new QWFromUser();
                    //用户发送
                    qwFromUser.setId(Long.parseLong(qwMsg.getQwExtId()));
                    qwFromUser.setAvatar(qwMsg.getAvatar());
                    qwFromUser.setDisplayName(qwMsg.getNickName());
                    msg.setFromUser(qwFromUser);
                    if (qwuser.getAppKey()!=null){
                        sendSocket("receiveMsg",JSONObject.toJSONString(msg),qwuser.getAppKey());
                    }
                    return R.ok().put("data", qwSession);
                }
            }


        }
        return R.error();
    }

    public void sendSocket(String cmd,String message,String appKey){
        MsgBean msgBean=new MsgBean();
        msgBean.setCmd(cmd);
        msgBean.setData(message);
        JSONObject params=new JSONObject();
        params.put("id","msg"+appKey);
        params.put("message",JSONObject.toJSONString(msgBean));
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.post(domainName+"/app/qwmsg/receiveMsg")
                .body(JSONObject.toJSONString(params),"application/json;charset=UTF-8")
                .execute().body();
    }

    @Override
    public R addAiMsg(QwSession session, String content, Integer msgType,QwUser user) {
        if (session == null) {
            return R.error();
        }
        QwMsg qwMsg = new QwMsg();
        qwMsg.setContent(content);
        qwMsg.setSessionId(session.getSessionId());
        qwMsg.setSendType(2);
        qwMsg.setCompanyId(session.getCompanyId());
        qwMsg.setCompanyUserId(session.getCompanyUserId());
        qwMsg.setStatus(0);
        qwMsg.setMsgType(msgType);
        qwMsg.setQwUserId(session.getQwUserId());
        qwMsg.setQwExtId(session.getQwExtId());
        qwMsg.setAvatar(session.getAvatar());
        qwMsg.setNickName(session.getNickName());
        qwMsg.setCreateTime(new Date());
        if (qwMsgMapper.insertQwMsg(qwMsg)>0 && user!=null && user.getAppKey()!=null){
            //发送socket
            QwMessageListVO msg = new QwMessageListVO();
            msg.setId(qwMsg.getMsgId().toString());
            msg.setToContactId(qwMsg.getSessionId().toString());
            msg.setType("text");
            msg.setStatus("succeed");
            msg.setContent(content);
            msg.setSendTime(qwMsg.getCreateTime().getTime());
            QWFromUser qwFromUser = new QWFromUser();
            //客服发送
            qwFromUser.setId(Long.parseLong(qwMsg.getQwUserId()));
            qwFromUser.setDisplayName(user.getQwUserName());
            qwFromUser.setAvatar("https://cos.his.cdwjyyh.com/fs/20241231/22a765a96da247d1b83ea94fef438a41.png");
            msg.setFromUser(qwFromUser);
            sendSocket("receiveMsg",JSONObject.toJSONString(msg),user.getAppKey());
        }
        return R.ok();
    }

    @Override
    public R sendMsg(QwMsgSendParam param) {
        FsSysConfig config = configUtil.getSysConfig();
        String domainName = config.getHookUrl();
        HttpRequest.post(domainName+"/app/qwmsg/sendMsg")
                .body(JSON.toJSONString(param),"application/json;charset=UTF-8")
                .execute().body();
        return R.ok();
    }

    @Override
    public List<QwUser> qwUserList(Long userId) {
        LambdaQueryWrapper<QwUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QwUser::getCompanyUserId, userId);
        lambdaQueryWrapper.eq(QwUser::getLoginStatus,1);
        lambdaQueryWrapper.eq(QwUser::getToolStatus,1);
        List<QwUser> qwUsers = qwUserMapper.selectList(lambdaQueryWrapper);
        return qwUsers;
    }


    @Override
    public List<QwMsg> getQwMessageList(Long companyId) {
        LambdaQueryWrapper<QwUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QwUser::getCompanyId, companyId);
        List<QwUser> qwUsers = qwUserMapper.selectList(lambdaQueryWrapper);
        List<String> qwUserIds = qwUsers.stream().map(x -> x.getQwUserId()).collect(Collectors.toList());
        LambdaQueryWrapper<QwSession> sessionWrapper = new LambdaQueryWrapper<>();
        if (CollectionUtil.isEmpty(qwUserIds)) {
            return null;
        }
        sessionWrapper.in(QwSession::getQwUserId, qwUserIds);
        List<QwSession> qwSessions = qwSessionMapper.selectList(sessionWrapper);
        List<Long> sessionIds = qwSessions.stream().map(x -> x.getSessionId()).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(sessionIds)) {
            return null;
        }
        LambdaQueryWrapper<QwMsg> msgWrapper = new LambdaQueryWrapper<>();
        msgWrapper.in(QwMsg::getSessionId, sessionIds);
        msgWrapper.orderByDesc(QwMsg::getCreateTime);
        List<QwMsg> qwMsgs = qwMsgMapper.selectList(msgWrapper);
        return qwMsgs;
    }

    @Override
    public List<QwContactListVO> selectQwConversationByUserId(Long userId) {
        LambdaQueryWrapper<QwSession> sessionWrapper = new LambdaQueryWrapper<>();
        sessionWrapper.eq(QwSession::getQwUserId, userId);
        sessionWrapper.orderByDesc(QwSession::getUpdateTime);
        List<QwSession> qwSessions = qwSessionMapper.selectList(sessionWrapper);
        if (CollectionUtil.isEmpty(qwSessions)){
            return Collections.EMPTY_LIST;
        }
        ArrayList<QwContactListVO> qwContactListVOS = new ArrayList<>();
        for (QwSession qwSession : qwSessions) {
            QwContactListVO listVO = new QwContactListVO();
            listVO.setId(userId);
            listVO.setAvatar(qwSession.getAvatar());
            listVO.setConversationId(qwSession.getSessionId().toString());
            listVO.setDisplayName(qwSession.getNickName());
//            listVO.setIndex(qwSession.getNickName().substring(0, 1));
            LambdaQueryWrapper<QwMsg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(QwMsg::getSessionId, qwSession.getSessionId());
            lambdaQueryWrapper.orderByDesc(QwMsg::getMsgId);
            lambdaQueryWrapper.last("limit 1");
            List<QwMsg> qwMsgs = qwMsgMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtil.isEmpty(qwMsgs)){
                listVO.setLastContent("");
                listVO.setLastSendTime(new Date().getTime());
                qwContactListVOS.add(listVO);
                break;
            }
            listVO.setLastContent(qwMsgs.get(0).getContent());
            listVO.setLastSendTime(qwMsgs.get(0).getCreateTime().getTime());
            listVO.setUnread(0);
            qwContactListVOS.add(listVO);
        }
        return qwContactListVOS;
    }

    @Override
    public List<QwMsg> selectQwMsgBySession(QwSessionParam param) {
        LambdaQueryWrapper<QwMsg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QwMsg::getSessionId, param.getConversationId());
        lambdaQueryWrapper.orderByDesc(QwMsg::getMsgId);
        List<QwMsg> records = qwMsgMapper.selectList(lambdaQueryWrapper);
        return records;
    }

    @Override
    public List<QwMessageListVO> getQwMessageListBySession(QwSessionParam param , List<QwMsg> list) {
        QwUser user = qwUserMapper.selectQwUserById(param.getUserId());
        List<QwMessageListVO> qwMessageVOS = new ArrayList<>();
        for (QwMsg record : list) {
            QwMessageListVO listVO = new QwMessageListVO();
            listVO.setType("text");
            listVO.setStatus("succeed");
            QWFromUser qwFromUser = new QWFromUser();
            //用户发送
            if (record.getSendType() == 1) {
                qwFromUser.setId(Long.parseLong(record.getQwExtId()));
                qwFromUser.setAvatar(record.getAvatar());
                qwFromUser.setDisplayName(record.getNickName());
            }else if(record.getSendType() == 2){
                qwFromUser.setId(Long.parseLong(record.getQwUserId()));
                qwFromUser.setDisplayName(user.getQwUserName());
                qwFromUser.setAvatar("https://cos.his.cdwjyyh.com/fs/20241231/22a765a96da247d1b83ea94fef438a41.png");
            }
            listVO.setFromUser(qwFromUser);
            listVO.setSendTime(record.getCreateTime().getTime());
            listVO.setId(record.getMsgId().toString());
            listVO.setContent(record.getContent());
            listVO.setToContactId(param.getConversationId());
            qwMessageVOS.add(listVO);
        }
        return qwMessageVOS;
    }


    @Override
    public QwContactListVO selectQwSessionBycId(String sessionId, Long qwUserId) {
        QwSession session = qwSessionMapper.selectQwSessionBySessionId(Long.parseLong(sessionId));
        QwContactListVO listVO = new QwContactListVO();
        listVO.setId(Long.parseLong(session.getQwUserId()));
        listVO.setAvatar(session.getAvatar());
        listVO.setConversationId(session.getSessionId().toString());
        listVO.setDisplayName(session.getNickName());
        listVO.setIndex(session.getNickName().substring(0, 1));
        LambdaQueryWrapper<QwMsg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QwMsg::getSessionId, session.getSessionId());
        lambdaQueryWrapper.orderByDesc(QwMsg::getMsgId);
        lambdaQueryWrapper.last("limit 1");
        List<QwMsg> qwMsgs = qwMsgMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtil.isEmpty(qwMsgs)){
            listVO.setLastContent("");
            listVO.setLastSendTime(new Date().getTime());
        }else {
            listVO.setLastContent(qwMsgs.get(0).getContent());
            listVO.setLastSendTime(qwMsgs.get(0).getCreateTime().getTime());
        }
        listVO.setUnread(0);
        return listVO;
    }
}
