package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fs.common.core.domain.R;
import com.fs.qw.domain.*;
import com.fs.qw.dto.QwMessageDTO;
import com.fs.qw.enums.MessageTypeEnum;
import com.fs.qw.mapper.*;
import com.fs.qw.service.IQwMessageService;
import com.fs.qw.utils.QwAllUtil;
import com.fs.qw.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 企微消息管理Service业务层处理
 *
 * @author fs
 * @date 2023-08-23
 */
@Service
public class QwMessageServiceImpl implements IQwMessageService {

    @Autowired
    private QwUserMapper qwUserMapper;
    @Autowired
    private QwMessageMapper qwMessageMapper;

    @Autowired
    private QwContactMapper qwContactMapper;


    @Autowired
    private QwRoomMapper qwRoomMapper;

    @Autowired
    private QwConversationMapper qwConversationMapper;

    @Autowired
    private QwMaterialMapper qwMaterialMapper;

    @Autowired
    private QwRoomMemberMapper qwRoomMemberMapper;

    @Autowired
    private QwInnerContactMapper innerContactMapper;


    /**
     * 查询企微消息
     *
     * @param id 企微消息ID
     * @return 企微消息
     */
    @Override
    public QwMessage selectQwMessageById(Long id)
    {
        return qwMessageMapper.selectQwMessageById(id);
    }

    /**
     * 查询企微消息列表
     *
     * @param qwMessage 企微消息
     * @return 企微消息
     */
    @Override
    public List<QwMessage> selectQwMessageList(QwMessage qwMessage)
    {
        return qwMessageMapper.selectQwMessageList(qwMessage);
    }

    /**
     * 新增企微消息
     *
     * @param qwMessage 企微消息
     * @return 结果
     */
    @Override
    public void insertQwMessage(QwMessage qwMessage)
    {
//        return qwMessageMapper.insertQwMessage(qwMessage);
    }

    /**
     * 修改企微消息
     *
     * @param qwMessage 企微消息
     * @return 结果
     */
    @Override
    public int updateQwMessage(QwMessage qwMessage)
    {
        return qwMessageMapper.updateQwMessage(qwMessage);
    }

    /**
     * 批量删除企微消息
     *
     * @param ids 需要删除的企微消息ID
     * @return 结果
     */
    @Override
    public int deleteQwMessageByIds(Long[] ids)
    {
        return qwMessageMapper.deleteQwMessageByIds(ids);
    }

    /**
     * 删除企微消息信息
     *
     * @param id 企微消息ID
     * @return 结果
     */
    @Override
    public int deleteQwMessageById(Long id)
    {
        return qwMessageMapper.deleteQwMessageById(id);
    }

