package com.fs.qw.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.common.utils.OrderUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.http.HttpUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.service.ICompanyUserService;
import com.fs.crm.domain.CrmMsg;
import com.fs.crm.service.ICrmMsgService;
import com.fs.jpush.service.JpushService;
import com.fs.qw.config.MsgBean;
import com.fs.qw.config.QwUrlConfig;
import com.fs.qw.domain.*;
import com.fs.qw.dto.QwMessageDTO;
import com.fs.qw.dto.QwRoomMemberDTO;
import com.fs.qw.enums.cdnDownloadTypeEnum;
import com.fs.qw.enums.fileShowTypeEnum;
import com.fs.qw.event.*;
import com.fs.qw.mapper.*;
import com.fs.qw.service.*;
import com.fs.qw.utils.QwAllUtil;
import com.fs.qw.utils.QwDownloadUtil;
import com.fs.qw.vo.*;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;

import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import lombok.Synchronized;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;

import static com.fs.qw.utils.QwUtil.toJson;

@Service
public class QwEventMessageServiceImpl implements IQwEventMessageService {
    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private QwMessageMapper qwMessageMapper;

    @Autowired
    private QwConversationMapper conversationMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwContactMapper qwContactMapper;

    @Autowired
    private QwRoomMapper qwRoomMapper;

    @Autowired
    private QwRoomMemberMapper qwRoomMemberMapper;

    @Autowired
    private IQwForbiddenWordsService qwForbiddenWordsService;

    @Autowired
    private IQwForbiddenMessageService qwForbiddenMessageService;

    @Autowired
    private QwInnerContactMapper innerContactMapper;

    @Override
    @Synchronized
    @Transactional
    public R contactChanged(String deviceId, EventContactChanged contactChanged) {
        QwUserVO qwUser = qwUserMapper.selectQwUserByDeviceId(deviceId);
        QwContact qwContact = new QwContact();
        System.out.println(contactChanged);
        if (!contactChanged.getAdded().isEmpty()){
            for (QwContactVO vo : contactChanged.getAdded()){
                BeanUtils.copyProperties(vo,qwContact);
                qwContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                qwContact.setLabels(toJson(vo.getLabels()));
                qwContact.setDescribes(vo.getDesc());
                qwContact.setHomeUserId(qwUser.getUserId().toString());
                qwContactMapper.insertQwContact(qwContact);
            }
        }else if (!contactChanged.getRemoved().isEmpty()){
            for (QwContactVO vo : contactChanged.getRemoved()){
                BeanUtils.copyProperties(vo,qwContact);
                qwContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                qwContact.setLabels(toJson(vo.getLabels()));
                qwContact.setDescribes(vo.getDesc());
                qwContact.setHomeUserId(qwUser.getUserId().toString());
                qwContactMapper.updateQwContact(qwContact);
            }
        }else if (!contactChanged.getChanged().isEmpty()){
            //更新联系人数据
            for (QwContactVO vo : contactChanged.getChanged()){
                BeanUtils.copyProperties(vo,qwContact);
                qwContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                qwContact.setLabels(toJson(vo.getLabels()));
                qwContact.setDescribes(vo.getDesc());
                qwContact.setHomeUserId(qwUser.getUserId().toString());
                qwContactMapper.updateQwContact(qwContact);
                //更新会话中ext
                String conver = sortAndCombine(qwUser.getUserId().toString(),qwContact.getUserId().toString());
                String conversationId = DigestUtils.md5Hex(conver);
                QwConversation qwConversation = conversationMapper.selectConByConversationId(conversationId);
                if (qwConversation!=null){
                    List<QwConversationExt> extList = new ArrayList<>();
                    QwConversationExt qwConversationExt = new QwConversationExt();
                    QwConversationExt qwConversationExt1 = new QwConversationExt();
                    qwConversationExt1.setUserId(qwUser.getUserId());
                    qwConversationExt1.setNickName(qwUser.getNickName());
                    qwConversationExt1.setAvatar(qwUser.getAvatar());
                    qwConversationExt1.setRemark("");
                    qwConversationExt.setUserId(vo.getUserId());
                    qwConversationExt.setNickName(vo.getNickName());
                    qwConversationExt.setAvatar(vo.getAvatar());
                    qwConversationExt.setRemark(qwContact.getRemark());
                    extList.add(qwConversationExt);
                    extList.add(qwConversationExt1);
                    String ext = toJson(extList);
                    conversationMapper.updateExt(conversationId,ext);
                }
            }
        }
        return R.ok();
    }

