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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.annotation.MyRequestBody;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.*;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.core.validator.UpdateGroup;
import com.tourism.common.huaweicloud.obs.util.MergeAvatarsFlexUtils;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.app.website.dto.*;
import com.tourism.webadmin.app.website.model.TourShortImGroup;
import com.tourism.webadmin.app.website.model.TourShortUser;
import com.tourism.webadmin.app.website.service.TourTravelNotesPublishService;
import com.tourism.webadmin.app.website.vo.*;
import com.tourism.webadmin.back.dto.TourTravelNotesMentionUserDto;
import com.tourism.webadmin.back.dto.TourismTravelNotesContentWriteDto;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.model.constant.AuditState;
import com.tourism.webadmin.back.model.constant.UnmountState;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.vo.TourTravelNotesMentionUserVo;
import com.tourism.webadmin.back.vo.TourTravelNotesTopicVo;
import com.tourism.webadmin.back.vo.TourismProjectTravelNotesWriteVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "门户网站发布游记接口")
@Slf4j
@RestController
@RequestMapping("/website/tourism/publishTravelNotes")
public class WebSiteTourismTravelNotesPublishController {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TourismProjectTravelNotesWriteService tourismProjectTravelNotesWriteService;
    @Autowired
    private TourTourismProjectTravelNotesService tourTourismProjectTravelNotesService;
    @Autowired
    private TourUserService tourUserService;
    @Autowired
    private DirectoryInfoService directoryInfoService;
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourFansService tourFansService;
    @Autowired
    private TourTravelNotesTopicService tourTravelNotesTopicService;
    @Autowired
    private TourImGroupService tourImGroupService;
    @Autowired
    private TourImMemberService tourImMemberService;
    @Autowired
    private MergeAvatarsFlexUtils mergeAvatarsFlexUtils;
    @Autowired
    private TourTravelNotesPublishService tourTravelNotesPublishService;
    @Autowired
    private TourTravelNotesImgService tourTravelNotesImgService;
    @Autowired
    private TourTravelNotesTopicRelationService tourTravelNotesTopicRelationService;
    @Autowired
    private TourTravelNotesMentionUserService tourTravelNotesMentionUserService;

