package com.gic.haoban.manage.service.context.chat;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.BusinessException;
import com.gic.api.base.commons.Constant;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.dto.StoreGroupDTO;
import com.gic.enterprise.api.dto.StoreSearchDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.common.utils.DistanceUtil;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatActivityDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatActivityJoinDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.ChatHmSearchQDTO;
import com.gic.haoban.manage.api.enums.chat.ChatActivityJoinEnum;
import com.gic.haoban.manage.api.enums.chat.ChatActivityJoinRuleEnum;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivityHmQDTO;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatHmMapper;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatHmRelationMapper;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatMapper;
import com.gic.haoban.manage.service.dao.mapper.chat.GroupChatUserMapper;
import com.gic.haoban.manage.service.entity.chat.TabGroupChat;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatHm;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatHmRelation;
import com.gic.haoban.manage.service.entity.chat.TabGroupChatUser;
import com.gic.haoban.manage.service.pojo.bo.chat.GroupChatHmBO;
import com.gic.haoban.manage.service.service.ESMemberInfoService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.chat.GroupChatHmService;
import com.gic.member.api.dto.MemberDTO;
import com.gic.member.api.dto.store.MemberStoreResp;
import com.gic.member.api.service.MemberService;
import com.gic.member.api.service.MemberStoreService;
import com.gic.member.tag.api.dto.MemberExistDTO;
import com.gic.member.tag.api.service.MemberTagGroupApiService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * Created by wangzubo on 2024/8/23.
 */
@Component
public class JoinRuleManager {

    private static final Logger logger = LoggerFactory.getLogger(JoinRuleManager.class);

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberStoreService memberStoreService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private GroupChatUserMapper groupChatUserMapper;
    @Autowired
    private GroupChatHmRelationMapper groupChatHmRelationMapper;
    @Autowired
    private GroupChatMapper groupChatMapper;
    @Autowired
    private GroupChatHmService groupChatHmService;
    @Autowired
    private StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private ESMemberInfoService esMemberInfoService;
    @Autowired
    private MemberTagGroupApiService memberTagGroupApiService;
    @Autowired
    private GroupChatHmMapper groupChatHmMapper ;

    private final Map<ChatActivityJoinRuleEnum, FunctionWithException<GroupChatActivityHmQDTO,List<GroupChatHmBO>>> ruleHandlers = new HashMap<>();

    public JoinRuleManager() {
        ruleHandlers.put(ChatActivityJoinRuleEnum.INVITER_CHAT, this::handleInviterChat);
        ruleHandlers.put(ChatActivityJoinRuleEnum.MAIN_STORE, this::handleMainStore);
        ruleHandlers.put(ChatActivityJoinRuleEnum.OTHER_STORE, this::handleOtherStore);
        ruleHandlers.put(ChatActivityJoinRuleEnum.LBS, this::handleLbs);
    }

    @FunctionalInterface
    public interface FunctionWithException<T, R> {
        R apply(T t) throws BusinessException;
    }