    @Override
    @Synchronized
//  @Transactional
    public R EventMessageText(String deviceId,EventMessageText messageText) {
        if (messageText!= null){
            QwMessage qwMessage1;
             qwMessage1 = qwMessageMapper.selectQwMessageBySenderIdAndTime(messageText.getSenderId(),messageText.getSendTime(),messageText.getRoomId());
            if (qwMessage1 == null){
                    QwMessage qwMessage = new QwMessage();
                    BeanUtils.copyProperties(messageText,qwMessage);
                    Map<String, Object> map = messageText.toMap();
                    String json = toJson(map);
                    qwMessage.setParam(json);
                    qwMessage.setContent(messageText.getContent());
                    qwMessage.setCreateTime(new Date());
                    qwMessageMapper.insertQwMessage(qwMessage);
                    createConversation(qwMessage,deviceId);
                    addForbiddenMessage(qwMessage,deviceId);
                    qwMessage1=qwMessage;

            }
            return R.ok().put("QwMessage",qwMessage1);
        }else {
            return R.error();
        }
    }

    @Override
    @Synchronized
//    @Transactional
    public R EventMessageImage(String deviceId, EventMessageImage messageImage) throws IOException {
        if (messageImage!= null){
            QwMessage qwMessage1 = qwMessageMapper.selectQwMessageBySenderIdAndTime(messageImage.getSenderId(),messageImage.getSendTime(),messageImage.getRoomId());
            if (qwMessage1 == null){
                  QwMessage qwMessage = new QwMessage();
                //QwContact qwContact = qwContactMapper.selectQwContactByUserId(messageImage.getSenderId());
                //QwUserVO qwUser = qwUserMapper.selectQwUserByDeviceId(deviceId);
                //if ((qwUser!=null &&(qwUser.getUserId().equals(messageImage.getSenderId()))) || (qwContact !=null &&(qwContact.getUserId().equals(messageImage.getSenderId())))) {
                    BeanUtils.copyProperties(messageImage,qwMessage);
                    QwCDNDownload cdnDownload = new QwCDNDownload();
                    BeanUtils.copyProperties(messageImage,cdnDownload);
                    cdnDownload.setFileType(cdnDownloadTypeEnum.IMAGE.getValue());
                    cdnDownload.setFileName(UUID.randomUUID().toString().replaceAll("-", "")+".jpg");
                    String url = createOssImageUrl(cdnDownload,deviceId);
                    qwMessage.setUrl(url);
                    qwMessage.setWidth(messageImage.getWidth());
                    qwMessage.setHeight(messageImage.getHeight());
                    Map<String, Object> map = messageImage.toMap();
                    String json = toJson(map);
                    qwMessage.setParam(json);
                    qwMessage.setCreateTime(new Date());
                    qwMessageMapper.insertQwMessage(qwMessage);
                    createConversation(qwMessage,deviceId);
                    qwMessage1=qwMessage;
               // }

            }
            return R.ok().put("QwMessage",qwMessage1);
        }else {
            return R.error();
        }
    }

