package com.tourism.webadmin.app.website.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.page.PageMethod;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.core.annotation.DisableDataFilter;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.upload.BaseUpDownloader;
import com.tourism.common.core.upload.UpDownloaderFactory;
import com.tourism.common.core.upload.UploadResponseInfo;
import com.tourism.common.core.upload.UploadStoreInfo;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.common.redis.cache.SessionCacheHelper;
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.TourGroupInvitationVo;
import com.tourism.webadmin.app.website.vo.UserGroupVo;
import com.tourism.webadmin.app.website.vo.UserNameVo;
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.back.vo.TourImGroupTypeVo;
import com.tourism.webadmin.back.vo.TourImGroupVo;
import com.tourism.webadmin.back.vo.TourImMemberVo;
import com.tourism.webadmin.enums.MyAttentionStatus;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.xml.bind.DatatypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 类功能描述：
 *  群聊相关接口
 * @author 大春
 * @date 2025/01/06
 */

@Tag(name = "群聊")
@RestController
@DisableDataFilter
@Slf4j
@RequestMapping("/website/tourGroup")
public class TourGroupController {

    @Autowired
    private TourGroupService tourGroupService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TourImGroupService tourImGroupService;
    @Autowired
    private TourImMemberService tourImMemberService;
    @Autowired
    private TourFansService tourFansService;
    @Autowired
    private TourImGroupTypeService tourImGroupTypeService;
    @Autowired
    private TourMemberService tourMemberService;
    @Autowired
    private TourImGroupInvitationService tourImGroupInvitationService;
    @Autowired
    private UpDownloaderFactory upDownloaderFactory;
    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private SessionCacheHelper cacheHelper;
    @Autowired
    private TourImMessageService tourImMessageService;
    @Autowired
    private TourUserService tourUserService;


    /**
     *  创建群聊
     * @return {@link ResponseResult }<{@link List }<{@link TourUser }>>
     */
    @PostMapping("/createGroup")
    @Transactional
    public ResponseResult<String> createGroup(@RequestBody CreateGroupDto params){
        Long group = tourGroupService.createGroup(params);
        return ResponseResult.success(group.toString());
    }

    /**退出群聊*/
    @PostMapping("/exitGroup")
    @Transactional
    public ResponseResult<Void> exitGroup(@RequestBody Map<String,String> map){
        String groupId = map.get("groupId");
        if(ObjectUtil.isEmpty(groupId)){
            return ResponseResult.error("500","群聊不存在");
        }
        TourImGroup group = tourGroupService.getById(groupId);
        if(group==null) return ResponseResult.error("500","群不存在或被封禁");
        tourGroupService.exitGroup(group);
        return ResponseResult.success();
    }

    /**
     * 修改群信息(群聊操作)
     * @param groupDto
     * @return {@link ResponseResult }<{@link Void }>
     */
    @PostMapping("/updateGroup")
    @Transactional
    public ResponseResult<Boolean> updateGroup(@RequestBody UpdateGroupDto groupDto){
        TourImGroup group = tourGroupService.getById(groupDto.getGroupId());
        //登录账户ID
        Long userId = TokenData.takeFromRequest().getUserId();

        List<TourImMember> memberList = tourMemberService.list(new LambdaQueryWrapper<TourImMember>()
                .eq(TourImMember::getGroupId, group.getId())
                .eq(TourImMember::getDataState, 1)
                .eq(TourImMember::getUserId, TokenData.takeFromRequest().getUserId())
                .last("limit 1"));
        if (memberList!= null && !memberList.isEmpty()){
            if(!tourGroupService.isAdmin(memberList.get(0).getGroupId(), userId)){
                return ResponseResult.error("500","您不是群主或管理员，无法修改群信息");
            }
        }

        tourGroupService.updateGroup(groupDto,group);
        return ResponseResult.success(true);
    }

