package com.tourism.webadmin.app.website.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tourism.common.core.object.TokenData;
import com.tourism.webadmin.app.website.controller.SystemMessageController;
import com.tourism.webadmin.app.website.dto.*;
import com.tourism.webadmin.app.website.service.TourGroupService;
import com.tourism.webadmin.app.website.service.TourMemberService;
import com.tourism.webadmin.app.website.vo.LastTourMessageVo;
import com.tourism.webadmin.app.website.vo.MainMemberVo;
import com.tourism.webadmin.back.dao.TourImMemberMapper;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.model.constant.IsTrue;
import com.tourism.webadmin.back.model.constant.NoticeType;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.enums.*;
import com.tourism.webadmin.strategy.dto.FocusDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
public class TourMemberImpl extends ServiceImpl<TourImMemberMapper, TourImMember> implements TourMemberService {

    @Autowired
    private TourImMemberMapper tourImMemberMapper;
    @Autowired
    private TourUserService tourUserService;
    @Autowired
    private TourImMessageService tourImMessageService;
    @Autowired
    private TourImGroupService tourImGroupService;
    @Autowired
    private TourGroupService tourGroupService;
    @Autowired
    private TourFansService tourFansService;
    @Autowired
    private TourImGroupInvitationService tourImGroupInvitationService;
    @Autowired
    private SystemMessageController systemMessageController;