    @Override
    public List<QwMessageListVO> selectQwMessageListVO(String conversationId) {
        List<QwMessageListVO> listVOS = new ArrayList<>();
        List<QwMessage> qwMessageList = qwMessageMapper.selectQwMessageListVO(conversationId);
        int isRoom = qwConversationMapper.selectConType(conversationId);
        for (QwMessage qwMessage : qwMessageList){
            QwMessageListVO listVO = new QwMessageListVO();
            listVO.setId(qwMessage.getId().toString());
            if (qwMessage.getMessageType()==1){
                listVO.setType("text");
                listVO.setContent(qwMessage.getContent());
            }else if (qwMessage.getMessageType()==2){
                listVO.setType("image");
                listVO.setUrl(qwMessage.getUrl());
                listVO.setContent(qwMessage.getUrl());
            } else if (qwMessage.getMessageType()==3) {
                listVO.setType("video");
                listVO.setContent(qwMessage.getUrl());
                listVO.setImageUrl(qwMessage.getImageUrl());
            } else if (qwMessage.getMessageType()==4){
                listVO.setType("file");
                listVO.setContent(qwMessage.getUrl());
                listVO.setFileSize(qwMessage.getFileSize());
                listVO.setFileName(qwMessage.getFileName());
                listVO.setFileShowType(qwMessage.getFileShowType());
            }else if (qwMessage.getMessageType()==5){
                listVO.setType("voice");
                listVO.setContent(qwMessage.getUrl());
                listVO.setDuration(qwMessage.getDuration());
            }else if (qwMessage.getMessageType()==7){
                listVO.setType("image");
                listVO.setUrl(qwMessage.getUrl());
            }else {
                listVO.setContent("");
            }
            listVO.setStatus("succeed");
//            //获取fromUser
//            QWFromUser fromUser=new QWFromUser();
//            fromUser.setId(qwMessage.getSenderId());
//            QwUser qwUser=qwUserMapper.selectQwUserById(qwMessage.getSenderId());
//            if(qwUser!=null){
//                fromUser.setAvatar(qwUser.getAvatar());
//                fromUser.setDisplayName(qwUser.getNickName());
//            }else{
//                QwContact qwContact=qwContactMapper.selectQwContactByUserId(qwMessage.getSenderId());
//                fromUser.setAvatar(qwContact.getAvatar());
//                fromUser.setDisplayName(qwContact.getNickName());
//            }

            QWFromUser fromUser=new QWFromUser();
            fromUser.setId(qwMessage.getSenderId());
            if (isRoom == 0){
                //获取fromUser
                QwInnerContact innerContact = innerContactMapper.selectInnerContactById(qwMessage.getSenderId());
                if(innerContact!=null){
                    fromUser.setAvatar(innerContact.getAvatar());
                    fromUser.setDisplayName(innerContact.getNickName());
                }else{
                    QwContact qwContact=qwContactMapper.selectQwContactByUserId(qwMessage.getSenderId());
                    fromUser.setAvatar(qwContact.getAvatar());
                    fromUser.setDisplayName(qwContact.getNickName());
                }

            }else {
                QwRoomMember qwRoomMember = qwRoomMemberMapper.selectQwRoomMemberByUserId(qwMessage.getSenderId(), Long.valueOf(conversationId));
                if (qwRoomMember!=null){
                    fromUser.setAvatar(qwRoomMember.getAvatar());
                    fromUser.setDisplayName(qwRoomMember.getNickName());
                }
            }
            listVO.setToContactId(conversationId);
            listVO.setSendTime(qwMessage.getSendTime()*1000);
            listVO.setFromUser(fromUser);
           listVOS.add(listVO);
        }
        return listVOS;
    }

    @Override
    public  List<QwMessage> selectQwMessageListByTypeVO(QwMessageListParam param) {
        List<QwMessage> qwMessageList = qwMessageMapper.selectQwMessageListByTypeVO(param);
        return qwMessageList;
    }

    @Override
    public  List<QwMessage> selectQwMessageListContextVO(QwMessageListParam param) {
        List<QwMessage> qwMessageList = qwMessageMapper.selectQwMessageListContextVO(param);
        return qwMessageList;
    }