    /**
     * 创建群聊二维码
     * @param systemOs 0 pc 1 h51
     * @param groupId 群组id
     * @param response
     * @throws IOException
     */
    @GetMapping("/getGroupQR")
    @SaIgnore
    @DisableDataFilter
       public void getGroupQR(Integer systemOs,String groupId, HttpServletResponse response) throws IOException {
        //如果有则把base64转换成数组写回前端
        if (redisTemplate.hasKey(groupId)){
            byte[] bytes = DatatypeConverter.parseBase64Binary(redisTemplate.opsForValue().get(groupId).toString());
            response.setContentType("image/png");
            response.getOutputStream().write(bytes, 0, bytes.length);
            return;
        }
        QrConfig config = new QrConfig(600, 600);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(1);
        String path = "/mnt/logo.png";
        String logoPath = path;
        config.setImg(logoPath);
        // 设置前景色，二维码颜色（绿色）
        config.setForeColor(new Color(0, 0, 0));
        // 设置背景色（淡黄色）
        config.setBackColor(new Color(255, 255, 255));
        // 设置容错级别
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        byte[] pngArr = null;
        if (systemOs  == 0) {
           pngArr = QrCodeUtil.generatePng("https://www.xiaoyaotravel.com/chat?groupId="+groupId+"&time="+System.currentTimeMillis(), config);
        }else {
            pngArr = QrCodeUtil.generatePng("https://m.xiaoyaotravel.com/chat/group?groupId="+groupId+"&time="+System.currentTimeMillis(), config);
        }
        //转成base64存储
        String base64Binary = DatatypeConverter.printBase64Binary(pngArr);
        //base64设置7天过期
        redisTemplate.opsForValue().set(groupId, base64Binary,7, TimeUnit.DAYS);
        response.setContentType("image/png");
        response.getOutputStream().write(pngArr, 0, pngArr.length);
    }

    /**
     *  根据群ID查询群信息群成员列表
     * @param groupId
     * @return {@link ResponseResult }<{@link List }<{@link TourImGroupVo }>>
     */
    @GetMapping("/getGroupInfoAndMemberByGroupId")
    public ResponseResult<TourImGroupVo> getGroupInfoAndMemberByGroupId(Long groupId) {

        //用户身份验证
        TokenData tokenData = TokenData.takeFromRequest();
        if (tokenData == null) return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "用户未登录");
        Long userId = tokenData.getUserId();

        //参数校验
        if (groupId == null) return ResponseResult.success(null);
        //群查询
        TourImGroup tourImGroup = tourImGroupService.getByIdWithRelation(groupId, MyRelationParam.dictOnly());
        if (tourImGroup == null) return ResponseResult.success(null);
        //群状态判断
        TourImGroupVo tourImGroupVo = MyModelUtil.copyTo(tourImGroup, TourImGroupVo.class);
        //群是否被封禁
        if (tourImGroupVo.getBannedStatus()== IsTrue.FALSE) tourImGroupVo.setCodeShowStatus(2);
        //群是否被解散
        if (tourImGroup.getDataState() == -1) tourImGroupVo.setCodeShowStatus(3);
        //群成员列表
        TourImMember tourImMember = new TourImMember();
        tourImMember.setGroupId(tourImGroup.getId());
        tourImMember.setDataState(1);
        List<TourImMember> tourImMemberList = tourImMemberService.getTourImMemberList(tourImMember, null);
        if (tourImMemberList == null) return ResponseResult.success(null);
        List<TourImMemberVo> tourImMemberVos = MyModelUtil.copyCollectionTo(tourImMemberList, TourImMemberVo.class);
        List<String>  memberIds = tourImMemberVos.stream().map(TourImMemberVo::getUserId).toList();
        //查询用户信息
        List<TourUser> tourUserList = tourUserService.list(new LambdaQueryWrapper<TourUser>()
                .in(TourUser::getUserId, memberIds));