    /**
     * 获取入群群活码
     * @param activityHmQDTO qdto
     * @return
     * @throws BusinessException
     */
    public List<GroupChatHmBO> listGroupHm(GroupChatActivityHmQDTO activityHmQDTO) throws BusinessException{
        GroupChatActivityDTO chatActivity = activityHmQDTO.getChatActivity();
        String inviteeMemberId = activityHmQDTO.getInviteeMemberId();
        if (chatActivity == null) {
            return new ArrayList<>();
        }
        logger.info("入群规则:{}", JSON.toJSONString(activityHmQDTO));
        Integer joinType = chatActivity.getJoinType();
        if (Objects.equals(ChatActivityJoinEnum.RULE.value, joinType)) {
            String joinRule = chatActivity.getJoinRule();
            List<JSONObject> joinRuleList = JSONArray.parseArray(joinRule, JSONObject.class);
            for (JSONObject jsonObject : joinRuleList) {
                //是否开启
                Integer openFlag = jsonObject.getInteger("openFlag");
                Integer val = jsonObject.getInteger("val");
                if (!Objects.equals(openFlag, Constant.FLAG_TRUE)) {
                    continue;
                }
                ChatActivityJoinRuleEnum ruleEnum = ChatActivityJoinRuleEnum.getByValue(val);
                List<GroupChatHmBO> hmBOList = applyJoinRule(ruleEnum, activityHmQDTO);
                if (CollectionUtils.isNotEmpty(hmBOList)) {
                    return hmBOList;
                }
            }
        }else {
            //受邀人没有memberId则取邀请人所在群的群活码
            if (StringUtils.isBlank(inviteeMemberId)) {
                logger.info("受邀人没有memberId则取邀请人所在群的群活码");
                List<GroupChatHmBO> hmBOList = handleInviterChat(activityHmQDTO);
                if (CollectionUtils.isNotEmpty(hmBOList)) {
                    return hmBOList;
                }
            }else {
                List<GroupChatActivityJoinDTO> joinList = activityHmQDTO.getChatActivity().getJoinList();
                for (GroupChatActivityJoinDTO joinDTO : joinList) {
                    boolean checked = checkActivityMember(chatActivity, joinDTO, inviteeMemberId);
                    if (checked) {
                        logger.info("命中会员条件joinId:{},index:{}", joinDTO.getChatActivityJoinId(), joinDTO.getIndex());
                        GroupChatHmBO chatHm = groupChatHmService.getById(joinDTO.getChatHmId());
                        if (chatHm != null && Objects.equals(chatHm.getStatusFlag(), 1)) {
                            return Lists.newArrayList(chatHm);
                        }
                    }
                }
            }
        }
        GroupChatHmBO chatHm = groupChatHmService.getById(chatActivity.getJoinChatHmId());
        if (chatHm != null && Objects.equals(chatHm.getStatusFlag(), 1)) {
            return Lists.newArrayList(chatHm);
        }
        return null;
    }

    /**
     * 校验会员是否满足校验条件
     * @param chatActivity 社群活动
     * @param joinDTO   入群规则
     * @param memberId  受邀人id
     * @return
     */
    private boolean checkActivityMember(GroupChatActivityDTO chatActivity,GroupChatActivityJoinDTO joinDTO,String memberId) {
        String enterpriseId = chatActivity.getEnterpriseId();
        Integer memberType = joinDTO.getMemberType();
        String filterJson = joinDTO.getFilterJson();
        String creatorId = chatActivity.getCreatorId();
        boolean exist = true;
        //校验是否有权限
        if (memberType == 0) {
            String searchParams = esMemberInfoService.getMemberSearchParamOld(enterpriseId, memberType, filterJson,creatorId,false);
            JSONObject searchJson = JSON.parseObject(searchParams);
            exist = esMemberInfoService.matchMember(enterpriseId, searchJson, memberId,creatorId);
        } else if (memberType == 1) {
            MemberExistDTO dto = new MemberExistDTO();
            dto.setEnterpriseId(enterpriseId);
            String[] tagGroupIdArr = filterJson.split(",");
            List<String> list = Arrays.asList(tagGroupIdArr);
            dto.setMemberTagGroupIds(list);
            dto.setUseId(creatorId);
            dto.setMemberId(memberId);
            exist =  memberTagGroupApiService.memberIsExistGroup(dto);
        }
        logger.info("activity:{},memberId:{},joinId:{},有无权限:{}",chatActivity.getChatActivityId(),memberId,joinDTO.getChatActivityJoinId(),exist);
        return exist;
    }

    public List<GroupChatHmBO> applyJoinRule(ChatActivityJoinRuleEnum ruleEnum, GroupChatActivityHmQDTO activityHmQDTO) throws BusinessException{
        FunctionWithException<GroupChatActivityHmQDTO, List<GroupChatHmBO>> handler = ruleHandlers.get(ruleEnum);
        if (handler != null) {
            List<GroupChatHmBO> apply = handler.apply(activityHmQDTO);
            if (apply == null) {
                apply = new ArrayList<>();
            }
            logger.info("规则:{},获取活码数:{}", ruleEnum.desc, apply.size());
            return apply;
        }
        return null;
    }