    @Override
    public  List<QwMessageListVO> getQwMessageListVO(List<QwMessage> qwMessageList,String conversationId, int isRoom){
        List<QwMessageListVO> listVOS = new ArrayList<>();
        for (QwMessage qwMessage : qwMessageList){
            QwMessageListVO listVO = new QwMessageListVO();
            listVO.setId(qwMessage.getId().toString());
            if (qwMessage.getMessageType()==1){
                listVO.setType("text");
                listVO.setContent(qwMessage.getContent());
            }else if (qwMessage.getMessageType()==2){
                listVO.setType("image");
                listVO.setUrl(qwMessage.getUrl());
                listVO.setContent(qwMessage.getUrl());
            } else if (qwMessage.getMessageType()==3) {
                listVO.setType("video");
                listVO.setContent(qwMessage.getUrl());
                listVO.setImageUrl(qwMessage.getImageUrl());
            } else if (qwMessage.getMessageType()==4){
                listVO.setType("file");
                listVO.setContent(qwMessage.getUrl());
                listVO.setFileSize(qwMessage.getFileSize());
                listVO.setFileName(qwMessage.getFileName());
                listVO.setFileShowType(qwMessage.getFileShowType());
            }else if (qwMessage.getMessageType()==5){
                listVO.setType("voice");
                listVO.setContent(qwMessage.getUrl());
                listVO.setDuration(qwMessage.getDuration());
            }else if (qwMessage.getMessageType()==7){
                listVO.setType("image");
                listVO.setUrl(qwMessage.getUrl());
            }else {
                listVO.setContent("");
            }
            listVO.setStatus("succeed");

//            //获取fromUser
//            QWFromUser fromUser=new QWFromUser();
//            fromUser.setId(qwMessage.getSenderId());
//            QwUser qwUser=qwUserMapper.selectQwUserById(qwMessage.getSenderId());
//            if(qwUser!=null){
//                fromUser.setAvatar(qwUser.getAvatar());
//                fromUser.setDisplayName(qwUser.getNickName());
//            }else{
//                QwContact qwContact=qwContactMapper.selectQwContactByUserId(qwMessage.getSenderId());
//                fromUser.setAvatar(qwContact.getAvatar());
//                fromUser.setDisplayName(qwContact.getNickName());
//            }

            QWFromUser fromUser=new QWFromUser();
            fromUser.setId(qwMessage.getSenderId());
            //判断是否群聊
            if (isRoom == 0){
                //获取fromUser
                //判断是内部联系人还是联系人
                QwInnerContact innerContact = innerContactMapper.selectInnerContactById(qwMessage.getSenderId());
                QwContact qwContact=qwContactMapper.selectQwContactByUserId(qwMessage.getSenderId());
                QwUser qwUser = qwUserMapper.selectQwUserByUserId(qwMessage.getSenderId());
                if(innerContact!=null){
                    fromUser.setAvatar(innerContact.getAvatar());
                    fromUser.setDisplayName(innerContact.getNickName());
                }else if (qwContact!=null){
                    fromUser.setAvatar(qwContact.getAvatar());
                    fromUser.setDisplayName(qwContact.getNickName());
                }else if (qwUser!=null){
                    fromUser.setAvatar(qwUser.getAvatar());
                    fromUser.setDisplayName(qwUser.getNickName());
                }

            }else {
                QwRoomMember qwRoomMember = qwRoomMemberMapper.selectQwRoomMemberByUserId(qwMessage.getSenderId(), Long.valueOf(conversationId));
                if (qwRoomMember!=null){
                    fromUser.setAvatar(qwRoomMember.getAvatar());
                    fromUser.setDisplayName(qwRoomMember.getNickName());
                }
            }
            listVO.setToContactId(conversationId);
            listVO.setSendTime(qwMessage.getSendTime()*1000);
            listVO.setFromUser(fromUser);
            listVOS.add(listVO);
        }
        return listVOS;
    }


    @Override
    public List<QwMessageListExportVO> selectMessageListExportVO(String conversationId) {
        List<QwMessageListExport> list = qwMessageMapper.selectMessageListExportVO(conversationId);
        List<QwMessageListExportVO> exportVOList = new ArrayList<>();
        for (QwMessageListExport vo : list){
            //遍历组装exportVO
            QwMessageListExportVO exportVO = new QwMessageListExportVO();
            BeanUtils.copyProperties(vo,exportVO);
            QwConversation qwConversation = qwConversationMapper.selectByConversationId(conversationId);
            //判断会话是单聊还是群聊
            if(qwConversation.getType()==0){
                //单聊取ext
                List<QwConversationExt> extList = JSON.parseObject(qwConversation.getExt(), new TypeReference<List<QwConversationExt>>() {
                });
                //获取发送人的备注或者昵称
                for (QwConversationExt ext : extList){
                    if (!ext.getUserId().equals(vo.getSenderId())){
                        if (ext.getRemark()!=null&&!ext.getRemark().equals("")){
                            exportVO.setSenderName(ext.getRemark());
                        }else {
                            exportVO.setSenderName(ext.getNickName());
                        }
                    }
                }
                //群聊取群成员信息
            }else {
                QwRoomMember qwRoomMember = qwRoomMemberMapper.selectQwRoomMemberByUserId(vo.getSenderId(),Long.valueOf(conversationId));
                exportVO.setSenderName(qwRoomMember.getNickName());
            }
            //非文本消息将获取的url  set到content里
            if (vo.getMessageType()!=MessageTypeEnum.TEXT.getValue()){
                exportVO.setContent(vo.getUrl());
            }
            //时间戳转换时间
            Instant instant = Instant.ofEpochSecond(vo.getSendTime());
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            exportVO.setSendTime(localDateTime.format(formatter));
            exportVOList.add(exportVO);
        }
        return exportVOList;
    }

