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.common.utils.DateUtils;
import com.fs.pay.pay.util.PayUtil;
import com.fs.qw.domain.*;
import com.fs.qw.event.EventMessageText;
import com.fs.qw.mapper.*;
import com.fs.qw.param.CreateConParam;
import com.fs.qw.service.IQwConversationService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.QwContactListVO;
import com.fs.qw.vo.QwContactVO;
import com.fs.qw.vo.QwRoomMember;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

import static com.fs.qw.service.impl.QwContactServiceImpl.getFormattedNickname;
import static com.fs.qw.utils.QwUtil.toJson;

/**
 * 企微功能账号管理Service业务层处理
 *
 * @author fs
 * @date 2023-08-23
 */
@Service
public class QwConversationServiceImpl implements IQwConversationService {
    @Autowired
    private QwConversationMapper qwConversationMapper;

    @Autowired
    private QwMessageMapper qwMessageMapper;

    @Autowired
    private QwRoomMapper qwRoomMapper;

    @Autowired
    private QwRoomMemberMapper qwRoomMemberMapper;

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwContactMapper qwContactMapper;

    /**
     * 查询企微会话管理
     *
     * @return 企微会话管理
     */
    @Override
    public QwConversation selectQwConversationById(String conversationId)
    {
        return qwConversationMapper.selectConByConversationId(conversationId);
    }

    /**
     * 查询企微会话管理 列表
     *
     * @param qwConversation 企微会话管理
     * @return 企微会话管理
     */
    @Override
    public List<QwConversation> selectQwConversationList(QwConversation qwConversation)
    {
        return qwConversationMapper.selectQwConversationList(qwConversation);
    }

    /**
     * 新增企微会话管理
     *
     * @param qwConversation 企微会话管理
     * @return 结果
     */
    @Override
    public int insertQwConversation(QwConversation qwConversation)
    {
        qwConversation.setCreateTime(DateUtils.getNowDate());
        return qwConversationMapper.insertQwConversation(qwConversation);
    }

    /**
     * 修改企微会话管理
     *
     * @param qwConversation 企微会话管理
     * @return 结果
     */
    @Override
    public int updateQwConversation(QwConversation qwConversation)
    {
        qwConversation.setUpdateTime(DateUtils.getNowDate());
        return qwConversationMapper.updateQwConversation(qwConversation);
    }

    /**
     * 批量删除企微会话管理
     *
     * @param ids 需要删除的企微会话管理 ID
     * @return 结果
     */
    @Override
    public int deleteQwConversationByIds(Long[] ids)
    {
        return qwConversationMapper.deleteQwConversationByIds(ids);
    }

    /**
     * 删除企微会话管理 信息
     *
     * @param id 企微会话管理 ID
     * @return 结果
     */
    @Override
    public int deleteQwConversationById(Long id)
    {
        return qwConversationMapper.deleteQwConversationById(id);
    }