    @Override
    public UserMainMemberVo getTourMemberList(GetMainMemberDto params,Long userId) {

        //获取全部会话列表
        List<MainMemberVo>  list=tourImMemberMapper.getTourMemberList(userId);

        //登录账户信息
        TourUser user = tourUserService.getById(userId);

        UserMainMemberVo userMainMemberVo = new UserMainMemberVo();

        //登录账户信息
        userMainMemberVo.setTourUser(user);
        //会话列表为空
        if(list.isEmpty()){
            return userMainMemberVo;
        }
        //群聊ID ->会话详情
        Map<String, MainMemberVo> map = new HashMap<>();
        for (MainMemberVo mainMemberVo : list) {
            map.put(mainMemberVo.getGroupId(), mainMemberVo);
        }
        //群聊ids
        List<String> collect = list.stream().map(MainMemberVo::getGroupId).collect(Collectors.toList());

        //全部群聊对应的用户
        Map<String, Set<TourUser>> userByGroupId = getUserByGroupId(collect);

        //获取群聊ID
        List<String> group = list.stream().filter(o -> o.getNoticeType().equals(2)).map(MainMemberVo::getGroupId).collect(Collectors.toList());
        //全部群聊信息
        HashMap<String, TourImGroup> groupId = new HashMap<>();
        if(!group.isEmpty()){
            List<TourImGroup> tourImGroups = tourGroupService.getBaseMapper().selectBatchIds(group);
            for (TourImGroup tourImGroup : tourImGroups) {
                groupId.put(tourImGroup.getId().toString(),tourImGroup);
            }
        }
        //群聊对应的用户
        Map<String, Set<TourUser>> users = getUserByGroupId(collect);
        if(!ObjectUtil.isEmpty(users)){
            users.forEach((k, v) -> {
                MainMemberVo mainMemberVo = map.get(k);
                if(mainMemberVo.getNoticeType().equals(1)){
                    //单聊
                    for (TourUser tourUser : v) {
                        if(tourUser.getUserId().toString().equals(mainMemberVo.getToUserId())){
                            //头像
                            mainMemberVo.setHeadImage(tourUser.getHeadImageUrl());
                            if(ObjectUtil.isEmpty(mainMemberVo.getGroupRemark())){
                                //如果备注为空 则为对方名字
                                mainMemberVo.setGroupRemark(tourUser.getShowName());
                            }
                        }
                    }
                }else {
                    //群聊
                    if(ObjectUtil.isEmpty(mainMemberVo.getGroupRemark())){
                        TourImGroup g = groupId.get(k);
                        if(!ObjectUtil.isEmpty(g)){
                            mainMemberVo.setGroupRemark(g.getGroupName());
                        }
                    }
                }
            });
        }

        for (MainMemberVo mainMemberVo : list) {
            //当前群聊群全部用户
            Set<TourUser> tourUsers = userByGroupId.get(mainMemberVo.getGroupId());
            //单聊不用填充
            if(ObjectUtil.isEmpty(tourUsers)||mainMemberVo.getNoticeType().equals(1)) continue;
            //获取当前群聊10人的头像逗号分隔
            ArrayList<String> image = new ArrayList<>();
            //头像
            if(mainMemberVo.getGroupId().equals(SystemDefaultHead.INTERACT_USERID_OR_GROUPID.getCode().toString())){
                mainMemberVo.setHeadImage(SystemDefaultHead.INTERACT_USERID_OR_GROUPID.getHead());
                mainMemberVo.setGroupRemark(SystemDefaultHead.INTERACT_USERID_OR_GROUPID.getName());
            }else if(mainMemberVo.getGroupId().equals(SystemDefaultHead.FOCUS_USERID_OR_GROUPID.getCode().toString())){
                mainMemberVo.setHeadImage(SystemDefaultHead.FOCUS_USERID_OR_GROUPID.getHead());
                mainMemberVo.setGroupRemark(SystemDefaultHead.FOCUS_USERID_OR_GROUPID.getName());
            }else if(mainMemberVo.getGroupId().equals(SystemDefaultHead.SYSTEM_USERID_OR_GROUPID.getCode().toString())){
                mainMemberVo.setHeadImage(SystemDefaultHead.SYSTEM_USERID_OR_GROUPID.getHead());
                mainMemberVo.setGroupRemark(SystemDefaultHead.SYSTEM_USERID_OR_GROUPID.getName());
            }else {
                int i=0;
                for (TourUser tourUser : tourUsers) {
                    if(i>=10) break;
                    image.add(tourUser.getHeadImageUrl());
                    i++;
                }
            }
            mainMemberVo.setDfGroupImage(image);
        }

        //获取当前会话最后一条消息
        List<TourImMessage> message  = tourImMemberMapper.selectLastMessage(collect,TokenData.takeFromRequest().getUserId());
        //获取用户当前群聊的未读消息数量
        QueryWrapper<TourImMessage> query=new QueryWrapper<TourImMessage>().
                select("group_id, COUNT(*) as unreadCount")
                .notLike("read_by_users",TokenData.takeFromRequest().getUserId())
                .eq("revocation_tag",0)
                .groupBy("group_id");
        List<Map<String, Object>> maps = tourImMessageService.getBaseMapper().selectMaps(query);
        //获取未读消息数量  groupId->number
        Map<Long, Integer> unreadCountMap = maps.stream()
                .collect(Collectors.toMap(
                        itemMap -> (Long) itemMap.get("group_id"),
                        itemMap -> ((Long) itemMap.get("unreadCount")).intValue()
                ));
        //最后一条消息  groupId->message
        HashMap<Long, TourImMessage> messageHashMap = new HashMap<>();
        for (TourImMessage tourImMessage : message) {
            messageHashMap.put(tourImMessage.getGroupId(), tourImMessage);
        }
        for (String s : collect) {
            if(s.equals("-2")||s.equals("-3")) continue;
            MainMemberVo mainMemberVo = map.get(s);
            Long l = Long.valueOf(s);
            Integer i = unreadCountMap.get(l);
            int num=i==null? 0 : i;
            mainMemberVo.setUnreadMessageCount(num);
            TourImMessage tourImMessage = messageHashMap.get(l);
            if(tourImMessage!=null){
                LastTourMessageVo bean = BeanUtil.toBean(tourImMessage, LastTourMessageVo.class);
                String messageContent = (String)bean.getMessageContent();
                SystemMessageDTO bean1 = JSONUtil.toBean(messageContent, SystemMessageDTO.class);
                bean.setMessageContent(bean1);
                mainMemberVo.setLastMessage(bean);
                //用于排序
                mainMemberVo.setCreateTime(tourImMessage.getCreateTime());
            }
        }
        //排序  1 系统 2 关注 3 互动 .....
        List<MainMemberVo> sort = sort(list);
        //处理前三个固定群聊的最后一条消息
        this.delLastSysMessage(sort);
        //处理三个固定群聊未读消息数量
        this.delUnreadMessageCount(sort);
        userMainMemberVo.setList(sort);
        return userMainMemberVo;
    }