        tourImMemberVos.forEach(member -> {
            //填充头像 和群昵称
            tourUserList.stream().forEach(user -> {
                if (user.getUserId().toString().equals(member.getUserId())&&user.getHeadImageUrl()!=null){
                    member.setHeadImageUrl(user.getHeadImageUrl());
                    if (StringUtils.isEmpty(member.getGroupNickname())&& StringUtils.isNotEmpty(user.getShowName())){
                        member.setGroupNickname(user.getShowName());
                    }
                }
            });
        });
        //填充成员数量
        tourImGroupVo.setMemberCount(tourImMemberVos.size());

        //分别查找群主 管理员 普通成员
        List<TourImMemberVo> vos = new ArrayList<>(tourImMemberVos.stream().sorted(Comparator.comparingInt(TourImMemberVo::getGroupRole)).toList());
//        Collections.reverse(vos);
        //对ID进行加密
        for (TourImMemberVo vo : vos) {
            String id = vo.getUserId();
//            String encrypt = aesUtil.encrypt(id);
            vo.setPass(id);
        }
        tourImGroupVo.setMemberList(vos);

        //如果我的id在群成员中，则设置标记
        //true 未加入 false已加入
        boolean b = tourImMemberList.stream().filter(member -> member.getUserId().equals(userId)).findFirst().isEmpty();
        tourImGroupVo.setCodeShowStatus(b?0:1);

        //是否在申请中
        if (b){
            long count = tourImGroupInvitationService.count(new LambdaQueryWrapper<TourImGroupInvitation>()
                    .eq(TourImGroupInvitation::getGroupId, groupId)
                    .eq(TourImGroupInvitation::getInvitee, userId)
                    .eq(TourImGroupInvitation::getStatus, 1));
            if (count==1) tourImGroupVo.setCodeShowStatus(4);
        }