    @Override
    @Synchronized
//    @Transactional
    public R EventMessageVideo(String deviceId, EventMessageVideo messageVideo) {
        if (messageVideo!= null){
            QwMessage qwMessage1 = qwMessageMapper.selectQwMessageBySenderIdAndTime(messageVideo.getSenderId(),messageVideo.getSendTime(),messageVideo.getRoomId());
            if (qwMessage1 == null){
                QwMessage qwMessage = new QwMessage();
                BeanUtils.copyProperties(messageVideo,qwMessage);
                QwCDNDownload cdnDownload = new QwCDNDownload();
                cdnDownload.setFileId(messageVideo.getVideoFileId());
                cdnDownload.setFileSize(messageVideo.getVideoFileSize());
                cdnDownload.setMd5(messageVideo.getVideoMd5());
                cdnDownload.setAesKey(messageVideo.getVideoAesKey());
                cdnDownload.setFileType(cdnDownloadTypeEnum.VIDEO.getValue());
                cdnDownload.setFileName(UUID.randomUUID().toString().replaceAll("-", "")+".mp4");
                String url = createOssUrl(cdnDownload,deviceId);
                qwMessage.setUrl(url);
                qwMessage.setHeight(messageVideo.getHeight());
                qwMessage.setWidth(messageVideo.getWidth());
                qwMessage.setDuration(messageVideo.getDuration());
                //判断有无缩略图的cdn参数
                if (StringUtils.isEmpty(messageVideo.getThumbnailAesKey())||StringUtils.isEmpty(messageVideo.getThumbnailMd5())||messageVideo.getThumbnailFileSize()==0){
                    qwMessage.setImageUrl(messageVideo.getThumbnailFileId());
                }else {
                    cdnDownload.setFileId(messageVideo.getThumbnailFileId());
                    cdnDownload.setAesKey(messageVideo.getThumbnailAesKey());
                    cdnDownload.setMd5(messageVideo.getThumbnailMd5());
                    cdnDownload.setFileSize(messageVideo.getThumbnailFileSize());
                    cdnDownload.setFileType(cdnDownloadTypeEnum.THUMBNAIL.getValue());
                    cdnDownload.setFileName(UUID.randomUUID().toString().replaceAll("-", "")+".jpg");
                    String imageUrl = createOssUrl(cdnDownload,deviceId);
                    qwMessage.setImageUrl(imageUrl);
                }
                Map<String, Object> map = messageVideo.toMap();
                String json = toJson(map);
                qwMessage.setParam(json);
                qwMessage.setCreateTime(new Date());
                qwMessageMapper.insertQwMessage(qwMessage);
                createConversation(qwMessage,deviceId);
                qwMessage1=qwMessage;
            }
            return R.ok().put("QwMessage",qwMessage1);
        }else {
            return R.error();
        }
    }


    @Override
    @Synchronized
//    @Transactional
    public R EventMessageVoice(String deviceId, EventMessageVoice messageVoice) {
        if (messageVoice!= null){
            QwMessage qwMessage1 = qwMessageMapper.selectQwMessageBySenderIdAndTime(messageVoice.getSenderId(),messageVoice.getSendTime(),messageVoice.getRoomId());
            if (qwMessage1 == null){
                QwMessage qwMessage = new QwMessage();
                BeanUtils.copyProperties(messageVoice,qwMessage);
                QwCDNDownload cdnDownload = new QwCDNDownload();
                BeanUtils.copyProperties(messageVoice,cdnDownload);
                cdnDownload.setFileType(cdnDownloadTypeEnum.VOICE.getValue());
                cdnDownload.setFileName(UUID.randomUUID().toString().replaceAll("-", "")+".mp3");
                String url = createOssUrl(cdnDownload,deviceId);
                qwMessage.setUrl(url);
                qwMessage.setDuration(messageVoice.getDuration());
                Map<String, Object> map = messageVoice.toMap();
                String json = toJson(map);
                qwMessage.setParam(json);
                qwMessage.setCreateTime(new Date());
                qwMessageMapper.insertQwMessage(qwMessage);
                createConversation(qwMessage,deviceId);
                qwMessage1=qwMessage;
            }
            return R.ok().put("QwMessage",qwMessage1);
        }else {
            return R.error();
        }
    }

    @Override
    @Synchronized
//    @Transactional
    public R EventMessageEmoji(String deviceId, EventMessageEmoji messageEmoji) {
        if (messageEmoji!= null){
            QwMessage qwMessage1 = qwMessageMapper.selectQwMessageBySenderIdAndTime(messageEmoji.getSenderId(),messageEmoji.getSendTime(),messageEmoji.getRoomId());
            if (qwMessage1 == null){
                QwMessage qwMessage = new QwMessage();
                BeanUtils.copyProperties(messageEmoji,qwMessage);
                qwMessage.setUrl(messageEmoji.getUrl());
                Map<String, Object> map = messageEmoji.toMap();
                String json = toJson(map);
                qwMessage.setParam(json);
                qwMessage.setCreateTime(new Date());
                qwMessageMapper.insertQwMessage(qwMessage);
                createConversation(qwMessage,deviceId);
                qwMessage1=qwMessage;
            }
            return R.ok().put("QwMessage",qwMessage1);
        }else {
            return R.error();
        }
    }