    /**
     * 修改群或用户备注
     * @param params
     */
    @Override
    public boolean updateTourMember(UpdateTourMemberDto params) {

        Long userId = TokenData.takeFromRequest().getUserId();

        TourImMember member = getOne(Wrappers.<TourImMember>lambdaQuery().eq(TourImMember::getGroupId, params.getGroupId())
                .eq(TourImMember::getUserId, userId).eq(TourImMember::getDataState,1));
        if (Objects.isNull(member)) {
            return false;
        }
        boolean mark = ObjectUtil.isEmpty(params.getRemark());
        member.setGroupRemark(mark? "":params.getRemark());


        TourImGroup group = tourGroupService.getById(params.getGroupId());
        if(group.getNoticeType().equals(2)){
            boolean empty = ObjectUtil.isEmpty(params.getGroupNickname());
            //设置自己在群里的备注
            member.setGroupNickname(empty? "":params.getGroupNickname());
        }
        updateById(member);
        return true;
    }

    @Override
    public List<TourUser> memberLit(Long groupId) {
        Long userId = TokenData.takeFromRequest().getUserId();

        //我关注的用户列表
        List<TourFans>  fans = tourFansService.lambdaQuery().eq(TourFans::getCreateUserId, userId).list();

        //关注我的用户列表
        List<TourFans> myFans = tourFansService.lambdaQuery().eq(TourFans::getAttentionId, userId).list();

        List<TourFans> tourFans = fans.stream().filter(item -> myFans.stream().map(TourFans::getCreateUserId).anyMatch(id -> Objects.equals(item.getAttentionId(), id)))
                .collect(Collectors.toList());
        //获取互关用户ID
        List<Long> collect = tourFans.stream().map(TourFans::getAttentionId).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(collect)) return null;
        //获取互关用户详细信息
        List<TourUser> list = tourUserService.lambdaQuery().in(TourUser::getUserId, collect).list();

        TourImGroup group = tourImGroupService.getById(groupId);