        //群公告设置
        List<TourImMessage> list = tourImMessageService.list(new LambdaQueryWrapper<TourImMessage>()
                .eq(TourImMessage::getGroupId, groupId)
                .eq(TourImMessage::getIsTop, 1));
        if (list!=null &&list.size()==1) {
            String content = list.get(0).getMessageContent();
            MessageDTO jsonObject =JSONUtil.toBean(content, MessageDTO.class);
            MessageDTO dto = new MessageDTO();
            dto.setMessageContent(jsonObject.getMessageContent());

            dto.setCreateTime(DateUtil.format(list.get(0).getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            tourImGroupVo.setGroupNotice(dto);

        }else {
            tourImGroupVo.setGroupNotice("暂无公告");
        }
        return ResponseResult.success(tourImGroupVo);
    }


    /**
     * 群头像文件上传文件上传操作。
     *
     * @param fieldName  上传文件名。
     * @param asImage    是否作为图片上传。如果是图片，今后下载的时候无需权限验证。否则就是附件上传，下载时需要权限验证。
     * @param uploadFile 上传文件对象。
     */
    @OperationLog(type = SysOperationLogType.UPLOAD, saveResponse = false)
    @PostMapping("/upload")
    public void upload(
            @RequestParam String fieldName,
            @RequestParam Boolean asImage,
            @RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
        long size = 0;
        String remark = "";
        if (asImage){
            size=1024*1024*10;
            remark="图片大小不能超过20M";
        }else {
            size=1024*1024*20;
            remark="文件大小不能超过20M";
        }
        if(uploadFile.getSize()>size){
            ResponseResult.output(HttpServletResponse.SC_FORBIDDEN,
                    ResponseResult.error(ErrorCodeEnum.INVALID_UPLOAD_FILE_IOERROR, remark));
            return;
        }
        UploadStoreInfo storeInfo = MyModelUtil.getUploadStoreInfo(TourImGroup.class, fieldName);
        // 根据字段注解中的存储类型，通过工厂方法获取匹配的上传下载实现类，从而解耦。
        BaseUpDownloader upDownloader = upDownloaderFactory.get(storeInfo.getStoreType());
        UploadResponseInfo responseInfo = upDownloader.doUpload(null,
                appConfig.getUploadFileBaseDir(), TourImComplait.class.getSimpleName(), fieldName, asImage, uploadFile);
        if (Boolean.TRUE.equals(responseInfo.getUploadFailed())) {
            ResponseResult.output(HttpServletResponse.SC_FORBIDDEN,
                    ResponseResult.error(ErrorCodeEnum.UPLOAD_FAILED, responseInfo.getErrorMessage()));
            return;
        }
        cacheHelper.putSessionUploadFile(responseInfo.getFilename());
        ResponseResult.output(ResponseResult.success(responseInfo));
    }


    /**
     * 群聊广场 群名字、群类型搜索。
     *
     * @param groupName 过滤对象。
     * @param groupTypeId 排序参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @GetMapping("/list")
    public ResponseResult<MyPageData<TourImGroupVo>> getGroupListByFilter(String groupName,Long groupTypeId,Integer pageNum,Integer pageSize) {

        //用户id
        Long userId = TokenData.takeFromRequest().getUserId();
        List<Long> typeIds = new ArrayList<>();
        //类型不为空查找其子类型ids
        if (groupTypeId != null){
            List<TourImGroupType> groupTypes = tourImGroupTypeService.list(new LambdaQueryWrapper<TourImGroupType>()
                    .eq(TourImGroupType::getParentId, groupTypeId));
            typeIds = groupTypes.stream().map(TourImGroupType::getId).collect(Collectors.toList());

            //没有子类则自己就是子节点，自己作为查询条件
            if (groupTypes.isEmpty()){
                typeIds.add(groupTypeId);
            }
        }


        //构建查询条件
        LambdaQueryWrapper<TourImGroup> queryWrapper = new LambdaQueryWrapper<TourImGroup>()
                .eq(TourImGroup::getNoticeType, NoticeType.NOTICE_GROUP)
                .like(TourImGroup::getGroupName, groupName==null?"":groupName)
                .eq(TourImGroup::getBannedStatus, IsTrue.TRUE)
                .eq(TourImGroup::getIsPublic, IsTrue.TRUE)
                .eq(TourImGroup::getDataState, 1)
                .orderByAsc(TourImGroup::getHotValue);

        // 如果 typeIds 不为 null，则添加 in 条件
        if (typeIds != null && !typeIds.isEmpty()) {
            queryWrapper.in(TourImGroup::getBelongTypeId, typeIds);
        }
        //获取群组列表
        List<TourImGroup> groupList = tourImGroupService.list(queryWrapper);

        if (groupList==null || groupList.isEmpty()) return ResponseResult.success(new MyPageData<>());

        //群组ids
        List<Long> groupIds  = groupList.stream().map(TourImGroup::getId).collect(Collectors.toList());
        List<String> gIds  = groupList.stream().map(o->o.getId().toString()).collect(Collectors.toList());

        //分页
        if (pageNum==null) pageNum=1;
        if (pageSize==null) pageSize=10;
        PageHelper.startPage(pageNum, pageSize);


        //群聊成员
        List<TourImMember> memberList = tourImMemberService.list(new LambdaQueryWrapper<TourImMember>()
                .in(TourImMember::getGroupId, groupIds)
                .select(TourImMember::getGroupId,TourImMember::getUserId)
                .eq(TourImMember::getDataState,1));
        List<TourImMemberVo> tourImMemberVos = MyModelUtil.copyCollectionTo(memberList, TourImMemberVo.class);
        //群成员头像填充
        List<String>  memberIds = tourImMemberVos.stream().map(TourImMemberVo::getUserId).toList();
        //查询用户信息
        List<TourUser> tourUserList = tourUserService.list(new LambdaQueryWrapper<TourUser>()
                .in(TourUser::getUserId, memberIds));
        tourImMemberVos.forEach(member -> {
            //填充头像
            tourUserList.stream().forEach(user -> {
                if (user.getUserId().toString().equals(member.getUserId())&&user.getHeadImageUrl()!=null){
                    member.setHeadImageUrl(user.getHeadImageUrl());
                }
            });
        });

        //群申请
        List<TourImGroupInvitation> invitationList = tourImGroupInvitationService.list(new LambdaQueryWrapper<TourImGroupInvitation>()
                .eq(TourImGroupInvitation::getInvitee, userId)
                .eq(TourImGroupInvitation::getStatus, 1)
                .in(TourImGroupInvitation::getGroupId, groupIds));

        //群组vo
        MyPageData<TourImGroupVo> pageData = MyPageUtil.makeResponseData(groupList, TourImGroupVo.class);
        List<TourImGroupVo> groupVos = pageData.getDataList();

        //群聊成员map key:群聊id value:群聊成员id集合
        Map<Long, List<Long>> memberMap = memberList.stream().collect(Collectors
                .groupingBy(TourImMember::getGroupId, Collectors
                        .mapping(TourImMember::getUserId, Collectors.toList())));

        //群申请map key:群聊id value:群聊申请id集合
        Map<Long, List<Long>> invatationMap = invitationList.stream().collect(Collectors
                .groupingBy(TourImGroupInvitation::getGroupId, Collectors
                        .mapping(TourImGroupInvitation::getInvitee, Collectors.toList())));

        //加群状态填充
        groupVos.forEach(groupVo->{
            //判断是否加群
            tourImMemberVos.forEach(item->{
                if (memberMap.containsKey(Long.parseLong(groupVo.getId()))){
                    List<Long> list = memberMap.get(Long.parseLong(groupVo.getId()));
                    if (list.contains(userId)){
                        groupVo.setCodeShowStatus(IsTrue.TRUE);
                    }else {
                        groupVo.setCodeShowStatus(IsTrue.FALSE);
                    }
                    //填充成员数量
                    if (groupVo.getMemberCount()==null){
                        groupVo.setMemberCount(list.size());
                    }
                }
            });
            //判断是否在申请中
            invitationList.forEach(item->{
                if (invatationMap.containsKey(Long.valueOf(groupVo.getId()))){
                    List<Long> list = invatationMap.get(Long.valueOf(groupVo.getId()));
                    if (list.contains(userId)){
                        groupVo.setCodeShowStatus(4);
                    }
                }
            });

        });
        //查询群类型字典并填入
//        if (ObjectUtil.isNotEmpty(typeIds)){
        List<Long> tourTypeIds = groupList.stream().map(TourImGroup::getBelongTypeId).toList();
            List<TourImGroupType> tourImGroupTypes = tourImGroupTypeService.listByIds(tourTypeIds);
            groupVos.forEach(item->{
                if (item.getBelongTypeId()!=null){
                    Set<TourImGroupType> typeSet = tourImGroupTypes.stream().filter(i -> i.getId().toString().equals(item.getBelongTypeId().toString())).collect(Collectors.toSet());
                    if (!typeSet.isEmpty()) {
                        List<HashMap<String, Object>> collected = typeSet.stream()
                                .map(i -> {
                                    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                                    stringObjectHashMap.put("id", i.getId().toString());
                                    stringObjectHashMap.put("name", i.getTypeName());
                                    return stringObjectHashMap;
                                }).toList();
                        HashMap<String, Object> stringObjectHashMap = collected.get(0);
                        item.setBelongTypeIdDictMap(stringObjectHashMap);
                    }
                }
            });
            pageData.setTotalCount((long) groupList.size());


        //群ID->用户集合
        Map<String, Set<TourUser>> userByGroupId = tourMemberService.getUserByGroupId(gIds);

        for (TourImGroupVo group : groupVos) {
            Set<TourUser> tourUsers = userByGroupId.get(group.getId().toString());
            if(tourUsers!=null){
                List<TourUser> list = tourUsers.stream().toList();
                if(list.size()>10){
                    list = list.subList(0, 10);
                }
                group.setUserList(list);
            }
        }
        return ResponseResult.success(pageData);
    }

    /**
     * 是否加入了该群
     *
     * @param groupId
     * @return boolean
     */
    @GetMapping("/isJoinGroup")
    public ResponseResult<TourImGroupVo> isJoinGroup(Long groupId) {
        //用户id
        Long userId = TokenData.takeFromRequest().getUserId();
        //过滤条件
        TourImGroup tourImGroup = tourImGroupService.getById(groupId);
        if (tourImGroup==null) return null;
        TourImGroupVo tourImGroupVo = MyModelUtil.copyTo(tourImGroup, TourImGroupVo.class);
        //判断是否加入群聊
        TourImMember member = tourImMemberService.getOne(new LambdaQueryWrapper<TourImMember>()
                .eq(TourImMember::getGroupId, groupId)
                .eq(TourImMember::getUserId, userId));
        if (member!=null){
            tourImGroupVo.setCodeShowStatus(IsTrue.TRUE);
        }else {
            tourImGroupVo.setCodeShowStatus(IsTrue.FALSE);
        }

//        //群类型父级id填充
//        Map<String, Object> belongTypeIdDictMap = tourImGroupVo.getBelongTypeIdDictMap();
//        Set<Map.Entry<String, Object>> entries = belongTypeIdDictMap.entrySet();
//        for (Map.Entry<String, Object> entry : entries) {
//            if (entry.getValue() instanceof Long){
//                belongTypeIdDictMap.put(entry.getKey(),entry.getValue().toString());
//            }
//        }

        return ResponseResult.success(tourImGroupVo);
    }

    /**
     * 于该用户的关注状态
     *
     * @param userId
     * @return boolean
     */
    @GetMapping("/isFollow")
    public ResponseResult<Long> isFollow(Long userId) {
        Long status = this.attentionStatus(userId);
        return ResponseResult.success(status);
    }

    public Long attentionStatus(Long userId) {
        //用户id
        Long myId = TokenData.takeFromRequest().getUserId();
        // 我的粉丝列表  attentionId = currentUserId
        List<TourFans> myFansList = tourFansService.list(
                new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, myId).eq(TourFans::getDeleteFlag, 1)
        );
        //我的关注列表  createUserId = currentUserId
        List<TourFans> myFocusList = tourFansService.list(
                new LambdaQueryWrapper<TourFans>().eq(TourFans::getCreateUserId, myId).eq(TourFans::getDeleteFlag, 1)
        );
        //关注列表用户ids
        Set<Long> myFocusIds = myFocusList.stream()
                .map(TourFans::getAttentionId)
                .collect(Collectors.toSet());
        //粉丝列表用户ids
        Set<Long> myFansIds = myFansList.stream()
                .map(TourFans::getCreateUserId)
                .collect(Collectors.toSet());

        // 关注状态填充
        Long status = null;
        if (userId.toString().equals(myId.toString())){
            status = MyAttentionStatus.MYSELF;// 自己
        }else if(myFocusIds.contains(userId) && myFansIds.contains(userId)) {
            status =MyAttentionStatus.FOCUS_EACH; // 互关
        } else if (myFansIds.contains(userId)&& !myFocusIds.contains(userId)) {
            status =MyAttentionStatus.BE_FOCUSED; // 他关注了我
        }else if (myFocusIds.contains(userId)) {
            status =MyAttentionStatus.FOCUSED;// 已关注
        } else {
            status =MyAttentionStatus.UN_FOCUS;  // 未关注
        }
        return status;
    }