    @Override
    public R sendMessageText(QwMessageDTO qwMessageDTO) {
        QwConversation conversation = qwConversationMapper.selectByConversationId(qwMessageDTO.getConversationId());
        Long receiverId  = Long.valueOf(extractUserId(conversation.getAncestors(),qwMessageDTO.getUserId().toString()));
        Long userId = qwUserMapper.selectUserIdByDeviceId(qwMessageDTO.getDeviceId());
        QwMessageText qwMessageText = new QwMessageText();
        qwMessageText.setContent(qwMessageDTO.getContent());
        QwMessage qwMessage = new QwMessage();
        qwMessage.setMessageType(MessageTypeEnum.TEXT.getValue());
        qwMessage.setSenderId(userId);
        qwMessage.setConversationId(qwMessageDTO.getConversationId());
        qwMessage.setCreateTime(new Date());
//        Map<String,Object> messageMap = new HashMap<>();
        QwConversation qwConversation = new QwConversation();
        //判断会话为群聊还是单聊
        if (conversation.getType()==0){
            qwMessageText.setReceiverId(receiverId);
            qwMessageText.setRoom(false);
            qwMessage.setReceiverId(receiverId);
            qwMessage.setRoomId(0L);
            qwMessage.setContent(qwMessageDTO.getContent());
            R sendR = QwAllUtil.messageText(qwMessageText.toMap(),qwMessageDTO.getDeviceId());
            if (sendR.containsKey("QwSendMessageText")){
                QwMessageReturn qwMessageReturn = (QwMessageReturn) sendR.get("QwSendMessageText");
                BeanUtils.copyProperties(qwMessageReturn,qwMessage);
                qwMessageMapper.insertQwMessage(qwMessage);
                qwConversation.setConversationId(qwMessageDTO.getConversationId());
                qwConversation.setLastMessageId(qwMessage.getId());
                qwConversationMapper.updateLastMessage(qwConversation);
            }
            return sendR;
        }else {
            qwMessage.setReceiverId(0L);
            qwMessage.setRoomId(Long.valueOf(qwMessageDTO.getConversationId()));
            qwMessage.setConversationId(qwMessageDTO.getConversationId());
            qwMessage.setContent(qwMessageDTO.getContent());
            qwMessageText.setRoom(true);
            qwMessageText.setReceiverId(Long.valueOf(qwMessageDTO.getConversationId()));
            R sendR = QwAllUtil.messageText(qwMessageText.toMap(),qwMessageDTO.getDeviceId());
            if (sendR.containsKey("QwSendMessageText")){
                QwMessageReturn qwMessageReturn = (QwMessageReturn) sendR.get("QwSendMessageText");
                BeanUtils.copyProperties(qwMessageReturn,qwMessage);
                qwMessageMapper.insertQwMessage(qwMessage);
                qwConversation.setConversationId(qwMessageDTO.getConversationId());
                qwConversation.setLastMessageId(qwMessage.getId());
                qwConversationMapper.updateLastMessage(qwConversation);

            }
            return sendR;
        }
    }