    @Override
    @Synchronized
//    @Transactional
    public R EventMessageFile(String deviceId, EventMessageFile messageFile){
        if (messageFile!= null){
            QwMessage qwMessage1 = qwMessageMapper.selectQwMessageBySenderIdAndTime(messageFile.getSenderId(),messageFile.getSendTime(),messageFile.getRoomId());
            if (qwMessage1 == null){
                QwMessage qwMessage = new QwMessage();
                BeanUtils.copyProperties(messageFile,qwMessage);
                QwCDNDownload cdnDownload = new QwCDNDownload();
                BeanUtils.copyProperties(messageFile,cdnDownload);
                cdnDownload.setFileType(cdnDownloadTypeEnum.FILE.getValue());
                String url = createOssUrl(cdnDownload,deviceId);
                qwMessage.setUrl(url);
                qwMessage.setFileName(cdnDownload.getFileName());
                qwMessage.setFileShowType(fileShowType(cdnDownload.getFileName()));
                qwMessage.setFileSize(cdnDownload.getFileSize());
                qwMessage.setCreateTime(new Date());
                qwMessageMapper.insertQwMessage(qwMessage);
                createConversation(qwMessage,deviceId);
                qwMessage1=qwMessage;
            }
            return R.ok().put("QwMessage",qwMessage1);
        }else {
            return R.error();
        }
    }

    @Override
    public R EventMessageRevoked(Long severId) {
        QwMessage qwMessage = qwMessageMapper.selectQwMessageByServerId(severId);
        if (qwMessage!=null){
            qwMessage.setIsRevoked(true);
            qwMessageMapper.updateQwMessage(qwMessage);
            return R.ok();
        }else {
            return R.error();
        }
    }

    @Autowired
    private IQwContactService qwContactService;

    @Autowired
    private IQwEventAuthService qwEventAuthService;