    /**
     *  群申请审核
     * @params  申请消息ID 2 同意 3不同意
     * @return {@link ResponseResult }<{@link Void }>
     */
    @PostMapping("/applyIsPass")
    public ResponseResult<Boolean> applyIsPass(@RequestBody ApplyIsPassDto params) {
        Long groupId = Long.valueOf(params.getGroupId());

        List<String> ids = params.getIds();
        if (ObjectUtil.isEmpty(ids)) return ResponseResult.error("500","数据异常");

        Long userId = TokenData.takeFromRequest().getUserId();
        //是否是管理员
        boolean admin = tourGroupService.isAdmin(groupId, userId);

        if(!admin){
            return ResponseResult.error("500","您不是群主或管理员，无法操作");
        }
        TourImGroup group = tourGroupService.getById(params.getGroupId());
        //群状态是否可加入
        if(group.getBannedStatus().equals(0)){
            return ResponseResult.error("500","群聊状态异常");
        }

        List<TourImGroupInvitation> list = tourImGroupInvitationService.lambdaQuery().in(TourImGroupInvitation::getId,params.getIds()).
                eq(TourImGroupInvitation::getStatus,1).list();
        if(ObjectUtil.isEmpty(list)) return ResponseResult.error("500","数据异常");
        boolean b = tourGroupService.applyIsPass(list,params.getIsPass(), params.getGroupId());

        return ResponseResult.success(b);
    }