    @Override
    public R sendMessageImage(QwMessageDTO qwMessageDTO) {
        //解析会话中的接收方
        QwConversation conversation = qwConversationMapper.selectByConversationId(qwMessageDTO.getConversationId());
        Long receiverId  = Long.valueOf(extractUserId(conversation.getAncestors(),qwMessageDTO.getUserId().toString()));
        //获取发送者的UserId
        Long userId = qwUserMapper.selectUserIdByDeviceId(qwMessageDTO.getDeviceId());
        //组装图片请求的请求参数
        QwMessageImage qwMessageImage = new QwMessageImage();
        //获取素材库中图片的cdn参数
        QwMaterial material = qwMaterialMapper.selectQwMaterialById(qwMessageDTO.getMaterialId());
        BeanUtils.copyProperties(material,qwMessageImage);
        //组装Qwmessage
        QwMessage qwMessage = new QwMessage();
        qwMessage.setMessageType(MessageTypeEnum.IMAGE.getValue());
        qwMessage.setSenderId(userId);
        qwMessage.setConversationId(qwMessageDTO.getConversationId());
        qwMessage.setCreateTime(new Date());
//        Map<String,Object> messageMap = new HashMap<>();
        QwConversation qwConversation = new QwConversation();
        //判断会话为群聊还是单聊
        if (conversation.getType()==0){
            qwMessageImage.setReceiverId(receiverId);
            qwMessageImage.setRoom(false);
            qwMessage.setReceiverId(receiverId);
            qwMessage.setRoomId(0L);
            qwMessage.setUrl(material.getUrl());
            //发送图片请求
            R sendR = QwAllUtil.messageImage(qwMessageImage.toMap(),qwMessageDTO.getDeviceId());

            if (sendR.containsKey("QwSendMessageImage")){
                //获取返回参数
                QwMessageReturn qwMessageReturn = (QwMessageReturn) sendR.get("QwSendMessageImage");
                BeanUtils.copyProperties(qwMessageReturn,qwMessage);
                //新增到数据库
                qwMessageMapper.insertQwMessage(qwMessage);
                qwConversation.setConversationId(qwMessageDTO.getConversationId());
                qwConversation.setLastMessageId(qwMessage.getId());
                //修改会话最后一条消息id
                qwConversationMapper.updateLastMessage(qwConversation);
            }
            return sendR;
        }else {
            qwMessage.setReceiverId(0L);
            qwMessage.setRoomId(Long.valueOf(qwMessageDTO.getConversationId()));
            qwMessage.setConversationId(qwMessageDTO.getConversationId());
            qwMessage.setUrl(material.getUrl());
            qwMessageImage.setRoom(true);
            qwMessageImage.setReceiverId(Long.valueOf(qwMessageDTO.getConversationId()));
            //发送图片请求
            R sendR = QwAllUtil.messageImage(qwMessageImage.toMap(),qwMessageDTO.getDeviceId());
            if (sendR.containsKey("QwSendMessageImage")){
                //获取返回参数
                QwMessageReturn qwMessageReturn = (QwMessageReturn) sendR.get("QwSendMessageImage");
                BeanUtils.copyProperties(qwMessageReturn,qwMessage);
                //新增到数据库
                qwMessageMapper.insertQwMessage(qwMessage);
                qwConversation.setConversationId(qwMessageDTO.getConversationId());
                qwConversation.setLastMessageId(qwMessage.getId());
                //修改会话最后一条消息id
                qwConversationMapper.updateLastMessage(qwConversation);
            }
            return sendR;
        }
    }