    /**
     * 创建会话
     */
    public void createConversation(QwMessage qwMessage,String deviceId) {
        QwConversation conversation = new QwConversation();
        QwUserVO qwUser = qwUserMapper.selectQwUserByDeviceId(deviceId);
        //判断是否群聊
        if (qwMessage.getRoomId()!=null && qwMessage.getRoomId().longValue() == 0&&qwMessage.getReceiverId()!=0L){
            //单聊组成形式 sender_id+receiver_id升序组合md5字符串为会话id
            String combinedString = sortAndCombine(qwMessage.getSenderId().toString(), qwMessage.getReceiverId().toString());
            String conversationId = DigestUtils.md5Hex(combinedString);
            qwMessage.setConversationId(conversationId);
            //往message里面加入会话id
            qwMessageMapper.updateConversationId(qwMessage.getId(),conversationId);
            QwConversation qwConversation = conversationMapper.selectByConversationId(conversationId);
            //判断会话是否存在
            if (qwConversation != null){
                //会话最新一条消息id为消息的服务端id
                conversation.setLastMessageId(qwMessage.getId());
                conversation.setConversationId(qwConversation.getConversationId());
                conversationMapper.updateLastMessage(conversation);
            }else {
                //不存在时新建会话
                conversation.setConversationId(DigestUtils.md5Hex(combinedString));
                conversation.setType(0L);
                conversation.setDeviceId(deviceId);
                //会话最新一条消息id为消息的服务端id
                conversation.setLastMessageId(qwMessage.getId());
                conversation.setAncestors(qwMessage.getSenderId()+","+qwMessage.getReceiverId());
                QwConversationExt conversationExt = new QwConversationExt();
                QwConversationExt conversationExt1 = new QwConversationExt();
                //首次会话判断本用户是接收方还是发送方
                if(qwMessage.getSenderId().equals(qwUser.getUserId())){
                    //组装单聊会话的ext
                    conversationExt.setUserId(qwUser.getUserId());
                    conversationExt.setNickName(qwUser.getNickName());
                    conversationExt.setAvatar(qwUser.getAvatar());
                    conversationExt.setRemark("");
                    //判断是与联系人的会话还是企业通讯录的会话并组装ext
                    QwContact qwContact = qwContactMapper.selectQwContactByUserId(qwMessage.getReceiverId());
                    QwUser qwUser1 = qwUserMapper.selectQwUserByUserId(qwMessage.getReceiverId());
                    //判断是否为内部联系人
                    QwInnerContact innerContact = innerContactMapper.selectInnerContactByUserId(qwUser.getCorpId(), qwMessage.getReceiverId());
                    if (qwContact != null){
                        conversationExt1.setUserId(qwContact.getUserId());
                        conversationExt1.setNickName(qwContact.getNickName());
                        conversationExt1.setAvatar(qwContact.getAvatar());
                        conversationExt1.setRemark(qwContact.getRemark());
                    }else if (innerContact != null){
                        conversationExt1.setUserId(innerContact.getUserId());
                        conversationExt1.setNickName(innerContact.getNickName());
                        conversationExt1.setAvatar(innerContact.getAvatar());
                        conversationExt1.setRemark(innerContact.getAliasName());
                    }else {
                        //表中没有时调用联系人详情接口
                        QwContactVO qwContactVO = qwContactService.detail(deviceId,qwMessage.getReceiverId());
                        if (qwContactVO != null){
                            conversationExt1.setUserId(qwContactVO.getUserId());
                            conversationExt1.setNickName(qwContactVO.getNickName());
                            conversationExt1.setAvatar(qwContactVO.getAvatar());
                            conversationExt1.setRemark(qwContactVO.getRemark());
                        }
                    }
                    //当为接收方时
                }else if (qwMessage.getReceiverId().equals(qwUser.getUserId())){
                    conversationExt.setUserId(qwUser.getUserId());
                    conversationExt.setNickName(qwUser.getNickName());
                    conversationExt.setAvatar(qwUser.getAvatar());
                    conversationExt.setRemark("");
                    //判断是与联系人的会话还是企业通讯录的会话并组装ext
                    QwContact qwContact = qwContactMapper.selectQwContactByUserId(qwMessage.getSenderId());
                    QwUser qwUser1 = qwUserMapper.selectQwUserByUserId(qwMessage.getSenderId());
                    //判断是否为内部联系人
                    QwInnerContact innerContact = innerContactMapper.selectInnerContactByUserId(qwUser.getCorpId(), qwMessage.getSenderId());
                    if (qwContact != null){
                        conversationExt1.setUserId(qwContact.getUserId());
                        conversationExt1.setNickName(qwContact.getNickName());
                        conversationExt1.setAvatar(qwContact.getAvatar());
                        conversationExt1.setRemark(qwContact.getRemark());
                    }else if (innerContact != null){
                        conversationExt1.setUserId(innerContact.getUserId());
                        conversationExt1.setNickName(innerContact.getNickName());
                        conversationExt1.setAvatar(innerContact.getAvatar());
                        conversationExt1.setRemark(innerContact.getAliasName());
                    }else {
                        //表中不存在时调用联系人详情接口
                        QwContactVO qwContactVO = qwContactService.detail(deviceId,qwMessage.getSenderId());
                        if (qwContactVO != null){
                            conversationExt1.setUserId(qwContactVO.getUserId());
                            conversationExt1.setNickName(qwContactVO.getNickName());
                            conversationExt1.setAvatar(qwContactVO.getAvatar());
                            conversationExt1.setRemark(qwContactVO.getRemark());
                        }
                    }
                }
                List<QwConversationExt> extList = new ArrayList<>();
                extList.add(conversationExt);
                extList.add(conversationExt1);
                //将组装的ext转换成json塞到会话表
                String ext = toJson(extList);
                conversation.setExt(ext);
                conversation.setCreateTime(new Date());
                //新建会话
                conversationMapper.insertQwConversation(conversation);
            }
        }
        else {
            //对激活的群聊进行增同步、判断群聊是否存在
            QwRoom qwRoom = qwRoomMapper.selectRoomByRoomId(qwMessage.getRoomId());
            if (qwRoom == null){
                QwRoom qwRoom1 = new QwRoom();
                Map<String,Object> roomMap = new HashMap<>();
                roomMap.put("roomId",qwMessage.getRoomId());
                //获取群详情
                QwRoomListVO vo = QwAllUtil.roomDetail(roomMap,deviceId);
                if (vo != null){
                    BeanUtils.copyProperties(vo,qwRoom1);
                    qwRoom1.setAdminList(toJson(vo.getAdminList()));
                    List<QwRoomMember> roomMembers = vo.getMemberList();
                    for (QwRoomMember qwRoomMember:roomMembers){
                        QwRoomMember newRoomMember = qwRoomMemberMapper.selectQwRoomMemberByUserId(qwRoomMember.getUserId(),qwMessage.getRoomId());
                        if (newRoomMember == null){
                            qwRoomMember.setRoomId(vo.getRoomId());
                            qwRoomMemberMapper.insertQwRoomMember(qwRoomMember);
                        }
                    }
                    qwRoomMapper.insertQwRoom(qwRoom1);
                }
            }else {
                QwRoomMember qwRoomMember = qwRoomMemberMapper.selectQwRoomMemberByUserId(qwMessage.getSenderId(),qwMessage.getRoomId());
                if (qwRoomMember==null){
                    qwRoom = new QwRoom();
                    Map<String,Object> roomMap = new HashMap<>();
                    roomMap.put("roomId",qwMessage.getRoomId());
                    //获取群详情
                    QwRoomListVO vo = QwAllUtil.roomDetail(roomMap,deviceId);
                    BeanUtils.copyProperties(vo,qwRoom);
                    qwRoom.setAdminList(toJson(vo.getAdminList()));
                    List<QwRoomMember> roomMembers = vo.getMemberList();
                    for (QwRoomMember member:roomMembers){
                        QwRoomMember qwRoomMember1 = qwRoomMemberMapper.selectQwRoomMemberByUserId(member.getUserId(), qwRoom.getRoomId());
                        if (qwRoomMember1==null){
                            member.setRoomId(qwRoom.getRoomId());
                            qwRoomMemberMapper.insertQwRoomMember(member);
                            qwEventAuthService.updateRoomAncestors(qwRoom.getRoomId());
                        }
                    }
                }
            }
            //群聊取roomId为会话id
            qwMessage.setConversationId(qwMessage.getRoomId().toString());
            //更新message的会话id
            qwMessageMapper.updateConversationId(qwMessage.getId(),qwMessage.getRoomId().toString());
            QwConversation qwConversation = conversationMapper.selectByConversationId(qwMessage.getRoomId().toString());
            //判断会话是否存在
            if (qwConversation != null){
//                    qwMessage.setConversationId(qwConversation.getConversationId());
                conversation.setLastMessageId(qwMessage.getId());
                conversation.setConversationId(qwConversation.getConversationId());
                conversationMapper.updateLastMessage(conversation);
            }else {
                //不存在时新建会话
                conversation.setConversationId(qwMessage.getRoomId().toString());
                conversation.setType(1L);
                conversation.setDeviceId(deviceId);
                Map<String,Object> roomMap = new HashMap<>();
                roomMap.put("roomId",qwMessage.getRoomId());
                QwRoomListVO qwRoom1 = QwAllUtil.roomDetail(roomMap,deviceId);
                //群成员转换成逗号间隔的String
                List<QwRoomMember> roomMembers = qwRoom1.getMemberList();
                if (roomMembers == null && roomMembers.size() == 0){
                    logger.error("获取群成员列表为空：{}",qwRoom1);
                }
                String ancestors = roomMembers.stream()
                        .map(QwRoomMember::getUserId)
                        .map(Object::toString)
                        .collect(Collectors.joining(","));
                conversation.setAncestors(ancestors);
                //组装群聊会话的ext
                Map<String,Object> extMap = new HashMap<>();
                extMap.put("roomId",qwMessage.getRoomId());
                extMap.put("roomAvatar","https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
                extMap.put("roomName",qwRoom1.getRoomName());
                String ext = toJson(extMap);
                conversation.setExt(ext);
                //会话最新一条消息id为消息id
                conversation.setLastMessageId(qwMessage.getId());
                conversation.setCreateTime(new Date());
                conversationMapper.insertQwConversation(conversation);
            }
        }

    }

    //创建Oss的url
    public String createOssUrl(QwCDNDownload cdnDownload,String deviceId){
        Map<String,Object> downloadMap = cdnDownload.toMap();
        byte[] fileBytes = QwDownloadUtil.cdnDownload(downloadMap,deviceId);
        String suffix = cdnDownload.getFileName().substring(cdnDownload.getFileName().lastIndexOf("."));
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(fileBytes, suffix);
        return url;
    }

    //创建Oss的url
    public String createOssImageUrl(QwCDNDownload cdnDownload,String deviceId) throws IOException {
        Map<String,Object> downloadMap = cdnDownload.toMap();

        String base64Url= QwDownloadUtil.cdnDownloadBase64(downloadMap,deviceId);
        MultipartFile file=QwDownloadUtil.base64ToMultipart(base64Url);

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(file.getBytes(), suffix);
        return url;
    }

    /**
     * 升序组和senderId和receiverId
     */
    public String sortAndCombine(String senderId, String receiverId) {
        // 将 senderId 和 receiverId 放入数组，进行排序
        String[] ids = {senderId, receiverId};
        Arrays.sort(ids);
        // 组合排序后的值为一个字符串，并返回
        return ids[0] + ids[1];
    }

    public  String saveFileLocally(QwCDNDownload cdnDownload, String deviceId, String targetDirectory) throws IOException {
        Map<String, Object> downloadMap = cdnDownload.toMap();
        byte[] fileBytes = QwDownloadUtil.cdnDownload(downloadMap, deviceId);

        // 生成一个唯一的文件名
        String uniqueFileName = UUID.randomUUID().toString();

        // 构建目标文件路径
        String targetFilePath = targetDirectory + File.separator + uniqueFileName + cdnDownload.getFileName();

        // 将字节数组写入目标文件
        Path tempFilePath = Files.createTempFile(null, null);
        Files.write(tempFilePath, fileBytes, StandardOpenOption.CREATE);

        // 复制临时文件到目标位置
        Path targetPath = Paths.get(targetFilePath);
        Files.copy(tempFilePath, Paths.get(targetFilePath), StandardCopyOption.REPLACE_EXISTING);

        // 删除临时文件
        Files.deleteIfExists(tempFilePath);
        // 获取文件类型
        String fileType = Files.probeContentType(targetPath);

        // 返回文件类型
        return fileType;
    }

    //判断文件显示类型
    public Integer fileShowType(String fileName){
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (suffix.equalsIgnoreCase(".docx") || suffix.equalsIgnoreCase(".doc") || suffix.equalsIgnoreCase(".dot") || suffix.equalsIgnoreCase(".dotx")){
            return fileShowTypeEnum.WORD.getValue();
        }else if (suffix.equalsIgnoreCase(".xls") || suffix.equalsIgnoreCase(".xlsx") || suffix.equalsIgnoreCase(".xlsm") || suffix.equalsIgnoreCase(".xlsb")){
            return fileShowTypeEnum.EXCEL.getValue();
        }else if (suffix.equalsIgnoreCase(".zip") || suffix.equalsIgnoreCase(".rar") || suffix.equalsIgnoreCase(".tar") || suffix.equalsIgnoreCase(".7z")) {
            return fileShowTypeEnum.RAR.getValue();
        }else if (suffix.equalsIgnoreCase(".txt")){
            return fileShowTypeEnum.TXT.getValue();
        }else if (suffix.equalsIgnoreCase(".pdf")){
            return fileShowTypeEnum.PDF.getValue();
        }else if (suffix.equalsIgnoreCase(".ppt") || suffix.equalsIgnoreCase(".pptx") || suffix.equalsIgnoreCase(".pot") || suffix.equalsIgnoreCase(".potx")){
            return fileShowTypeEnum.PPT.getValue();
        }else {
            return fileShowTypeEnum.UNKNOWN.getValue();
        }
    }

    @Autowired
    private QwAccountMapper qwAccountMapper;

    @Autowired
    private IQwMessageService qwMessageService;

    @Autowired
    private QwForbiddenMessageMapper qwForbiddenMessageMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private ICrmMsgService msgService;


    public void addForbiddenMessage(QwMessage qwMessage,String deviceId){
        HasForbiddenWord hasForbiddenWord = hasForbiddenWord(qwMessage.getContent());
        if (hasForbiddenWord.getIsHas()){
            QwForbiddenMessage qwForbiddenMessage = new QwForbiddenMessage();
            qwForbiddenMessage.setMessageId(qwMessage.getId());
            qwForbiddenMessage.setContent(qwMessage.getContent());
            qwForbiddenMessage.setConversationId(qwMessage.getConversationId());
            QwAccountListVO account = qwAccountMapper.selectCompany(deviceId);
            qwForbiddenMessage.setCompanyId(account.getCompanyId());
            qwForbiddenMessage.setCompanyUserId(account.getCompanyUserId());
            qwForbiddenMessage.setAccount(account.getAccount());
            qwForbiddenMessage.setSendTime(qwMessage.getSendTime());
            qwForbiddenMessage.setCreateTime(new Date());
            qwForbiddenMessage.setWordId(hasForbiddenWord.getWordId());
            //新增到违禁消息列表
            qwForbiddenMessageMapper.insertQwForbiddenMessage(qwForbiddenMessage);
//            QwMessageText qwMessageText = new QwMessageText();
//            qwMessageText.setContent(account.getCompanyName()+" "+account.getCompanyUserName()+"，在账号"+account.getAccount()+" 聊天中存在异常，消息编号为："+qwMessage.getId()+"  请注意查看");
//            //向管理员发送预警消息
//            qwMessageService.sendWarningMessage(qwMessageText);
            Long companyUserId = companyUserMapper.selectCompanyAdminByCompanyId(qwForbiddenMessage.getCompanyId());
            msgService.insertCrmMsg(new CrmMsg(3,account.getCompanyUserName()+"|"+account.getAccount(),"违禁消息编号："+qwForbiddenMessage.getId(),account.getCompanyId(), companyUserId, null));
            String message = account.getCompanyUserName()+"，在账号"+account.getAccount()+" 聊天中存在异常，消息编号为："+qwForbiddenMessage.getId()+"  请注意查看";
            sendSocket("warningMsg",message,companyUserId);
        }
    }

    public HasForbiddenWord hasForbiddenWord(String message) {
        List<QwForbiddenWords> forbiddenWords = qwForbiddenWordsService.QwForbiddenWordsList();
        HasForbiddenWord hasForbiddenWord = new HasForbiddenWord();
        for (QwForbiddenWords forbiddenWord : forbiddenWords) {
            if (message.toLowerCase().contains(forbiddenWord.getWord().toLowerCase())) {
                hasForbiddenWord.setWordId(forbiddenWord.getId());
                hasForbiddenWord.setWord(forbiddenWord.getWord());
                hasForbiddenWord.setIsHas(true);
                return hasForbiddenWord; // 找到匹配的禁用词，立即返回
            }
        }
        hasForbiddenWord.setIsHas(false); // 循环结束仍未找到匹配的禁用词
        return hasForbiddenWord;
    }



    public void sendSocket(String cmd,String message,Long companyUserId){
        MsgBean msgBean=new MsgBean();
        msgBean.setCmd(cmd);
        msgBean.setMsg(message);
        JSONObject params=new JSONObject();
        params.put("id","u:"+companyUserId);
        params.put("message",JSONObject.toJSONString(msgBean));
        String url = "http://localhost:7018/sendInfo";
//        String url = "https://im.yjf.runtzh.com/sendInfo";
        HttpUtils.doPost(url,JSONObject.toJSONString(params));
        logger.info("发送预警：{}",message+companyUserId);
    }


}