    /**
     *  群类型一级类型
     * @return {@link ResponseResult }<{@link List }<{@link TourImGroupTypeVo }>>
     */
    @GetMapping("/getGroupTypeFirst")
    public ResponseResult<List<TourImGroupTypeVo>> getGroupTypeFirst() {
        TourImGroupType filter = new TourImGroupType();
        filter.setParentId(0L);
        List<TourImGroupType> list = tourImGroupTypeService.getTourImGroupTypeList(filter, null);
        List<TourImGroupTypeVo> tourImGroupTypeVos = MyModelUtil.copyCollectionTo(list, TourImGroupTypeVo.class);
        return ResponseResult.success(tourImGroupTypeVos);
    }

    /**
     * 查询群审核列表。
     */
    @GetMapping("/getApplicationsList")
    public ResponseResult<List<TourGroupInvitationVo>> getApplicationsList(String groupId) {
        LambdaQueryWrapper<TourImGroupInvitation> query = Wrappers.<TourImGroupInvitation>lambdaQuery().eq(TourImGroupInvitation::getGroupId, groupId)
                .eq(TourImGroupInvitation::getStatus, 1).orderByAsc(TourImGroupInvitation::getCreateTime);
        //申请集合
        List<TourImGroupInvitation> list = tourImGroupInvitationService.list(query);

        if(list.isEmpty()) return ResponseResult.success(new ArrayList<TourGroupInvitationVo>());
        //申请用户
        Set<Long> userId = list.stream().map(TourImGroupInvitation::getInvitee).collect(Collectors.toSet());
        HashMap<String, TourUser> map = new HashMap<>();

        List<TourUser> tourUsers = tourUserService.getBaseMapper().selectBatchIds(userId);
        for (TourUser tourUser : tourUsers) {
            map.put(tourUser.getUserId().toString(), tourUser);
        }

        ArrayList<TourGroupInvitationVo> vo = new ArrayList<>();
        //封装为返回结果集
        for (TourImGroupInvitation tourImGroupInvitation : list) {
            TourGroupInvitationVo tourGroupInvitationVo = new TourGroupInvitationVo();
            tourGroupInvitationVo.setId(tourImGroupInvitation.getId().toString());
            tourGroupInvitationVo.setInvitee(tourImGroupInvitation.getInvitee().toString());
            tourGroupInvitationVo.setTourUser(map.get(tourImGroupInvitation.getInvitee().toString()));
            tourGroupInvitationVo.setCreateTime(tourImGroupInvitation.getCreateTime());
            tourGroupInvitationVo.setStatus(tourImGroupInvitation.getStatus());
            vo.add(tourGroupInvitationVo);
        }
        return ResponseResult.success(vo);
    }