    /**
     * 获取草稿id
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getDraftId")
    public ResponseResult<String> getDraftId() {
        return ResponseResult.success(String.valueOf(idGenerator.nextLongId()));
    }

    /**
     * 存为草稿
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/saveDraft")
    public ResponseResult<Void> saveDraft(@RequestBody TourismProjectTravelNotesWriteToWebDto tourismProjectTravelNotesWriteDto) {

        Long userId = TokenData.takeFromRequest().getUserId();
        //先校验提及的用户id是否符合互关的状态
        if(CollectionUtils.isNotEmpty(tourismProjectTravelNotesWriteDto.getMentions())) {
            List<TourTravelNotesMentionUserDto> mentions = tourismProjectTravelNotesWriteDto.getMentions();
            List<TourTravelNotesMentionUserDto> mentionsUserIdList = mentions.stream().filter(item -> item.getUserId() != null).collect(Collectors.toList());
            List<TourShortUser> fouceEachFriendsByName = tourFansService.getFouceEachFriendsByName(userId, "");
            List<TourShortUser> fouceEachFriedsUserIdList = fouceEachFriendsByName.stream().filter(i -> i.getUserId() != null).collect(Collectors.toList());

            Set<Long> collect = mentionsUserIdList.stream().map(TourTravelNotesMentionUserDto::getUserId).collect(Collectors.toSet());
            Set<Long> collect1 = fouceEachFriedsUserIdList.stream().map(TourShortUser::getUserId).collect(Collectors.toSet());
            if (!(collect1).containsAll(collect)) {
                return ResponseResult.error(ErrorCodeEnum.MENTION_USER_ERROR, "提及的用户与本人不符合互关的状态");
            }
        }

        //校验dto中的群聊是否为本人参与的群聊
        if(tourismProjectTravelNotesWriteDto.getTourImGroupId() != null) {
            List<TourShortImGroup> takePartImGroupListByName = tourImGroupService.getTakePartImGroupListByName(userId, "");
            List<Long> takePartImGroupIdList = takePartImGroupListByName.stream().mapToLong(TourShortImGroup::getId).boxed().collect(Collectors.toList());
            if (!takePartImGroupIdList.contains(tourismProjectTravelNotesWriteDto.getTourImGroupId())) {
                return ResponseResult.error(ErrorCodeEnum.MENTION_GROUP_ERROR, "本人未参与到关联的群聊中");
            }
        }
        
        tourTravelNotesPublishService.saveDraft(tourismProjectTravelNotesWriteDto);
        return ResponseResult.success();
    }

    /**
     * 获取数据列表
     * param type--->类型(0,草稿;1,待审核;2,审核未通过;3,审核通过
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getDraftList")
    public ResponseResult<MyPageData<TourismProjectTravelNotesWriteCovertVo>> getDraftList(@Validated TourismProjectTravelNotesWriteDetailPageDto pageDto) {
        if (pageDto.getType() == null) {
            return ResponseResult.success(null);
        }

        List<TourismProjectTravelNotesWrite> tourismProjectTravelNotesWriteList = tourTravelNotesPublishService.getDraftList(pageDto);

        MyPageData<TourismProjectTravelNotesWriteCovertVo> tourismProjectTravelNotesWriteVoMyPageData = MyPageUtil.makeResponseData(tourismProjectTravelNotesWriteList, TourismProjectTravelNotesWriteCovertVo.class);
        List<TourismProjectTravelNotesWriteCovertVo> dataList = tourismProjectTravelNotesWriteVoMyPageData.getDataList();
        if(CollectionUtils.isNotEmpty(dataList)){
            dataList.stream().forEach(item->{
                item.setTourismUrlsAfterConvert(UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getTourismUrl()));
            });
        }
        return ResponseResult.success(tourismProjectTravelNotesWriteVoMyPageData);
    }

    /**
     * 根据草稿id，获取草稿详情
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getDraftDetail")
    public ResponseResult<TourismProjectTravelNotesWriteVo> getDraftDetail(@RequestParam Long writeId) {

        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = tourismProjectTravelNotesWriteService.getByIdWithRelation(writeId,MyRelationParam.full());
        if(tourismProjectTravelNotesWrite == null){
            return ResponseResult.success(null);
        }
        TourismProjectTravelNotesWriteVo tourismProjectTravelNotesWriteVo = MyModelUtil.copyTo(tourismProjectTravelNotesWrite, TourismProjectTravelNotesWriteVo.class);

        //填充图片
        TourTravelNotesImg tourTravelNotesImg = new TourTravelNotesImg();
        tourTravelNotesImg.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        List<TourTravelNotesImg> tourTravelNotesImgList = tourTravelNotesImgService.getTourTravelNotesImgList(tourTravelNotesImg, "");
        List<String> imgUrlList = tourTravelNotesImgList.stream().map(TourTravelNotesImg::getImgUrl).collect(Collectors.toList());
        tourismProjectTravelNotesWriteVo.setImgUrls(imgUrlList);
        //填充关联话题
        TourTravelNotesTopicRelation tourTravelNotesTopicRelation = new TourTravelNotesTopicRelation();
        tourTravelNotesTopicRelation.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        List<TourTravelNotesTopicRelation> tourTravelNotesTopicRelationList =
                tourTravelNotesTopicRelationService.getTourTravelNotesTopicRelationList(tourTravelNotesTopicRelation, "");
        List<String> topicNameList = tourTravelNotesTopicRelationList.stream().map(TourTravelNotesTopicRelation::getTopicName).collect(Collectors.toList());
        tourismProjectTravelNotesWriteVo.setTopics(topicNameList);
        tourismProjectTravelNotesWriteVo.setTopicsList(BeanUtil.copyToList(tourTravelNotesTopicRelationList, NotesNameVo.class));
        //填充提及的用户
        TourTravelNotesMentionUser tourTravelNotesMentionUser = new TourTravelNotesMentionUser();
        tourTravelNotesMentionUser.setTravelNotesId(tourismProjectTravelNotesWrite.getId());
        List<TourTravelNotesMentionUser> tourTravelNotesMentionUserList = tourTravelNotesMentionUserService.getTourTravelNotesMentionUserList(tourTravelNotesMentionUser, "");
        List<TourTravelNotesMentionUserVo> tourTravelNotesMentionUserVo = MyModelUtil.copyCollectionTo(tourTravelNotesMentionUserList, TourTravelNotesMentionUserVo.class);
        tourismProjectTravelNotesWriteVo.setMentions(tourTravelNotesMentionUserVo);
        //填充关联用户
        return ResponseResult.success(tourismProjectTravelNotesWriteVo);
    }

    /**
     * 根据草稿id，删除草稿
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/removeByDraftId")
    public ResponseResult<Void> removeByDraftId(@MyRequestBody String writeId) {
        if (MyCommonUtil.existBlankArgument(writeId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        //验证是否为本人创建的数据
        Long userId = TokenData.takeFromRequest().getUserId();
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = tourismProjectTravelNotesWriteService.getById(Long.valueOf(writeId));
        if(tourismProjectTravelNotesWrite == null){
            return ResponseResult.success();
        }else {
            if(!tourismProjectTravelNotesWrite.getState().equals(AuditState.DRAFT)
                    && !tourismProjectTravelNotesWrite.getState().equals(AuditState.FAILAUDIT)){
                return ResponseResult.error(ErrorCodeEnum.UPLOAD_FILE_FAILED,"该数据状态不允许删除!");
            }
            //不是本人创建的数据
            if(!tourismProjectTravelNotesWrite.getCreateUserId().equals(userId)){
                return ResponseResult.error(ErrorCodeEnum.DATA_NOT_FOUND);
            }
        }
        tourTravelNotesPublishService.removeByDraftId(writeId);
        return ResponseResult.success();
    }

    /**
     * 草稿发布接口
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.PUBLISH)
    @PostMapping("/publishDraft")
    @Transactional
    public ResponseResult<Void> publishDraft(@RequestBody TourismProjectTravelNotesWriteToWebDto tourismProjectTravelNotesWriteDto) {

        Long userId = TokenData.takeFromRequest().getUserId();
        //先校验提及的用户id是否符合互关的状态
        if(CollectionUtils.isNotEmpty(tourismProjectTravelNotesWriteDto.getMentions())) {
            List<TourTravelNotesMentionUserDto> mentions = tourismProjectTravelNotesWriteDto.getMentions();
            Set<TourTravelNotesMentionUserDto> mentionsUserIdList = mentions.stream().filter(item -> item.getUserId() != null).collect(Collectors.toSet());
            List<TourShortUser> fouceEachFriendsByName = tourFansService.getFouceEachFriendsByName(userId, "");
            List<TourShortUser> fouceEachFriedsUserIdList = fouceEachFriendsByName.stream().filter(i -> i.getUserId() != null).collect(Collectors.toList());

            Map<Long, String> fouceEachFriendsUserIdMap = fouceEachFriedsUserIdList.stream().collect(Collectors.toMap(TourShortUser::getUserId, TourShortUser::getShowName));
            Map<Long, String> mentionsUserIdMap = mentionsUserIdList.stream().collect(Collectors.toMap(TourTravelNotesMentionUserDto::getUserId, TourTravelNotesMentionUserDto::getUserName));

            // 遍历 mentionsUserIdMap，检查其所有键值对是否都在 fouceEachFriendsUserIdMap 中
            for (Map.Entry<Long, String> entry : mentionsUserIdMap.entrySet()) {
                // 如果 fouceEachFriendsUserIdMap 不包含该 userId 或者值不相等，则返回 false
                if (!fouceEachFriendsUserIdMap.containsKey(entry.getKey()) || !fouceEachFriendsUserIdMap.get(entry.getKey()).equals(entry.getValue())) {
                    return ResponseResult.error(ErrorCodeEnum.MENTION_USER_ERROR, "提及的用户与本人不符合互关的状态");
                }
            }
        }
        //校验dto中的群聊是否为本人参与的群聊
        if(tourismProjectTravelNotesWriteDto.getTourImGroupId() != null) {
            List<TourShortImGroup> takePartImGroupListByName = tourImGroupService.getTakePartImGroupListByName(userId, "");
            List<Long> takePartImGroupIdList = takePartImGroupListByName.stream().mapToLong(TourShortImGroup::getId).boxed().collect(Collectors.toList());
            if (!takePartImGroupIdList.contains(tourismProjectTravelNotesWriteDto.getTourImGroupId())) {
                return ResponseResult.error(ErrorCodeEnum.MENTION_GROUP_ERROR, "本人未参与到关联的群聊中");
            }
        }
        tourTravelNotesPublishService.publishDraft(tourismProjectTravelNotesWriteDto);
        return ResponseResult.success();
    }

    /**
     * 审核中---->撤回接口
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/withdraw")
    public ResponseResult<Void> withdraw(@MyRequestBody String writeId) {
        if (MyCommonUtil.existBlankArgument(writeId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = tourismProjectTravelNotesWriteService.getById(Long.valueOf(writeId));
        //判断状态是否为审核中
        if(tourismProjectTravelNotesWrite == null){
            return ResponseResult.error(ErrorCodeEnum.DATA_ACCESS_FAILED,"该游记内容不存在，请刷新重试！");
        }
        if(!tourismProjectTravelNotesWrite.getState().equals(AuditState.UNAUDITSTATE)){
            return ResponseResult.error(ErrorCodeEnum.DATA_ACCESS_FAILED,"当前状态无法撤回");
        }else if(!tourismProjectTravelNotesWrite.getCreateUserId().equals(TokenData.takeFromRequest().getUserId())){
            return ResponseResult.error(ErrorCodeEnum.DATA_ACCESS_FAILED,"当前用户无法撤回");
        }else {
            tourismProjectTravelNotesWrite.setState(AuditState.DRAFT);
            tourismProjectTravelNotesWriteService.updateById(tourismProjectTravelNotesWrite);
            return ResponseResult.success();
        }
    }

    /**
     * 已审核通过的接口进行下架操作
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/delist")
    public ResponseResult<Void> delist(@MyRequestBody String writeId) {
        if (MyCommonUtil.existBlankArgument(writeId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = tourismProjectTravelNotesWriteService.getById(Long.valueOf(writeId));
        //校验该数据是否为用户所创建的数据
        if(!tourismProjectTravelNotesWrite.getCreateUserId().equals(TokenData.takeFromRequest().getUserId())){
            return ResponseResult.error(ErrorCodeEnum.DATA_ACCESS_FAILED,"当前用户无法进行下架操作");
        }
        //校验数据状态是否允许下架状态
        if(tourismProjectTravelNotesWrite.getUnmountState().equals(UnmountState.LISTING) && tourismProjectTravelNotesWrite.getState().equals(AuditState.SUCCEEDAUDIT)){
            tourismProjectTravelNotesWrite.setUnmountState(UnmountState.DELIST);
            tourismProjectTravelNotesWrite.setState(AuditState.DRAFT);
            tourismProjectTravelNotesWriteService.updateById(tourismProjectTravelNotesWrite);
            return ResponseResult.success();
        }else {
            return ResponseResult.error(ErrorCodeEnum.DATA_ACCESS_FAILED,"数据状态不允许下架");
        }
    }

    /**
     * 在写日志的页面，返回是否需要完善个人信息(0:需要完善个人信息;1:不需要完善)
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/isPerfect")
    public ResponseResult<Integer> isPerfect() {
        Long userId = TokenData.takeFromRequest().getUserId();
        TourismProjectTravelNotesWrite filter = new TourismProjectTravelNotesWrite();
        filter.setCreateUserId(userId);
        List<TourismProjectTravelNotesWrite> tourismProjectTravelNotesWriteList = tourismProjectTravelNotesWriteService.getTourismProjectTravelNotesWriteList(filter, "");
        int tourismProjectTravelNotesWriteCount = 0;
        if(CollectionUtils.isNotEmpty(tourismProjectTravelNotesWriteList)){
            tourismProjectTravelNotesWriteCount = tourismProjectTravelNotesWriteCount+(tourismProjectTravelNotesWriteList.size());
        }
        TourTourismProjectTravelNotes tourTourismProjectTravelNotes = new TourTourismProjectTravelNotes();
        tourTourismProjectTravelNotes.setCreateUserId(userId);
        List<TourTourismProjectTravelNotes> tourTourismProjectTravelNotesList = tourTourismProjectTravelNotesService.getTourTourismProjectTravelNotesList(tourTourismProjectTravelNotes, "");
        int tourTourismProjectTravelNotesCount = 0;
        if(CollectionUtils.isNotEmpty(tourTourismProjectTravelNotesList)){
            tourTourismProjectTravelNotesCount = tourTourismProjectTravelNotesCount+(tourTourismProjectTravelNotesList.size());
        }
        int totalCount = tourTourismProjectTravelNotesCount+tourismProjectTravelNotesWriteCount;

        //如果未超过3条，则不需要进行完善个人信息
        if(totalCount<3){
            return ResponseResult.success(1);
        }else {
            //查询个人信息表是否有必填信息需要用户完善
            TourUser tourUserInfo = new TourUser();
            tourUserInfo.setUserId(userId);
            TourUser tourUser = tourUserService.getOne(tourUserInfo);

            //假设用户的展示姓名和邮箱为空的话，则进行弹窗完善用户个人的信息
            if(StringUtils.isEmpty(tourUser.getShowName()) || StringUtils.isEmpty(tourUser.getEmail())){
                return ResponseResult.success(0);
            }
            return ResponseResult.success(1);
        }

    }

    /**
     * 保存个人信息
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/savePerfect")
    public ResponseResult<Void> savePerfect(@RequestBody WebsiteTourUserDto websiteTourUserDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(websiteTourUserDto, UpdateGroup.class);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        Long userId = TokenData.takeFromRequest().getUserId();
//        TourUser tourUser = tourUserService.getById(userId);
        TourUser tourUserModel = MyModelUtil.copyTo(websiteTourUserDto, TourUser.class);
        tourUserModel.setUserId(userId);
//        if(websiteTourUserDto.getShowName() != null){
//            tourUserModel.setShowName(websiteTourUserDto.getShowName());
//        }
//        if(websiteTourUserDto.getEmail() != null){
//            tourUserModel.setEmail(websiteTourUserDto.getEmail());
//        }
//        if(websiteTourUserDto.getAddress() != null){
//            tourUserModel.setAddress(websiteTourUserDto.getAddress());
//        }
//        if(websiteTourUserDto.getJob() != null){
//            tourUserModel.setJob(websiteTourUserDto.getJob());
//        }


        tourUserService.updateById(tourUserModel);
        return ResponseResult.success();
    }

    /**
     * 用户发布游记选择所属分类---->目的地
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getWriteBelongTab")
    public ResponseResult<List<TourWriteBelongTabVo>> getWriteBelongTab() {

        DirectoryInfo directoryInfo  = new DirectoryInfo();
        directoryInfo.setParentId(0L);
        directoryInfo.setDirectoryType(1);
        List<DirectoryInfo> directoryInfoList = directoryInfoService.getDirectoryInfoList(directoryInfo, "");

        List<TourWriteBelongTabVo> tourWriteBelongTabVoList = MyModelUtil.copyCollectionTo(directoryInfoList, TourWriteBelongTabVo.class);
        List<TourWriteBelongTabVo> newDirectoryInfoList = new ArrayList<>();
        for(TourWriteBelongTabVo i : tourWriteBelongTabVoList){
            if(!i.getId().equals("10")){
                DirectoryInfo directoryInfo2  = new DirectoryInfo();
                directoryInfo2.setParentId(Long.valueOf(i.getId()));
                directoryInfo2.setDirectoryType(1);
                List<DirectoryInfo> bodyDirectoryInfoList = directoryInfoService.getDirectoryInfoList(directoryInfo2, "");

                List<TourWriteBelongTabVo> bodyTourWriteBelongTabVoList = MyModelUtil.copyCollectionTo(bodyDirectoryInfoList, TourWriteBelongTabVo.class);
                if(CollectionUtils.isNotEmpty(bodyDirectoryInfoList)){
                    i.setTourWriteBelongTabVoList(bodyTourWriteBelongTabVoList);
                }
                newDirectoryInfoList.add(i);
            }
        }
        return ResponseResult.success(newDirectoryInfoList);
    }

    /**
     * 根据名称查询互关的好友信息
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getFouceEachFriendsByName")
    public ResponseResult<List<TourShortUserVo>> getFouceEachFriendsByName(@Validated TourFourceEachFriendsDto tourFourceEachFriendsDto) {
        //limit20
        PageMethod.startPage(tourFourceEachFriendsDto.getPageNum(), tourFourceEachFriendsDto.getPageSize(), true);
        Long userId = TokenData.takeFromRequest().getUserId();
        List<TourShortUser> tourShortUserList = tourFansService.getFouceEachFriendsByName(userId, tourFourceEachFriendsDto.getName());
        List<TourShortUserVo> tourShortUserVoList = MyModelUtil.copyCollectionTo(tourShortUserList, TourShortUserVo.class);
        return ResponseResult.success(tourShortUserVoList);
    }

    /**
     * 模糊搜索话题列表
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getTopicListByName")
    public ResponseResult<List<TourTravelNotesTopicVo>> getTopicListByName(@Validated TourTravelNotesTopicByNameDto tourTravelNotesTopicByNameDto) {
        //limit20
        PageMethod.startPage(tourTravelNotesTopicByNameDto.getPageNum(), tourTravelNotesTopicByNameDto.getPageSize(), true);
        TourTravelNotesTopic tourTravelNotesTopic = new TourTravelNotesTopic();
        tourTravelNotesTopic.setName(tourTravelNotesTopicByNameDto.getName());
        MyOrderParam myOrderParam = new MyOrderParam();
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourTravelNotesTopic.class);
        myOrderParam.add(new MyOrderParam.OrderInfo("hotValue", false, null));
        List<TourTravelNotesTopic> tourTravelNotesTopicList = tourTravelNotesTopicService.getTourTravelNotesTopicList(tourTravelNotesTopic,orderBy);
        List<TourTravelNotesTopicVo> tourTravelNotesTopicVoList = MyModelUtil.copyCollectionTo(tourTravelNotesTopicList, TourTravelNotesTopicVo.class);
        //专题ids
        List<Long> topicIdList = tourTravelNotesTopicVoList.stream().map(TourTravelNotesTopicVo::getId).map(Long::valueOf).collect(Collectors.toList());
        Map<Long, Integer> viewCountListTopicByName;
        if(!topicIdList.isEmpty()){
            viewCountListTopicByName= tourTravelNotesTopicService.getViewCountListTopicByName(topicIdList);
        } else {
            viewCountListTopicByName = new HashMap<Long, Integer>();
        }

        //放入浏览量的数值
        if(!ObjectUtil.isEmpty(viewCountListTopicByName)){
            for (TourTravelNotesTopicVo item : tourTravelNotesTopicVoList) {
                item.setViewCount(viewCountListTopicByName.get(Long.valueOf(item.getId())));
            }
        }
        if(tourTravelNotesTopicByNameDto.getName()!=null&&!tourTravelNotesTopicByNameDto.getName().isEmpty()){
            List<TourTravelNotesTopicVo> collect = tourTravelNotesTopicVoList.stream().filter(item -> item.getName().equals(tourTravelNotesTopicByNameDto.getName())).collect(Collectors.toList());
            if(collect.isEmpty()){
                TourTravelNotesTopicVo tourTravelNotesTopicVo = new TourTravelNotesTopicVo();
                tourTravelNotesTopicVo.setName(tourTravelNotesTopicByNameDto.getName());
                tourTravelNotesTopicVoList.add(0,tourTravelNotesTopicVo);
            }
        }

        return ResponseResult.success(tourTravelNotesTopicVoList);
    }

    /**
     * 模糊搜索自己参与的群聊列表
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/getTakePartImGroupListByName")
    public ResponseResult<List<TourShortImGroupVo>> getTakePartImGroupListByName(@Validated TourTakePartImGroupDto tourTakePartImGroupDto) {
        //limit20
        PageMethod.startPage(tourTakePartImGroupDto.getPageNum(), tourTakePartImGroupDto.getPageSize(), true);
        Long localUserId = TokenData.takeFromRequest().getUserId();
        List<TourShortImGroup> takePartImGroupListByName = tourImGroupService.getTakePartImGroupListByName(localUserId,tourTakePartImGroupDto.getName());

        //根据群聊id，填充每个群聊的人数以及每个群聊的头像
        Set<Long> set = new HashSet();
        set.addAll(takePartImGroupListByName.stream()
                .filter(t -> t.getId() != null)  // 过滤掉 id 为 null 的元素
                .map(TourShortImGroup::getId)    // 提取 id
                .collect(Collectors.toSet()));

        //查询群聊中有哪些群成员id
        List<TourImMember> tourImMemberList = tourImMemberService.getInList("groupId", set);
        // 根据群 ID 对群成员进行分组，并且每个群组最多取前 9 个成员
        Map<Long, List<TourImMember>> groupedMembers = tourImMemberList.stream()
                .collect(Collectors.groupingBy(
                        TourImMember::getGroupId,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                members -> members.stream().limit(9).collect(Collectors.toList())  // 限制每个群组的成员为前 9 个
                        )
                ));
        // 提取 userId 并去重
        Set<Long> uniqueUserIds = tourImMemberList.stream().map(TourImMember::getUserId).collect(Collectors.toSet());  // 使用 Set 自动去重
        // 根据userId获取用户头像
        List<TourUser> userIdList = tourUserService.getInList("userId", uniqueUserIds);
        // 使用 Stream 提取 userId 和 headImageUrl，生成 Map
        Map<Long, String> userHeadImageMap = userIdList.stream()
                .collect(Collectors.toMap(TourUser::getUserId, TourUser::getHeadImageUrl));
        //根据群成员id来查询群成员的头像
        for(TourShortImGroup i:takePartImGroupListByName){
                i.setCount(tourImMemberList.stream().filter(e -> e.getGroupId().equals(i.getId())).collect(Collectors.toList()).size());
            if(StringUtils.isBlank(i.getGroupAvatarUrl())){
                //没有设置头像，则进行拼头像
                List<TourImMember> tourImMembers = groupedMembers.get(i.getId());
                List<String> avatarUrls = tourImMembers.stream().map(TourImMember::getUserId).map(userId -> userHeadImageMap.get(userId)).collect(Collectors.toList());
                i.setMemberHeadImg(avatarUrls);
            }
        }

        List<TourShortImGroupVo> tourShortImGroupVo = MyModelUtil.copyCollectionTo(takePartImGroupListByName, TourShortImGroupVo.class);
        return ResponseResult.success(tourShortImGroupVo);
    }


}