    @Override
    public List<QwContactListVO> selectQwConversationByUserId(String userId) {
        List<QwContactListVO> listVOS = new ArrayList<>();
        List<QwConversation> list = qwConversationMapper.selectConByUSerId(userId);
        for (QwConversation conversation : list){
//            String contact = extractUserId(conversation.getAncestors(),userId);
            QwContactListVO listVO = new QwContactListVO();
            if(conversation.getType()==0){
                List<QwConversationExt> qwUsers = JSON.parseObject(conversation.getExt(), new TypeReference<List<QwConversationExt>>() {
                });
                for (QwConversationExt qwUser : qwUsers){
                    if (!qwUser.getUserId().toString().equals(userId)){
                        listVO.setId(qwUser.getUserId());
                        listVO.setConversationId(conversation.getConversationId());
                        //remark不为空时将昵称返回为remark
                        if (qwUser.getRemark()!=null&&!"".equals(qwUser.getRemark())){
                            listVO.setDisplayName(qwUser.getRemark());
                        }else {
                            listVO.setDisplayName(qwUser.getNickName());
                        }
                        listVO.setAvatar(qwUser.getAvatar());
                    }
                }
            }else{  //群聊
                QwRoom qwRoom=qwRoomMapper.selectRoomByRoomId(Long.valueOf(conversation.getConversationId()));
                listVO.setId(qwRoom.getRoomId());
                listVO.setConversationId(conversation.getConversationId());
                listVO.setAvatar("https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
                listVO.setIsGroup(true);
                listVO.setDisplayName(qwRoom.getRoomName());
            }
            QwMessage qwMessage = qwMessageMapper.selectQwMessageById(conversation.getLastMessageId());
            if (qwMessage.getMessageType() == 1){
                listVO.setLastContent(qwMessage.getContent());
            }else if (qwMessage.getMessageType() == 2){
                listVO.setLastContent("[图片]");
            }else if (qwMessage.getMessageType()==3){
                listVO.setLastContent("[视频]");
            }else if (qwMessage.getMessageType()==4){
                listVO.setLastContent("[文件]");
            }else if (qwMessage.getMessageType()==5){
                listVO.setLastContent("[语音]"+""+qwMessage.getDuration()+"\"");
            }else if (qwMessage.getMessageType()==7){
                listVO.setLastContent("[动画表情]");
            }else {
                listVO.setLastContent("");
            }
            listVO.setUnread(0);
            listVO.setLastSendTime(qwMessage.getSendTime()*1000);
            listVOS.add(listVO);
        }
        return listVOS;
    }


    @Override
    public QwContactListVO selectQwConversationBycId(String conversationId,String userId) {
            QwConversation conversation = qwConversationMapper.selectConByConversationId(conversationId);
            //String contact = extractUserId(conversation.getAncestors(),userId);
            QwContactListVO listVO = new QwContactListVO();
            if(conversation.getType()==0){
                List<QwConversationExt> qwUsers = JSON.parseObject(conversation.getExt(), new TypeReference<List<QwConversationExt>>() {
                });
                for (QwConversationExt qwUser : qwUsers){
                    if (!qwUser.getUserId().toString().equals(userId)){
                        listVO.setId(qwUser.getUserId());
                        listVO.setConversationId(conversation.getConversationId());
                        if (qwUser.getRemark()!=null&&!"".equals(qwUser.getRemark())){
                            listVO.setDisplayName(qwUser.getRemark());
                        }else {
                            listVO.setDisplayName(qwUser.getNickName());
                        }
                        listVO.setAvatar(qwUser.getAvatar());
                    }
                }
            }else{  //群聊
                QwRoom qwRoom=qwRoomMapper.selectRoomByRoomId(Long.valueOf(conversation.getConversationId()));
                listVO.setId(qwRoom.getRoomId());
                listVO.setConversationId(conversation.getConversationId());
                listVO.setAvatar("https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
                listVO.setIsGroup(true);
                listVO.setDisplayName(qwRoom.getRoomName());
            }
            QwMessage qwMessage = qwMessageMapper.selectQwMessageById(conversation.getLastMessageId());
            if (qwMessage.getMessageType() == 1){
                listVO.setLastContent(qwMessage.getContent());
            }else if (qwMessage.getMessageType() == 2){
                listVO.setLastContent("[图片]");
            }else if (qwMessage.getMessageType()==3){
                listVO.setLastContent("[视频]");
            }else if (qwMessage.getMessageType()==4){
                listVO.setLastContent("[文件]");
            }else if (qwMessage.getMessageType()==5){
                listVO.setLastContent("[语音]"+""+qwMessage.getDuration()+"\"");
            }else if (qwMessage.getMessageType()==7){
                listVO.setLastContent("[动画表情]");
            }else {
                listVO.setLastContent("");
            }
            listVO.setUnread(0);
            listVO.setLastSendTime(qwMessage.getSendTime()*1000);
            return listVO;
    }

    @Override
    public R createConversation(CreateConParam param) {
        QwConversation qwConversation1 = new QwConversation();
        //判断是否群聊
        if (param.getIsRoom()){
            //判断会话是否存在
            QwConversation qwConversation = qwConversationMapper.selectConByConversationId(param.getContactUserId().toString());
            if (qwConversation==null){
            //组装会话数据
                qwConversation1.setConversationId(param.getContactUserId().toString());
                qwConversation1.setType(1L);
                //群成员转换成逗号间隔的String
                List<QwRoomMember> roomMembers = qwRoomMemberMapper.selectQwRoomMemberByRoomId(param.getContactUserId());
                String ancestors = roomMembers.stream()
                        .map(QwRoomMember::getUserId)
                        .map(Object::toString)
                        .collect(Collectors.joining(","));
                qwConversation1.setAncestors(ancestors);
                QwRoom qwRoom = qwRoomMapper.selectRoomByRoomId(param.getContactUserId());
                //组装群聊会话的ext
                Map<String,Object> extMap = new HashMap<>();
                extMap.put("roomId",qwRoom.getRoomId());
                extMap.put("roomAvatar","https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
                extMap.put("roomName",qwRoom.getRoomName());
                String ext = toJson(extMap);
                qwConversation1.setExt(ext);
                qwConversation1.setCreateTime(new Date());
            }else {
                return R.ok().put("data",qwConversation);
            }
        }else {
            //不为群聊时
            //组装会话id
            String conver = new QwEventMessageServiceImpl().sortAndCombine(param.getUserId().toString(),param.getContactUserId().toString());
            String conversationId = DigestUtils.md5Hex(conver);
            QwConversation qwConversation = qwConversationMapper.selectConByConversationId(conversationId);
            //会话不存在时
            if (qwConversation==null){
                qwConversation1.setConversationId(conversationId);
                qwConversation1.setType(0L);
                qwConversation1.setAncestors(param.getContactUserId()+","+param.getUserId());
                qwConversation1.setCreateTime(new Date());
                QwUser qwUser = qwUserMapper.selectQwUserByUserId(param.getUserId());
                QwContact qwContact = qwContactMapper.selectQwContactByUserId(param.getContactUserId());
                QwConversationExt conversationExt1 = new QwConversationExt();
                conversationExt1.setUserId(qwUser.getUserId());
                conversationExt1.setNickName(qwUser.getNickName());
                conversationExt1.setRemark("");
                conversationExt1.setAvatar(qwUser.getAvatar());
                QwConversationExt conversationExt2 = new QwConversationExt();
                conversationExt2.setUserId(qwContact.getUserId());;
                conversationExt2.setAvatar(qwContact.getAvatar());
                conversationExt2.setNickName(qwContact.getNickName());
                conversationExt2.setRemark(qwContact.getRemark());
                List<QwConversationExt> extList = new ArrayList<>();
                extList.add(conversationExt1);
                extList.add(conversationExt2);
                String ext = toJson(extList);
                qwConversation1.setExt(ext);
            }
            else {
                return R.ok().put("data",qwConversation);
            }
        }
        return R.ok().put("data",qwConversation1);
    }

    @Override
    public int selectConType(String conversationId) {
        return qwConversationMapper.selectConType(conversationId);
    }

    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;
    }
}