        ArrayList<TourUser> userList = new ArrayList<>();
        if(group!=null&&group.getBannedStatus().equals(IsTrue.TRUE)){
            ArrayList<String> objects = new ArrayList<>();
            objects.add(groupId.toString());
            Map<String, Set<TourUser>> userByGroupId = getUserByGroupId(objects);
            Set<TourUser> tourUsers = userByGroupId.get(groupId.toString());
            if(ObjectUtil.isEmpty(tourUsers)){
                userList.addAll(list);
            }
            else {
                List<Long> userIds = tourUsers.stream().map(TourUser::getUserId).collect(Collectors.toList());
                return list.stream()
                        .filter(o -> !userIds.contains(o.getUserId()))  // 排除在群聊中的用户
                        .collect(Collectors.toList());
            }
        }
        return userList;
    }

    @Override
    @Transactional
    public void removeMember(RemoveMemberDto params) {
        //查询删除用户的member
        LambdaQueryWrapper<TourImMember> query = Wrappers.<TourImMember>lambdaQuery().eq(TourImMember::getGroupId, params.getGroupId())
                .eq(TourImMember::getGroupRole, GroupRole.ORDINARY_MEMBERS.getCode())
                .in(CollectionUtils.isNotEmpty(params.getDelUser()), TourImMember::getUserId, params.getDelUser())
                .eq(TourImMember::getDataState, 1);
        List<TourImMember> del = this.baseMapper.selectList(query);
        List<TourImMember> list = list(query);
        if(!del.isEmpty()){
            TourImMember tour = new TourImMember();
            tour.setDataState(-1);
            this.update(tour, query);
            TourImGroup byId = tourGroupService.getById(params.getGroupId());
            Long userId = TokenData.takeFromRequest().getUserId();
            for (TourImMember tourImMember : list) {
                SystemMessageDTO systemMessageDTO = new SystemMessageDTO();
                //移除群成员
                systemMessageDTO.setNoticeType(3);
                systemMessageDTO.setMessageType(0);
                systemMessageDTO.setContent("您已被移出群聊"+byId.getGroupName());
                systemMessageDTO.setTitle("群通知");
                systemMessageDTO.setGetUserId(tourImMember.getUserId().toString());//接收人
                systemMessageDTO.setSendUserId(userId.toString());//处理人
                systemMessageDTO.setGroupId(byId.getId().toString());//处理人
                systemMessageController.sendMessage(systemMessageDTO);
            }
        }
    }

    @Override
    public boolean updateSingleTourMember(UpdateSingleTourMemberDto params) {
        LambdaQueryWrapper<TourImMember> eq = Wrappers.<TourImMember>lambdaQuery()
                .eq(TourImMember::getGroupId, params.getGroupId())
                .eq(TourImMember::getDataState, 1)
                .eq(TourImMember::getUserId, TokenData.takeFromRequest().getUserId());
        TourImMember member = getOne(eq);
        if(ObjectUtil.isEmpty(member)){
           return false;
        }
        //置顶
        if(params.getIsTop()!=null){
            member.setIsTop(params.getIsTop());
        }
        //消息免打扰
        if(params.getIsNotDisturb()!=null){
            member.setIsNotDisturb(params.getIsNotDisturb());
        }
        //是否显示
        if(params.getIsShow()!=null){
            member.setIsShow(params.getIsShow());
        }
        //聊天背景
        if(params.getGroupBackImage()!=null){
            member.setGroupBackImage(params.getGroupBackImage());
        }
        return updateById(member);
    }

    /**
     * 邀请用户
     * @param group
     * @param userId
     */
    @Override
    @Transactional
    public boolean invite(TourImGroup group, List<TourUser> userId) {
        Long createUser = TokenData.takeFromRequest().getUserId();
        HashMap<Long, TourUser> map = new HashMap<>();
        for (TourUser tourUser : userId) {
            map.put(tourUser.getUserId(), tourUser);
        }

        //是不是管理员
        boolean admin = tourGroupService.isAdmin(group.getId(), createUser);
        //新增的集合
        ArrayList<TourImMember> isnert = new ArrayList<>();

        for (TourUser tourUser : userId) {
            //入群用户
            TourUser user = map.get(tourUser.getUserId());
            //群聊是否需要审核
            if(group.getIsNeedConfirm().equals(IsTrue.TRUE)&&!admin){
                //当前时间
                Date date = new Date();

                TourImGroupInvitation tourImGroupInvitation = new TourImGroupInvitation();
                tourImGroupInvitation.setGroupId(group.getId());
                //邀请人id
                tourImGroupInvitation.setInviter(createUser);
                //被邀请人id
                tourImGroupInvitation.setInvitee(user.getUserId());
                tourImGroupInvitation.setStatus(GroupAuthenticationState.UNKNOWN.getCode());

                tourImGroupInvitation.setCreateUserId(createUser);
                tourImGroupInvitation.setCreateTime(date);
                tourImGroupInvitation.setUpdateTime(date);
                tourImGroupInvitation.setUpdateUserId(createUser);
                tourImGroupInvitation.setDataState(1);

                tourImGroupInvitationService.save(tourImGroupInvitation);
                //开启群验证 && 非管理员 TODO 发送验证消息到管理员
                return true;
            }
            //管理员 || 不需要群验证 直接创建member
            TourImMember tourImMember = new TourImMember();
            tourImMember.setGroupId(group.getId());
            tourImMember.setGroupBackImage("");

            tourImMember.setUserId(user.getUserId());
            tourImMember.setCreateUserId(createUser);
            tourImMember.setCreateTime(new Date());
            tourImMember.setUpdateTime(new Date());
            tourImMember.setUpdateUserId(createUser);
            tourImMember.setGroupRole(GroupRole.ORDINARY_MEMBERS.getCode());
            isnert.add(tourImMember);
        }
        saveBatch(isnert);
        return true;
    }

    /**判断用户是否已经提交加群*/
    @Override
    public Set<Long> isExist(List<Long> userIds, Long groupId){
        TourImGroup group = tourGroupService.getById(groupId);
        if(group.getIsNeedConfirm().equals(1)){//开启群验证
            //判断是否已经发起的加群请求 并且 未处理
            List<TourImGroupInvitation> list = tourImGroupInvitationService.lambdaQuery().eq(TourImGroupInvitation::getGroupId, groupId)
                    .eq(TourImGroupInvitation::getStatus, GroupAuthenticationState.UNKNOWN.getCode())
                    .in(TourImGroupInvitation::getInvitee, userIds)
                    .list();
            if(!list.isEmpty()){
                return list.stream().map(TourImGroupInvitation::getInvitee).collect(Collectors.toSet());
            }
        }
        //判断是否进入了群聊
        List<TourImMember> list = lambdaQuery().eq(TourImMember::getGroupId, groupId).eq(TourImMember::getDataState,1).in(TourImMember::getUserId, userIds).list();
        if(!list.isEmpty()){
            return list.stream().map(TourImMember::getUserId).collect(Collectors.toSet());
        }
        return new HashSet<>();
    }

    /**
     *  根据群聊ID查询对应的用户对象
     * @param ids
     * @return  群聊 -> 用户集合
     */

    public Map<String,Set<TourUser>> getUserByGroupId(List<String> ids){
        if(ObjectUtil.isEmpty(ids))return null;
        LambdaQueryWrapper<TourImMember> query = new LambdaQueryWrapper<>();
        query.in(TourImMember::getGroupId,ids);
        query.eq(TourImMember::getDataState,1);
        query.eq(TourImMember::getIsShow,1);
        query.orderByAsc(TourImMember::getCreateTime);
        List<TourImMember> list = tourImMemberMapper.selectList(query);
        if (list.isEmpty()){
            return new HashMap<>();
        }
        //全部群聊用户 发起人
        Set<Long> collect = list.stream().map(TourImMember::getUserId).collect(Collectors.toSet());

        Set<Long> partner = list.stream().map(TourImMember::getPartnerId).collect(Collectors.toSet());

        collect.addAll(partner);

        HashMap<Long, TourUser> userMap = new HashMap<>();
        //全部人员信息
        List<TourUser> userList = tourUserService.lambdaQuery().in(TourUser::getUserId, collect).list();
        for (TourUser tourUser : userList) {
            userMap.put(tourUser.getUserId(),tourUser);
        }
        //群聊对应的用户列表
        Map<String, Set<TourUser>> map = new HashMap<>();
        // 群聊ID
        for (TourImMember l : list) {
            TourUser uUser = userMap.get(l.getUserId());
            TourUser pUser= userMap.get(l.getPartnerId());
            Set<TourUser> tourUsers = map.get(l.getGroupId().toString());
            if(tourUsers==null){
                tourUsers=new HashSet<TourUser>();
                map.put(l.getGroupId().toString(),tourUsers);
            }
            if(uUser!=null){
                tourUsers.add(uUser);
            }
            if(pUser!=null){
                tourUsers.add(pUser);
            }
        }
       return map;
    }

    @Override
    @Transactional
    public void createUserMember(String userId) {
        ArrayList<String>  groupId = new ArrayList<>();
        groupId.add(SystemDefaultHead.SYSTEM_USERID_OR_GROUPID.getCode().toString());
        groupId.add(SystemDefaultHead.FOCUS_USERID_OR_GROUPID.getCode().toString());
        groupId.add(SystemDefaultHead.INTERACT_USERID_OR_GROUPID.getCode().toString());

        ArrayList<TourImMember> tourImMembers = new ArrayList<>();

        for (String s : groupId) {
            TourImGroup group = tourImGroupService.getById(s);

            //遍历创建member对象
            TourImMember member = new TourImMember();
            member.setGroupId(group.getId());
            member.setGroupRole(GroupRole.ORDINARY_MEMBERS.getCode());

            member.setUserId(Long.valueOf(userId));
            member.setDataState(1);
            member.setUpdateTime(new Date());
            member.setUpdateUserId(group.getCreateUserId());
            member.setCreateUserId(group.getCreateUserId());

            tourImMembers.add(member);
        }
        this.saveBatch(tourImMembers);
    }


    /**
     *  根据置顶最后时间排序
     * @param list
     * @return
     */
    public List<MainMemberVo> sort(List<MainMemberVo> list){
        ArrayList<String> ls = new ArrayList<>();
        ls.add(SystemDefault.SYSTEM_USERID_OR_GROUPID.toString());
        ls.add(SystemDefault.FOCUS_USERID_OR_GROUPID.toString());
        ls.add(SystemDefault.INTERACT_USERID_OR_GROUPID.toString());
        //系统消息 、关注消息、互动消息
        List<MainMemberVo> collect = list.stream().filter(o -> ls.contains(o.getGroupId())).sorted(Comparator.comparing(MainMemberVo::getGroupId)).collect(Collectors.toList());
        //置顶
        List<MainMemberVo> collect1 = list.stream().filter(o -> o.getIsTop().equals(1L)&&!ls.contains(o.getGroupId())).sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
        //普通的会话
        List<MainMemberVo> collect2 = list.stream().filter(o -> o.getIsTop().equals(0L)&&!ls.contains(o.getGroupId())).sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
        collect.addAll(collect1);
        collect.addAll(collect2);
        return collect;
    }


    /**
     *  处理消息提示
     * @param list
     */
    public void delLastSysMessage(List<MainMemberVo> list){
        if(list.size()<3) return;
        //系统消息

        Long userId = TokenData.takeFromRequest().getUserId();
        //查询最后一条关注消息
        String n="\"getUserId\":"+"\""+userId+"\"";

        TourImMessage lastSysMessage = baseMapper.getLastSysMessage(NoticeType.NOTICE_SYSTEM+"",userId.toString());
        if(!ObjectUtil.isEmpty(lastSysMessage)){//系统消息
            String messageContent = lastSysMessage.getMessageContent();
            SystemMessageDTO bean = JSONUtil.toBean(messageContent, SystemMessageDTO.class);
            LastTourMessageVo bean1 = BeanUtil.toBean(lastSysMessage, LastTourMessageVo.class);
            bean.setMessageContent(bean.getContent());
            bean1.setMessageContent(bean);
            list.get(0).setLastMessage(bean1);
        }else {
            list.get(0).setLastMessage(null);
        }

        MainMemberVo mainMemberVo = list.get(1);//关注消息

        ArrayList<String> types = new ArrayList<>();
        String message="";
        types.add(NoticeType.NOTICE_FOCUS+"");

        TourImMessage lastMessage= baseMapper.getLast(types,n);
        LastTourMessageVo bean1 = BeanUtil.toBean(lastMessage, LastTourMessageVo.class);
        if(lastMessage!=null){
            String messageContent =(String) bean1.getMessageContent();

            message = NoticeTypeInfo.NOTICE_LIKE_COMMENT.getOperation();
            //关注消息类容对象
            FocusDTO bean = JSONUtil.toBean(messageContent, FocusDTO.class);
            //发送人ID
            message=bean.getTourUserVo().getShowName()+message;
            bean.setMessageContent(message);
            bean1.setMessageContent(bean);
        }
        mainMemberVo.setLastMessage(bean1);

        MainMemberVo vo = list.get(2);//互动消息
        types.clear();
        types.add(NoticeType.NOTICE_LIKE+"");
        types.add(NoticeType.NOTICE_COMMENT+"");
        types.add(NoticeType.NOTICE_COLLECTION+"");
        types.add(NoticeType.NOTICE_BROWSE+"");
        types.add(NoticeType.NOTICE_VISIT_HOME+"");
        types.add(NoticeType.NOTICE_COMMENT_MENTION+"");
        types.add(NoticeType.NOTICE_ARTICLE_MENTION+"");
        TourImMessage lsMessage= baseMapper.getLast(types,n);
        LastTourMessageVo be = BeanUtil.toBean(lsMessage, LastTourMessageVo.class);

        if(lsMessage!=null){
            String messageContent = (String) be.getMessageContent();

            //互动消息类容对象
            InteractionMessageDto bean = JSONUtil.toBean(messageContent, InteractionMessageDto.class);

            String type = bean.getNoticeType();
            String getUserId = lsMessage.getCreateUserId().toString();
            //业务
            String business="";
            if(BusinessType.TRAVELNOTES.getCode().equals(bean.getType())){
                //游记
                business="游记";
            }
            //发送人信息
            TourUser byId = tourUserService.getById(getUserId);

            switch (type)
            {
                case "4":
                    //用户 +关注了你
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_LIKE_COMMENT.getOperation();
                    break;
                case "5":
                    //用户 + 点赞 + 业务
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_LIKE.getOperation()+business;
                    break;
                case "6":
                    //用户 +评论了你
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_COMMENT.getOperation();
                    break;
                case "7":
                    //用户+收藏了你的 + 业务
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_COLLECTION.getOperation()+business;
                    break;
                case "8":
                    //用户+浏览了你的 + 业务
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_BROWSE.getOperation()+business;
                    break;
                case "9":
                    //用户 + 访问了你的主页
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_VISIT_HOME.getOperation();
                    break;
                case "10":
                    //用户 +评论提到了你
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_COMMENT_MENTION.getOperation();
                    break;
                case "11":
                    //用户 +评论提到了你
                    message=byId.getShowName()+NoticeTypeInfo.NOTICE_ARTICLE_MENTION.getOperation();
                    break;
            }
            bean.setMessageContent(message);

            be.setMessageContent(bean);
        }
        vo.setLastMessage(be);
    }


    public void delUnreadMessageCount(List<MainMemberVo> list){
        Long userId = TokenData.takeFromRequest().getUserId();
        ArrayList<String> ls = new ArrayList<>();
        ls.add(SystemDefault.SYSTEM_USERID_OR_GROUPID.toString());
        ls.add(SystemDefault.FOCUS_USERID_OR_GROUPID.toString());
        ls.add(SystemDefault.INTERACT_USERID_OR_GROUPID.toString());

        TourUser user = tourUserService.getById(userId);

        //所有未读消息数量
        List<TourImMessage> tourImMessages = baseMapper.getCount(ls, userId,user.getCreateTime());

        //群聊ID ->转消息List
        Map<Long, List<TourImMessage>> map = tourImMessages.stream().collect(Collectors.groupingBy(TourImMessage::getGroupId));
        int i=1;
        for (MainMemberVo mainMemberVo : list) {
            List<TourImMessage> tourImMessages1 = map.get(Long.valueOf(mainMemberVo.getGroupId()));
            mainMemberVo.setUnreadMessageCount(tourImMessages1==null? 0:tourImMessages1.size() );
            i++;
            if(i>3) break;
        }
    }
}