    @Override
    public R sendMessageVoice(QwMessageDTO qwMessageDTO) {
        //解析会话中的接收方
        QwConversation conversation = qwConversationMapper.selectByConversationId(qwMessageDTO.getConversationId());
        Long receiverId  = Long.valueOf(extractUserId(conversation.getAncestors(),qwMessageDTO.getUserId().toString()));
        //获取发送者的UserId
        Long userId = qwUserMapper.selectUserIdByDeviceId(qwMessageDTO.getDeviceId());
        //组装图片请求的请求参数
        QwMessageVoice qwMessageVoice = new QwMessageVoice();
        //获取素材库中图片的cdn参数
        QwMaterial material = qwMaterialMapper.selectQwMaterialById(qwMessageDTO.getMaterialId());
        BeanUtils.copyProperties(material,qwMessageVoice);
        //组装Qwmessage
        QwMessage qwMessage = new QwMessage();
        qwMessage.setMessageType(MessageTypeEnum.IMAGE.getValue());
        qwMessage.setSenderId(userId);
        qwMessage.setConversationId(qwMessageDTO.getConversationId());
        qwMessage.setCreateTime(new Date());
//        Map<String,Object> messageMap = new HashMap<>();
        QwConversation qwConversation = new QwConversation();
        //判断会话为群聊还是单聊
        if (conversation.getType()==0){
            qwMessageVoice.setReceiverId(receiverId);
            qwMessageVoice.setRoom(false);
            qwMessage.setReceiverId(receiverId);
            qwMessage.setRoomId(0L);
            qwMessage.setUrl(material.getUrl());
            //发送图片请求
            R sendR = QwAllUtil.messageVoice(qwMessageVoice.toMap(),qwMessageDTO.getDeviceId());
            if (sendR.containsKey("QwSendMessageVoice")){
                //获取返回参数
                QwMessageReturn qwMessageReturn = (QwMessageReturn) sendR.get("QwSendMessageVoice");
                BeanUtils.copyProperties(qwMessageReturn,qwMessage);
                //新增到数据库
                qwMessageMapper.insertQwMessage(qwMessage);
                qwConversation.setConversationId(qwMessageDTO.getConversationId());
                qwConversation.setLastMessageId(qwMessage.getId());
                //修改会话最后一条消息id
                qwConversationMapper.updateLastMessage(qwConversation);
            }
            return sendR;
        }else {
            //组装群聊的请求参数和新增数据库的参数
            qwMessage.setReceiverId(0L);
            qwMessage.setRoomId(Long.valueOf(qwMessageDTO.getConversationId()));
            qwMessage.setConversationId(qwMessageDTO.getConversationId());
            qwMessage.setUrl(material.getUrl());
            qwMessageVoice.setRoom(true);
            qwMessageVoice.setReceiverId(Long.valueOf(qwMessageDTO.getConversationId()));
            //发送图片请求
            R sendR = QwAllUtil.messageVoice(qwMessageVoice.toMap(),qwMessageDTO.getDeviceId());
            if (sendR.containsKey("QwSendMessageVoice")){
                //获取返回参数
                QwMessageReturn qwMessageReturn = (QwMessageReturn) sendR.get("QwSendMessageVoice");
                BeanUtils.copyProperties(qwMessageReturn,qwMessage);
                //新增到数据库
                qwMessageMapper.insertQwMessage(qwMessage);
                qwConversation.setConversationId(qwMessageDTO.getConversationId());
                qwConversation.setLastMessageId(qwMessage.getId());
                //修改会话最后一条消息id
                qwConversationMapper.updateLastMessage(qwConversation);
            }
            return sendR;
        }
    }

    @Override
    public R messageRevoke(QwMessageDTO qwMessageDTO) {
        QwMessageRevoke messageRevoke = qwMessageMapper.selectMessageRevokeById(qwMessageDTO.getId());
        return QwAllUtil.messageRevoke(messageRevoke,qwMessageDTO.getDeviceId());
    }

    @Override
    public void sendWarningMessage(QwMessageText qwMessageText) {
        qwMessageText.setReceiverId(1688854331463712L);
        qwMessageText.setRoom(false);
        String deviceId = "5e6214b205e94a2db6cdcbbaf46f2c00";
        QwAllUtil.messageText(qwMessageText.toMap(),deviceId);
    }

    public String extractUserId(String data, String excludedUserId) {
        String[] parts = data.split(",");
        for (String part : parts) {
            String userId = part.trim();
            if (!userId.equals(excludedUserId)) {
                return userId;
            }
        }
        return null;
    }
}