    /**
     * 获取邀请人所在群群活码
     * @param activityHmQDTO qdto
     * @return
     */
    private List<GroupChatHmBO> handleInviterChat(GroupChatActivityHmQDTO activityHmQDTO) {
        String wxEnterpriseId = activityHmQDTO.getChatActivity().getWxEnterpriseId();
        String enterpriseId = activityHmQDTO.getEnterpriseId();
        String inviterMemberId = activityHmQDTO.getInviterMemberId();
        MemberDTO member = memberService.getMember(inviterMemberId);
        if (member == null) {
            return new ArrayList<>();
        }
        //根据邀请人unionId获取所在群
        String thirdUnionid = member.getThirdUnionid();
        List<TabGroupChatUser> chartUserList = groupChatUserMapper.getByUnionId(enterpriseId, thirdUnionid);
        if (CollectionUtils.isEmpty(chartUserList)) {
            return new ArrayList<>();
        }
        //根据群id获取所有关联的群活码
        List<Long> groupChatIdList = chartUserList.stream().map(TabGroupChatUser::getGroupChatId).collect(Collectors.toList());
        List<TabGroupChatHmRelation> chatHmList = groupChatHmRelationMapper.listChatHmByGroupChatIds(groupChatIdList);
        if (CollectionUtils.isEmpty(chatHmList)) {
            return new ArrayList<>();
        }
        ChatHmSearchQDTO hmSearchQDTO = new ChatHmSearchQDTO();
        hmSearchQDTO.setEnterpriseId(enterpriseId);
        hmSearchQDTO.setWxEnterpriseId(wxEnterpriseId);
        List<Long> chatHmIdList = chatHmList.stream().map(TabGroupChatHmRelation::getChatHmId).collect(Collectors.toList());
        hmSearchQDTO.setChatHmIdList(chatHmIdList);
        hmSearchQDTO.setStatus(1);
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(100);
        Page<GroupChatHmBO> listPage = groupChatHmService.listPage(hmSearchQDTO, basePageInfo);
        return listPage.getResult();
    }

    /**
     * 获取会员主门店群活码
     * @param activityHmQDTO qdto
     * @return
     */
    public List<GroupChatHmBO> handleMainStore(GroupChatActivityHmQDTO activityHmQDTO) {
        String enterpriseId = activityHmQDTO.getEnterpriseId();
        String wxEnterpriseId = activityHmQDTO.getChatActivity().getWxEnterpriseId();
        MemberStoreResp memberStoreRelation = memberStoreService.getMemberStoreRelation(enterpriseId, activityHmQDTO.getInviteeMemberId());
        if (memberStoreRelation == null) {
            return new ArrayList<>();
        }
        String mainStoreId = memberStoreRelation.getMainStoreId();
        if (StringUtils.isBlank(mainStoreId)) {
            return new ArrayList<>();
        }
        return getByStoreIdList(enterpriseId,wxEnterpriseId, Lists.newArrayList(mainStoreId));
    }

    /**
     * 获取会员协管门店群活码
     * @param activityHmQDTO qdto
     * @return
     */
    public List<GroupChatHmBO> handleOtherStore(GroupChatActivityHmQDTO activityHmQDTO) {
        String enterpriseId = activityHmQDTO.getEnterpriseId();
        String wxEnterpriseId = activityHmQDTO.getChatActivity().getWxEnterpriseId();
        MemberStoreResp memberStoreRelation = memberStoreService.getMemberStoreRelation(enterpriseId, activityHmQDTO.getInviteeMemberId());
        if (memberStoreRelation == null) {
            return new ArrayList<>();
        }
        List<String> assistantStoreIds = memberStoreRelation.getAssistantStoreIds();
        if (CollectionUtils.isEmpty(assistantStoreIds)) {
            return new ArrayList<>();
        }
        return getByStoreIdList(enterpriseId,wxEnterpriseId, assistantStoreIds);
    }