    /**
     * 创建单向Member
     */
    @PostMapping("/createMember")
    @Transactional
    public ResponseResult<String> createMember(@RequestBody CreateMemberDto params) {
        String groupId = tourGroupService.createMember(params);
        return ResponseResult.success(groupId);
    }

    /**
     *  查询用户为群主的群聊
     */
    @GetMapping("/getUserGroup")
    public ResponseResult<MyPageData<UserGroupVo>> getUserGroup(String userId,Integer pageNum,Integer pageSize) {
        String myId=TokenData.takeFromRequest().getUserId().toString();
        if(userId==null){
            userId=myId;
        }
        PageMethod.startPage(pageNum==null? 1:pageNum, pageSize==null? 10:pageSize);
        List<TourImGroup> list = tourGroupService.lambdaQuery().eq(TourImGroup::getLeaderId, userId)
                .eq(TourImGroup::getNoticeType, 2)
                .eq(TourImGroup::getIsPublic,1)
                .eq(TourImGroup::getDataState, 1).list();
        long count=0;
        if(!ObjectUtil.isEmpty(list)){
            count = ((Page<TourImGroup>) list).getTotal();
        }
        if(count==0){
            return ResponseResult.success(MyPageUtil.makeResponseData(new ArrayList<>(),count));
        }
        List<UserGroupVo> userGroupVo = BeanUtil.copyToList(list, UserGroupVo.class);
        //群聊ids
        Set<String> groupIds = userGroupVo.stream().map(UserGroupVo::getId).collect(Collectors.toSet());
        List<TourImMember> list1 = tourMemberService.lambdaQuery().in(TourImMember::getGroupId, groupIds)
                .eq(TourImMember::getDataState, 1).list();
        //用户Ids
        Set<Long> collect1 = list1.stream().map(TourImMember::getUserId).collect(Collectors.toSet());
        List<TourUser> inList = tourUserService.getInList(collect1);

        LambdaQueryWrapper<TourImGroupInvitation> query = Wrappers.<TourImGroupInvitation>lambdaQuery().in(TourImGroupInvitation::getGroupId, groupIds)
                .eq(TourImGroupInvitation::getStatus, 1);
        //申请集合
        List<TourImGroupInvitation> listInvent = tourImGroupInvitationService.list(query);

        for (UserGroupVo groupVo : userGroupVo) {
            //填充人数
            //当前群聊中的用户ids
            Set<String> collect = list1.stream().filter(o -> o.getGroupId().toString().equals(groupVo.getId())).map(o->o.getUserId().toString()).collect(Collectors.toSet());
            groupVo.setCount(collect.size());
            //填充头像
            List<String> collect2 = inList.stream().filter(o -> collect.contains(o.getUserId().toString())).map(o -> o.getHeadImageUrl()).collect(Collectors.toList());
            groupVo.setMemberHeadImg(collect2);

            List<TourImGroupInvitation> collect3 = listInvent.stream().filter(o -> o.getGroupId().toString().equals(groupVo.getId()) && o.getInvitee().toString().equals(myId)).collect(Collectors.toList());
            //填充状态
            if(collect.contains(myId)){
                groupVo.setStatus("1");
            }else if(!collect.contains(myId)&& !collect3.isEmpty()){
                groupVo.setStatus("2");
            }else {
                groupVo.setStatus("0");
            }
        }
        if(myId.equals(userId)){
            //群聊是自己的
            userGroupVo.forEach(o->o.setStatus("1"));
        }
        return ResponseResult.success(MyPageUtil.makeResponseData(userGroupVo,count));
    }

    @PostMapping("/getUserByIds")
    public ResponseResult<List<UserNameVo>> getUserByIds(@RequestBody Set<String> ids){
        if(ids.isEmpty()){
            return ResponseResult.success(new ArrayList<>());
        }
        Set<Long> collect = ids.stream().map(Long::valueOf).collect(Collectors.toSet());
        List<TourUser> inList = tourUserService.getInList(collect);
        List<UserNameVo> userNameVos = BeanUtil.copyToList(inList, UserNameVo.class);
        return ResponseResult.success(userNameVos);
    }
}