    /**
     * 获取会员最近定位门店群活码
     * @param activityHmQDTO qdto
     * @return
     * @throws BusinessException
     */
    public List<GroupChatHmBO> handleLbs(GroupChatActivityHmQDTO activityHmQDTO) throws BusinessException {
        String enterpriseId = activityHmQDTO.getEnterpriseId();
        String wxEnterpriseId = activityHmQDTO.getChatActivity().getWxEnterpriseId();
        boolean skipArea = activityHmQDTO.isSkipArea();
        if (skipArea) {
            logger.info("跳过LBS");
            return new ArrayList<>();
        }
        String districtCode = activityHmQDTO.getDistrictCode();
        if (StringUtils.isBlank(districtCode)) {
            throw new BusinessException("777", "未获取到经纬度");
        }
        // 获取省市对应的门店
        StoreSearchDTO storeSearchDTO = new StoreSearchDTO();
        storeSearchDTO.setEnterpriseId(enterpriseId);
        storeSearchDTO.setProvinceCityIdList(Lists.newArrayList(districtCode));
        storeSearchDTO.setStatus("2");
        List<String> storeIds = this.storeService.listStoreIds(storeSearchDTO);

        if (CollectionUtils.isEmpty(storeIds)) {
            return new ArrayList<>();
        }
        //获取storeId对应活码
        Map<String, List<GroupChatHmBO>> storeToHmMap = getStoreIdToGroupChatHmBOMap(enterpriseId, wxEnterpriseId, storeIds);
        if (MapUtil.isEmpty(storeToHmMap)) {
            return new ArrayList<>();
        }
        Set<String> storeIdSet = storeToHmMap.keySet();
        //获取最近的一个门店
        List<StoreDTO> stores = storeService.getStores(storeIdSet.toArray(new String[0]));
        if (CollectionUtils.isEmpty(stores)) {
            return new ArrayList<>();
        }
        String storeId = stores.get(0).getStoreId();
        List<StoreDTO> sortStores = stores.stream().filter(x -> StringUtils.isNotBlank(x.getLatitude()) && StringUtils.isNotBlank(x.getLongitude()))
                .sorted(Comparator.comparing(x ->
                        DistanceUtil.getDistance(Double.parseDouble(x.getLatitude()),
                                Double.parseDouble(x.getLongitude()),
                                Double.parseDouble(activityHmQDTO.getLatitude()),
                                Double.parseDouble(activityHmQDTO.getLongitude())))).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sortStores)) {
            storeId = sortStores.get(0).getStoreId();
        }
        logger.info("最近的门店id:{}",storeId);
        return storeToHmMap.get(storeId);
    }

    /**
     * 根据门店id获取群活码
     * @param enterpriseId  企业id
     * @param wxEnterpriseId    好办企业id
     * @param storeIdList   门店id列表
     * @return
     */
    private List<GroupChatHmBO> getByStoreIdList(String enterpriseId,String wxEnterpriseId,List<String> storeIdList) {
        logger.info("门店id列表:{}",JSON.toJSONString(storeIdList));
        List<TabGroupChatHm> hmList = this.groupChatHmMapper.listByStoreIdList(storeIdList) ;
        if(CollectionUtils.isNotEmpty(hmList)) {
            return EntityUtil.changeEntityListByJSON(GroupChatHmBO.class,hmList) ;
        }
        // 获取导购列表
        Page<ClerkDTO> page = clerkService.pageClerkByNameOrCode(enterpriseId,"",storeIdList,1,1000);
        List<ClerkDTO> clerkList = page.getResult();
        if (CollectionUtils.isEmpty(clerkList)) {
            logger.info("导购不存在");
            return new ArrayList<>();
        }
        // 获取导购ID列表
        List<String> clerkIdList = clerkList.stream().map(ClerkDTO::getClerkId).collect(Collectors.toList());
        // 通过导购id查询staffId
        List<StaffClerkRelationDTO> relationDTOList = staffClerkRelationService.listByClerkIds(clerkIdList);
        if (CollectionUtils.isEmpty(relationDTOList)) {
            logger.info("导购staff关联不存在");
            return new ArrayList<>();
        }
        List<String> staffIdList = relationDTOList.stream().map(StaffClerkRelationDTO::getStaffId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(staffIdList)) {
            return new ArrayList<>();
        }
        // 过滤绑定多个门店的成员
        Map<String,Boolean> map = this.staffClerkRelationService.staffManyStore(staffIdList) ;
        staffIdList = staffIdList.stream().filter(item -> null == map.get(item) || !map.get(item)).collect(Collectors.toList()) ;
        logger.info("过滤有多个门店的成员后={}",staffIdList);
        if (CollectionUtils.isEmpty(staffIdList)) {
            return new ArrayList<>();
        }
        // 通过staffId查询群
        List<TabGroupChat> groupChatList = groupChatMapper.listByStaffIds(enterpriseId, staffIdList);
        if (CollectionUtils.isEmpty(groupChatList)) {
            logger.info("导购关联社群关联不存在");
            return new ArrayList<>();
        }
        List<Long> groupChatIdList = groupChatList.stream().map(TabGroupChat::getGroupChatId).collect(Collectors.toList());

        List<TabGroupChatHmRelation> chatHmList = groupChatHmRelationMapper.listChatHmByGroupChatIds(groupChatIdList);
        if (CollectionUtils.isEmpty(chatHmList)) {
            return new ArrayList<>();
        }
        List<Long> chatHmIdList = chatHmList.stream().map(TabGroupChatHmRelation::getChatHmId).collect(Collectors.toList());
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(1000);
        ChatHmSearchQDTO hmSearchQDTO = new ChatHmSearchQDTO();
        hmSearchQDTO.setEnterpriseId(enterpriseId);
        hmSearchQDTO.setWxEnterpriseId(wxEnterpriseId);
        hmSearchQDTO.setChatHmIdList(chatHmIdList);
        hmSearchQDTO.setStatus(1);
        Page<GroupChatHmBO> listPage = groupChatHmService.listPage(hmSearchQDTO, basePageInfo);
        logger.info("群活码列表:{}",JSON.toJSONString(listPage));
        List<GroupChatHmBO> retList = listPage.getResult();
        if(CollectionUtils.isNotEmpty(retList)) {
            Map<Long,Boolean> hmMap =  this.groupChatHmService.hasManyOwnerStore(wxEnterpriseId,retList.stream().map(o->o.getChatHmId()).collect(Collectors.toList())) ;
            retList = retList.stream().filter(item -> null == hmMap.get(item.getChatHmId()) || !hmMap.get(item.getChatHmId())).collect(Collectors.toList()) ;
        }
        return retList;
    }


    /**
     * 获取门店id对应群活码映射
     * @param enterpriseId  企业id
     * @param wxEnterpriseId    好办企业id
     * @param storeIdList   门店id列表
     * @return
     */
    public Map<String, List<GroupChatHmBO>>  getStoreIdToGroupChatHmBOMap(String enterpriseId,String wxEnterpriseId,List<String> storeIdList) {
        logger.info("门店id列表:{}",JSON.toJSONString(storeIdList));
        Page<ClerkDTO> page = clerkService.pageClerkByNameOrCode(enterpriseId,"",storeIdList,1,10000);
        List<ClerkDTO> clerkList = page.getResult();
        if (CollectionUtils.isEmpty(clerkList)) {
            logger.info("导购不存在");
            return new HashMap<>();
        }
        List<String> clerkIdList = clerkList.stream().map(ClerkDTO::getClerkId).collect(Collectors.toList());
        //通过导购id查询staffId
        List<StaffClerkRelationDTO> relationDTOList = staffClerkRelationService.listByClerkIds(clerkIdList);
        if (CollectionUtils.isEmpty(relationDTOList)) {
            logger.info("导购staff关联不存在");
            return new HashMap<>();
        }
        List<String> staffIdList = relationDTOList.stream().map(StaffClerkRelationDTO::getStaffId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(staffIdList)) {
            return new HashMap<>();
        }
        // 过滤绑定多个门店的成员
        Map<String,Boolean> map = this.staffClerkRelationService.staffManyStore(staffIdList) ;
        staffIdList = staffIdList.stream().filter(item -> null == map.get(item) || !map.get(item)).collect(Collectors.toList()) ;
        logger.info("过滤有多个门店的成员后={}",staffIdList);
        if (CollectionUtils.isEmpty(staffIdList)) {
            return new HashMap<>();
        }
        Map<String, Set<String>> storeToStaffMap = relationDTOList.stream().collect(Collectors.groupingBy(StaffClerkRelationDTO::getStoreId,
                Collectors.mapping(StaffClerkRelationDTO::getStaffId, Collectors.toSet())));
        //通过staffId查询群
        List<TabGroupChat> groupChatList = groupChatMapper.listByStaffIds(enterpriseId, staffIdList);
        if (CollectionUtils.isEmpty(groupChatList)) {
            logger.info("导购关联社群关联不存在");
            return new HashMap<>();
        }
        List<Long> groupChatIdList = groupChatList.stream().map(TabGroupChat::getGroupChatId).collect(Collectors.toList());

        Map<String, Set<Long>> staffToGroupChatMap = groupChatList.stream().collect(Collectors.groupingBy(TabGroupChat::getStaffId,
                Collectors.mapping(TabGroupChat::getGroupChatId, Collectors.toSet())));
        List<TabGroupChatHmRelation> chatHmList = groupChatHmRelationMapper.listChatHmByGroupChatIds(groupChatIdList);
        if (CollectionUtils.isEmpty(chatHmList)) {
            return new HashMap<>();
        }
        List<Long> chatHmIdList = chatHmList.stream().map(TabGroupChatHmRelation::getChatHmId).collect(Collectors.toList());
        //通过群查询群活码
        Map<Long, Set<Long>> groupChatToHmMap = chatHmList.stream().collect(Collectors.groupingBy(TabGroupChatHmRelation::getGroupChatId,
                Collectors.mapping(TabGroupChatHmRelation::getChatHmId, Collectors.toSet())));
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(1000);
        ChatHmSearchQDTO hmSearchQDTO = new ChatHmSearchQDTO();
        hmSearchQDTO.setEnterpriseId(enterpriseId);
        hmSearchQDTO.setWxEnterpriseId(wxEnterpriseId);
        hmSearchQDTO.setChatHmIdList(chatHmIdList);
        hmSearchQDTO.setStatus(1);
        Page<GroupChatHmBO> listPage = groupChatHmService.listPage(hmSearchQDTO, basePageInfo);
        List<GroupChatHmBO> hmList = listPage.getResult();
        if (CollectionUtils.isEmpty(hmList)) {
            return new HashMap<>();
        }
        Map<Long,Boolean> hmMap =  this.groupChatHmService.hasManyOwnerStore(wxEnterpriseId,hmList.stream().map(o->o.getChatHmId()).collect(Collectors.toList())) ;
        hmList = hmList.stream().filter(item -> null == hmMap.get(item.getChatHmId()) || !hmMap.get(item.getChatHmId())).collect(Collectors.toList()) ;
        Map<Long, GroupChatHmBO> groupHmMap = hmList.stream().collect(Collectors.toMap(GroupChatHmBO::getChatHmId, v -> v, (e, x) -> e));
        if (CollectionUtils.isEmpty(hmList)) {
            return new HashMap<>();
        }
        Map<String, List<GroupChatHmBO>> storeIdToGroupChatHmBOMap = convertMap(storeToStaffMap, staffToGroupChatMap, groupChatToHmMap, groupHmMap);

        return storeIdToGroupChatHmBOMap;
    }

    private static Map<String, List<GroupChatHmBO>> convertMap(Map<String, Set<String>> storeToStaffMap, Map<String, Set<Long>> staffToGroupChatMap, Map<Long, Set<Long>> groupChatToHmMap, Map<Long, GroupChatHmBO> groupHmMap) {
        // 1. 初始化结果Map，存储每个storeId对应的GroupChatHmBO列表
        Map<String, List<GroupChatHmBO>> storeIdToGroupChatHmBOMap = new HashMap<>();

        // 2. 遍历每个storeId
        for (String storeId : storeToStaffMap.keySet()) {
            Set<String> staffIds = storeToStaffMap.get(storeId);

            // 3. 获取该storeId对应的所有chatHmIds
            Set<Long> chatHmIds = new HashSet<>();
            for (String staffId : staffIds) {
                Set<Long> groupChatIds = staffToGroupChatMap.get(staffId);
                if (groupChatIds != null) {
                    for (Long groupChatId : groupChatIds) {
                        Set<Long> hmIds = groupChatToHmMap.get(groupChatId);
                        if (hmIds != null) {
                            chatHmIds.addAll(hmIds);
                        }
                    }
                }
            }

            // 4. 获取对应的GroupChatHmBO
            List<GroupChatHmBO> groupChatHmBOList = new ArrayList<>();
            for (Long chatHmId : chatHmIds) {
                GroupChatHmBO groupChatHmBO = groupHmMap.get(chatHmId);
                if (groupChatHmBO != null) {
                    groupChatHmBOList.add(groupChatHmBO);
                }
            }

            // 5. 将结果存入storeIdToGroupChatHmBOMap
            if (!groupChatHmBOList.isEmpty()) {
                storeIdToGroupChatHmBOMap.put(storeId, groupChatHmBOList);
            }
        }
        return storeIdToGroupChatHmBOMap;
    }


}
