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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
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.DisableDataFilter;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.webadmin.app.website.dto.GetMainMemberDto;
import com.tourism.webadmin.app.website.dto.TourWebFansDto;
import com.tourism.webadmin.app.website.dto.UserMainMemberVo;
import com.tourism.webadmin.app.website.service.TourMemberService;
import com.tourism.webadmin.app.website.vo.GlobalUserSearchVo;
import com.tourism.webadmin.app.website.vo.TourFriendsVo;
import com.tourism.webadmin.back.dto.TourFansDto;
import com.tourism.webadmin.back.model.TourFans;
import com.tourism.webadmin.back.model.TourTourismProjectTravelNotes;
import com.tourism.webadmin.back.model.TourUser;
import com.tourism.webadmin.back.model.constant.NoticeType;
import com.tourism.webadmin.back.service.TourFansService;
import com.tourism.webadmin.back.service.TourTourismProjectTravelNotesService;
import com.tourism.webadmin.back.service.TourUserService;
import com.tourism.webadmin.back.vo.TourFansVo;
import com.tourism.webadmin.back.vo.TourUserVo;
import com.tourism.webadmin.enums.MyAttentionStatus;
import com.tourism.webadmin.enums.SystemDefault;
import com.tourism.webadmin.strategy.dto.FocusDTO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author 畅
 * @date 2024年12月28日 周四 11:15:00
 */
@Tag(name = "粉丝接口")
@Slf4j
@RestController
@RequestMapping("/website/tourism/fans")
@DisableDataFilter
public class TourWebFansController {
    @Autowired
    private TourFansService tourFansService;
    @Autowired
    private TourUserService tourUserService;
    @Autowired
    private TourTourismProjectTravelNotesService tourTourismProjectTravelNotesService;
    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private TourMemberService tourMemberService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     *  获取用户首页会话列表
     * @param params
     * @return
     */
    @GetMapping("/getTourMemberList")
    public ResponseResult<UserMainMemberVo> getTourMemberList(GetMainMemberDto params){
        Long userId = TokenData.takeFromRequest().getUserId();
        UserMainMemberVo list=tourMemberService.getTourMemberList(params,userId);
        return ResponseResult.success(list);
    }
    /**
     * 全局关键字用户搜索
     * @param showName 用户昵称关键字
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return 包含用户信息、粉丝数量和关注状态的分页数据
     */
    @GetMapping("/getUserListByNickname")
    public ResponseResult<MyPageData<GlobalUserSearchVo>> getUserListByNickname(String showName, Integer pageNum, Integer pageSize) {

        // 参数校验
        if (StringUtils.isBlank(showName)) {
            return ResponseResult.success(null);
        }
        //设置分页参数
        pageNum = (pageNum == null) ? 1 : pageNum;
        pageSize = (pageSize == null) ? 4 : pageSize;

        // 开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 查询用户信息
        TourUser filter = new TourUser();
        filter.setDeletedFlag(1);
        filter.setShowName(showName);
        List<TourUser> userList = tourUserService.getTourUserListWithRelation(filter, null);

        //null处理
        if (userList == null || userList.isEmpty()){
            return ResponseResult.success(MyPageUtil.makeResponseData(new ArrayList<>(), GlobalUserSearchVo.class));
        }

        //用户ids
        List<Long> userIds = userList.stream().map(TourUser::getUserId).collect(Collectors.toList());

        //用户粉丝数量查询
        Map<Long, Long> fansCountMap = tourFansService.list(
                new LambdaQueryWrapper<TourFans>().in(TourFans::getAttentionId, userIds)
                        .eq(TourFans::getDeleteFlag, 1)
        ).stream().collect(Collectors.groupingBy(
                TourFans::getAttentionId,
                Collectors.counting()
        ));

        // 当前登录用户ID
        Long currentUserId = TokenData.takeFromRequest().getUserId();
//        Long currentUserId = id;

        // 我的粉丝列表  attentionId = currentUserId
        List<TourFans> myFansList = tourFansService.list(
                new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, currentUserId) .eq(TourFans::getDeleteFlag, 1)
        );
        //我的关注列表  createUserId = currentUserId
        List<TourFans> myFocusList = tourFansService.list(
                new LambdaQueryWrapper<TourFans>().eq(TourFans::getCreateUserId, currentUserId) .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());

        // 构造结果数据
        List<GlobalUserSearchVo> resultList = userList.stream().map(user -> {
            GlobalUserSearchVo result = new GlobalUserSearchVo();
            TourUserVo userVo = MyModelUtil.copyTo(user, TourUserVo.class);

            //填充用户粉丝数量
            result.setFansCount(fansCountMap.getOrDefault(user.getUserId(), 0L).toString());

            // 头像 URL 转换
            if (StringUtils.isNotEmpty(user.getHeadImageUrl())) {
                userVo.setHeadImageUrl(
                        UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), user.getHeadImageUrl())
                );
            }
            result.setTourUserVo(userVo);

            // 每个用户的粉丝数量 被关注人->userId
            Long fansCount = tourFansService.count(
                    new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, user.getUserId()) .eq(TourFans::getDeleteFlag, 1)
            );
            result.setFansCount(fansCount.toString());

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

            return result;
        }).collect(Collectors.toList());

        // 分页构造返回数据
        MyPageData<GlobalUserSearchVo> responseData = MyPageUtil.makeResponseData(resultList, GlobalUserSearchVo.class);
        responseData.setTotalCount(Long.valueOf(userList.size()));
        return ResponseResult.success(responseData);
    }



    /**
     * 获取自己的粉丝
     * @return
     */
    @GetMapping("/getMyFansCount")
    public ResponseResult<String> getMyFansCount(String userId){
        Long count = tourFansService.count(new LambdaQueryWrapper<TourFans>()
                .eq(StringUtils.isBlank(userId),TourFans::getAttentionId, TokenData.takeFromRequest() == null ? "" :TokenData.takeFromRequest().getUserId())
                .eq(StringUtils.isNotBlank(userId),TourFans::getAttentionId, userId)
                .eq(TourFans::getDeleteFlag, 1)

        );
        return ResponseResult.success(count.toString());
    }

    /**
     * 获取我关注的数量
     * @return
     */
    @GetMapping("/getMyConcernCount")
    public ResponseResult<String> getMyConcern(String userId){
        Long count = tourFansService.count(new LambdaQueryWrapper<TourFans>()
                .eq(StringUtils.isBlank(userId),TourFans::getCreateUserId, TokenData.takeFromRequest() == null ? "" :TokenData.takeFromRequest().getUserId())
                .eq(StringUtils.isNotBlank(userId),TourFans::getCreateUserId, userId)
                .eq(TourFans::getDeleteFlag, 1)

        )
                ;
        return ResponseResult.success(count.toString());
    }

    /**
     * 查询用户发布游记的点赞数 如果没有就查当前用户的
     * @param userId
     * @return
     */
    @GetMapping("/getMylikeCount")
    public ResponseResult<String> getMylikeCount(String userId){
        Map<String, Object> map = tourTourismProjectTravelNotesService.getMap(new QueryWrapper<TourTourismProjectTravelNotes>()
                .select("sum(like_count) as count")
                .lambda()
                .eq(StringUtils.isBlank(userId), TourTourismProjectTravelNotes::getCreateUserId, TokenData.takeFromRequest() == null ? "" : TokenData.takeFromRequest().getUserId())
                .eq(StringUtils.isNotBlank(userId), TourTourismProjectTravelNotes::getCreateUserId, userId)
        );
        if (map != null) {
            return ResponseResult.success(map.get("count").toString());
        }
        return ResponseResult.success("0");
    }

    /**
     * 分页查询我的粉丝列表
     * @param tourWebFansDto
     * @return
     */
    @GetMapping("/getMyFans")
    public ResponseResult getMyFans(TourWebFansDto tourWebFansDto) {
        //分页条件如果为空赋值默认值
        if (tourWebFansDto.getPageNum() == null){
            tourWebFansDto.setPageNum(1);
        }
        if (tourWebFansDto.getPageSize() == null){
            tourWebFansDto.setPageSize(10);
        }
        Long userId = TokenData.takeFromRequest().getUserId();
        //开启分页
        PageMethod.startPage(tourWebFansDto.getPageNum(), tourWebFansDto.getPageSize());
        //根据当前登录人id查询
        List<TourFans> list = tourFansService.list(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, TokenData.takeFromRequest().getUserId()).orderByDesc(TourFans::getCreateTime).eq(TourFans::getDeleteFlag, 1));
        //查询到为空直接返回空数组
        if (list == null || list.size() == 0){
            return ResponseResult.success(new MyPageData<>());
        }
        //被关注人id列表
        Set<Long> collect = list.stream().map(TourFans::getAttentionId).collect(Collectors.toSet());
        //关注人id列表
        Set<Long> collecteds = list.stream().map(TourFans::getCreateUserId).collect(Collectors.toSet());
//        List<TourFans> tourFans = tourFansService.list(new LambdaQueryWrapper<TourFans>().in(TourFans::getCreateUserId, userId) .eq(TourFans::getDeleteFlag, 1));
//        List<Long> ids ;
//        if (!tourFans.isEmpty()){
//            ids = tourFans.stream().map(TourFans::getAttentionId).collect(Collectors.toList());
//        }else {
//            ids = new ArrayList<>();
//        }
        //根据id查询用户
        List<TourUser> tourUsers = tourUserService.listByIds(collect);
        List<TourUser> tourUserList = tourUserService.listByIds(collecteds);
        //分页
        //转换返回对象
        MyPageData<TourFansVo> tourFansVoMyPageData = MyPageUtil.makeResponseData(list, TourFansVo.class);
        List<TourFansVo> dataList = tourFansVoMyPageData.getDataList();
        //处理粉丝数
        if (!dataList.isEmpty()){
            Set<Long> longs = dataList.stream().map(TourFansVo::getCreateUserId).collect(Collectors.toSet());
            //查询粉丝数量根据关注人分组
            List<Map<String, Object>> mapList = tourFansService.listMaps(new QueryWrapper<TourFans>().select("count(*) as num,attention_id").lambda().in(TourFans::getAttentionId, longs) .eq(TourFans::getDeleteFlag, 1).groupBy(TourFans::getAttentionId));
            //设置匹配对应的粉丝数
            dataList.forEach(item->{
                TourFans one = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, userId).eq(TourFans::getDeleteFlag, 1).eq(TourFans::getCreateUserId, item.getCreateUserId()));
                TourFans one1 = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, item.getCreateUserId()).eq(TourFans::getDeleteFlag, 1).eq(TourFans::getCreateUserId, userId));
                //如果双等于说明互关
                if (Objects.nonNull(one) && Objects.nonNull(one1)) {
                    item.setFansStatus("2");
                    item.setFansStatusName("互关");
                }else if (Objects.nonNull(one1) && Objects.isNull(one)){ //我关注他但是他没关注我说明单向关注
                    item.setFansStatus("1");
                    item.setFansStatusName("已关注");
                }else if (Objects.nonNull(one) && Objects.isNull(one1)){ //他关注了我但是我没关注他说明被关注
                    item.setFansStatus("4");
                    item.setFansStatusName("被关注");
                }else{//都没有说明未关注
                    item.setFansStatus("0");
                    item.setFansStatusName("未关注");
                }
                Optional<Map<String, Object>> first = mapList.stream().filter(i -> Objects.equals(item.getCreateUserId().toString(), i.get("attention_id").toString())).findFirst();
                if (first.isPresent()) {
                    Map<String, Object> stringObjectMap = first.get();
                    item.setFansNum(stringObjectMap.get("num").toString());
                }
            });
        }
        //循环设置字典
        dataList.forEach(item->{
            //过滤被关注人
            Set<TourUser> attentionSet = tourUsers.stream().filter(i -> i.getUserId().toString().equals(item.getAttentionId().toString())).collect(Collectors.toSet());
            if (!attentionSet.isEmpty()) {
                //设置进字典map
                List<HashMap<String, Object>> collected = attentionSet.stream()
                        .map(i -> {
                            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                            stringObjectHashMap.put("id", i.getUserId().toString());
                            stringObjectHashMap.put("name", i.getShowName());
                            stringObjectHashMap.put("avatar",UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(),i.getHeadImageUrl()));

                            return stringObjectHashMap;
                        }).collect(Collectors.toList());
                HashMap<String, Object> stringObjectHashMap = collected.get(0);
                item.setAttentionIdDictMap(stringObjectHashMap);
            }
            //过滤关注人
            Set<TourUser> userSet = tourUserList.stream().filter(i ->{
                if (i.getUserId().toString().equals(item.getCreateUserId().toString())) {
                    return true;
                }
                return false;
            }).collect(Collectors.toSet());
            if (!userSet.isEmpty()) {
                //设置进字典map
                List<HashMap<String, Object>> collected = userSet.stream().map(i -> {
                    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                    stringObjectHashMap.put("id", i.getUserId().toString());
                    stringObjectHashMap.put("name", i.getShowName());
                    stringObjectHashMap.put("avatar",UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(),i.getHeadImageUrl()));
                    return stringObjectHashMap;
                }).collect(Collectors.toList());
                HashMap<String, Object> stringObjectHashMap = collected.get(0);
                item.setCreateUserIdDictMap(stringObjectHashMap);

            }
        });
        tourFansVoMyPageData.setDataList(dataList);
        return ResponseResult.success(tourFansVoMyPageData);
    }

    /**
     * 获取我关注的人列表
     * @param tourWebFansDto
     * @return
     */
    @GetMapping("/getMyConCern")
    public ResponseResult<MyPageData<TourFansVo>> getMyConCern(TourWebFansDto tourWebFansDto) {
        //分页条件如果为空赋值默认值
        if (tourWebFansDto.getPageNum() == null){
            tourWebFansDto.setPageNum(1);
        }
        if (tourWebFansDto.getPageSize() == null){
            tourWebFansDto.setPageSize(10);
        }
        TokenData tokenData = TokenData.takeFromRequest();
        Long userId = tokenData.getUserId();
        //开启分页
        PageMethod.startPage(tourWebFansDto.getPageNum(), tourWebFansDto.getPageSize());
        //根据当前登录人id查询
        List<TourFans> list = tourFansService.list(new LambdaQueryWrapper<TourFans>().eq(TourFans::getCreateUserId, TokenData.takeFromRequest().getUserId()).orderByDesc(TourFans::getCreateTime) .eq(TourFans::getDeleteFlag, 1));
        //查询到为空直接返回空数组
        if (list == null || list.size() == 0){
            return ResponseResult.success(new MyPageData<>());
        }
        //被关注人id列表
        Set<Long> collect = list.stream().map(TourFans::getAttentionId).collect(Collectors.toSet());
        //查询我关注的人的关注
//        List<TourFans> tourFans = tourFansService.list(new LambdaQueryWrapper<TourFans>().in(TourFans::getCreateUserId, collect) .eq(TourFans::getDeleteFlag, 1));
//        List<Long> longSet;
//        过去出来我关注的人的关注
//        if (!tourFans.isEmpty()){
//            longSet =  tourFans.stream().map(TourFans::getAttentionId).collect(Collectors.toList());
//        } else {
//            longSet = new ArrayList<>();
//        }
        //关注人id列表
        Set<Long> collecteds = list.stream().map(TourFans::getCreateUserId).collect(Collectors.toSet());

        //根据id查询用户
        List<TourUser> tourUsers = tourUserService.listByIds(collect);
        List<TourUser> tourUserList = tourUserService.listByIds(collecteds);
        //分页
        //转换返回对象
        MyPageData<TourFansVo> tourFansVoMyPageData = MyPageUtil.makeResponseData(list, TourFansVo.class);
        List<TourFansVo> dataList = tourFansVoMyPageData.getDataList();
        //处理粉丝数
        if (!dataList.isEmpty()){
            Set<String> longs = dataList.stream().map(TourFansVo::getAttentionId).collect(Collectors.toSet());
            //查询粉丝数量根据关注人分组
            List<Map<String, Object>> mapList = tourFansService.listMaps(new QueryWrapper<TourFans>().select("count(*) as num,attention_id").lambda().in(TourFans::getAttentionId, longs) .eq(TourFans::getDeleteFlag, 1).groupBy(TourFans::getAttentionId));
            //设置匹配对应的粉丝数
            dataList.forEach(item->{
                TourFans fans = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, item.getAttentionId()).eq(TourFans::getDeleteFlag, 1).eq(TourFans::getCreateUserId, userId));
                TourFans tourFansServiceOne = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, userId).eq(TourFans::getDeleteFlag, 1).eq(TourFans::getCreateUserId, item.getAttentionId()));
                //如果双等于说明互关
                if (Objects.nonNull(fans) && Objects.nonNull(tourFansServiceOne)) {
                    item.setFansStatus("2");
                    item.setFansStatusName("互关");
                }else if (Objects.nonNull(fans) && !Objects.nonNull(tourFansServiceOne)){ //我关注他但是他没关注我说明单向关注
                    item.setFansStatus("1");
                    item.setFansStatusName("已关注");
                }else if (!Objects.nonNull(fans) && Objects.nonNull(tourFansServiceOne)){ //他关注了我但是我没关注他说明被关注
                    item.setFansStatus("4");
                    item.setFansStatusName("被关注");
                }else{//都没有说明未关注
                    item.setFansStatus("0");
                    item.setFansStatusName("未关注");
                }
                Optional<Map<String, Object>> first = mapList.stream().filter(i -> Objects.equals(item.getAttentionId().toString(), i.get("attention_id").toString())).findFirst();
                if (first.isPresent()) {
                    Map<String, Object> stringObjectMap = first.get();
                    item.setFansNum(stringObjectMap.get("num").toString());
                }
            });
        }

        //循环设置字典
        dataList.forEach(item->{
            //过滤被关注人
            Set<TourUser> attentionSet = tourUsers.stream().filter(i -> i.getUserId().toString().equals(item.getAttentionId().toString())).collect(Collectors.toSet());
            if (!attentionSet.isEmpty()) {
                //设置进字典map
                List<HashMap<String, Object>> collected = attentionSet.stream()
                        .map(i -> {
                            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                            stringObjectHashMap.put("id", i.getUserId().toString());
                            stringObjectHashMap.put("name", i.getShowName());
                            stringObjectHashMap.put("avatar",UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(),i.getHeadImageUrl()));
                            return stringObjectHashMap;
                        }).collect(Collectors.toList());
                HashMap<String, Object> stringObjectHashMap = collected.get(0);
                item.setAttentionIdDictMap(stringObjectHashMap);
            }
            //过滤关注人
            Set<TourUser> userSet = tourUserList.stream().filter(i ->{
                if (i.getUserId().toString().equals(item.getCreateUserId().toString())) {
                    return true;
                }
                return false;
            }).collect(Collectors.toSet());
            if (!userSet.isEmpty()) {
                //设置进字典map
                List<HashMap<String, Object>> collected = userSet.stream().map(i -> {
                    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                    stringObjectHashMap.put("id", i.getUserId().toString());
                    stringObjectHashMap.put("name", i.getShowName());
                    stringObjectHashMap.put("avatar",UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(),i.getHeadImageUrl()));

                    return stringObjectHashMap;
                }).collect(Collectors.toList());
                HashMap<String, Object> stringObjectHashMap = collected.get(0);
                item.setCreateUserIdDictMap(stringObjectHashMap);
            }
        });
        tourFansVoMyPageData.setDataList(dataList);
        return ResponseResult.success(tourFansVoMyPageData);
    }

    /**
     * 保存关注记录
     * @param tourFansDto
     * @return
     */
    @PostMapping("/saveConcern")
//    @PushNotification(noticeType = NoticeType.NOTICE_FOCUS)
    public ResponseResult saveConcern(@RequestBody TourFansDto  tourFansDto) {
        boolean flag = tourUserService.existId(tourFansDto.getAttentionId());
        if (!flag){
            return ResponseResult.error(ErrorCodeEnum.SERVER_INTERNAL_ERROR);
        }
        TourUser byId = tourUserService.getById(TokenData.takeFromRequest().getUserId());
        TourFans one = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, tourFansDto.getAttentionId()).eq(TourFans::getCreateUserId, TokenData.takeFromRequest().getUserId()).eq(TourFans::getDeleteFlag, 1));
        //如果id为空说明是新增
        if (Objects.isNull(one)) {
            if (Objects.equals(tourFansDto.getAttentionId(),TokenData.takeFromRequest().getUserId())) {
                return ResponseResult.error(ErrorCodeEnum.SERVER_INTERNAL_ERROR);
            }
            TourFans tourFans = new TourFans();
            BeanUtils.copyProperties(tourFansDto, tourFans);
            //设置当前登录人id
            tourFans.setCreateUserId(TokenData.takeFromRequest().getUserId());
            //设置关注时间
            tourFans.setCreateTime(new Date());
            //设置更新时间默认值
            tourFans.setUpdateTime(new Date());
            tourFans.setUpdateUserId(TokenData.takeFromRequest().getUserId());
            //保存
            boolean save = tourFansService.save(tourFans);
            //保存成功返回id
            if (save) {
                TourFans tourFansServiceOne = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId,TokenData.takeFromRequest().getUserId()).eq(TourFans::getCreateUserId, tourFansDto.getAttentionId()).eq(TourFans::getDeleteFlag, 1));
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                if (tourFansServiceOne != null) {
                    FocusDTO focusDTO = new FocusDTO();
                    focusDTO.setNoticeType(NoticeType.NOTICE_FOCUS);
                    focusDTO.setGroupId(SystemDefault.FOCUS_USERID_OR_GROUPID.toString());
                    focusDTO.setGetUserId(tourFansDto.getAttentionId().toString());
                    focusDTO.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    focusDTO.setSendUserId(TokenData.takeFromRequest().getUserId().toString());
                    TourUserVo tourUserVo = MyModelUtil.copyTo(byId, TourUserVo.class);
                    focusDTO.setTourUserVo(tourUserVo);
                    String jsonstring= JSON.toJSONString(focusDTO);
                    rabbitTemplate.convertSendAndReceive("focusExchange","focusRouter",jsonstring);
                    stringStringHashMap.put("fansStatus", "2");
                    stringStringHashMap.put("fansStatusName", "互关");
                }else {
                    FocusDTO focusDTO = new FocusDTO();
                    focusDTO.setNoticeType(NoticeType.NOTICE_FOCUS);
                    focusDTO.setGroupId(SystemDefault.FOCUS_USERID_OR_GROUPID.toString());
                    focusDTO.setGetUserId(tourFansDto.getAttentionId().toString());
                    focusDTO.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    focusDTO.setSendUserId(TokenData.takeFromRequest().getUserId().toString());
                    TourUserVo tourUserVo = MyModelUtil.copyTo(byId, TourUserVo.class);
                    focusDTO.setTourUserVo(tourUserVo);
                    String jsonstring= JSON.toJSONString(focusDTO);
                    rabbitTemplate.convertSendAndReceive("focusExchange","focusRouter",jsonstring);
                    stringStringHashMap.put("fansStatus", "1");
                    stringStringHashMap.put("fansStatusName", "已关注");
                }
                return ResponseResult.success(stringStringHashMap);
            }
            return ResponseResult.error(ErrorCodeEnum.SERVER_INTERNAL_ERROR);
        }else {
            //删除操作
            TourFans tourFans = tourFansService.getOne(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, tourFansDto.getAttentionId()).eq(TourFans::getCreateUserId, TokenData.takeFromRequest().getUserId()).eq(TourFans::getDeleteFlag, 1));

            if (!Objects.isNull(tourFans)) tourFans.setDeleteFlag(-1);

            boolean removeById = tourFansService.updateById(tourFans);
            //删除成功返回成功
            if (removeById) {
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put("fansStatus","0");
                stringStringHashMap.put("fansStatusName","未关注");
                return ResponseResult.success(stringStringHashMap);
            }
            return ResponseResult.error(ErrorCodeEnum.SERVER_INTERNAL_ERROR);
        }
    }

    /**
     * 查询互关数量
     * @return
     */
    @GetMapping("/getFriendsCount")
    public ResponseResult<String> getFriendsCount(){
        //先查询当前登录人的关注列表
        List<TourFans> my = tourFansService.list(new LambdaQueryWrapper<TourFans>().eq(TourFans::getCreateUserId, TokenData.takeFromRequest().getUserId()).orderByDesc(TourFans::getCreateTime) .eq(TourFans::getDeleteFlag, 1));
        //如果为空则为单向关注
        if (my == null || my.isEmpty()){
            return ResponseResult.success("0");
        }
        //接着查询关注当前登录人的数据
        List<TourFans> myFans = tourFansService.list(new LambdaQueryWrapper<TourFans>().eq(TourFans::getAttentionId, TokenData.takeFromRequest().getUserId()).orderByDesc(TourFans::getCreateTime) .eq(TourFans::getDeleteFlag, 1));
        //如果为空则为单向关注
        if (myFans == null || myFans.isEmpty()){
            return ResponseResult.success("0");
        }
        //求两个集合交集，通过createUserId 和 attentionId交集，判断出哪些关注了当前登录人且同时当前登录人也关注他的
        List<TourFans> tourFans = my.stream().filter(item -> myFans.stream().map(TourFans::getCreateUserId).anyMatch(id -> Objects.equals(item.getAttentionId(), id)))
                .collect(Collectors.toList());
        Integer size = tourFans.size();
        return ResponseResult.success(size.toString());
    }
    /**
     * 获取互关列表
     * @param tourWebFansDto
     * @return
     */
    @GetMapping("/getFriends")
    public ResponseResult<TourFriendsVo> getFriends(TourWebFansDto tourWebFansDto) {
        //如果分页参数为空则设置哥默认的参数
        if (tourWebFansDto.getPageNum() == null){
            tourWebFansDto.setPageNum(1);
        }
        if (tourWebFansDto.getPageSize() == null){
            tourWebFansDto.setPageSize(10);
        }
        //先查询当前登录人的关注列表
        List<TourFans> my = tourFansService.list(new LambdaQueryWrapper<TourFans>() .eq(TourFans::getDeleteFlag, 1).eq(TourFans::getCreateUserId, TokenData.takeFromRequest().getUserId()).orderByDesc(TourFans::getCreateTime));
        //如果为空则为单向关注
        if (my == null || my.isEmpty()){
            return ResponseResult.success(new TourFriendsVo());
        }
        //接着查询关注当前登录人的数据
        List<TourFans> myFans = tourFansService.list(new LambdaQueryWrapper<TourFans>() .eq(TourFans::getDeleteFlag, 1).eq(TourFans::getAttentionId, TokenData.takeFromRequest().getUserId()).orderByDesc(TourFans::getCreateTime));
        //如果为空则为单向关注
        if (myFans == null || myFans.isEmpty()){
            return ResponseResult.success(new TourFriendsVo());
        }
        //求两个集合交集，通过createUserId 和 attentionId交集，判断出哪些关注了当前登录人且同时当前登录人也关注他的
        List<TourFans> tourFans = my.stream().filter(item -> myFans.stream().map(TourFans::getCreateUserId).anyMatch(id -> Objects.equals(item.getAttentionId(), id)))
                .collect(Collectors.toList());
        //手动list分页
        if (tourWebFansDto.getFlagPage() == 1){
            TourFriendsVo tourFriendsVo = new TourFriendsVo(this.build(tourFans), tourFans.size());
            return ResponseResult.success(tourFriendsVo);
        }
        Integer pageNum = (tourWebFansDto.getPageNum() - 1) * tourWebFansDto.getPageSize();
        if (tourFans.size()<= tourWebFansDto.getPageSize()){
            TourFriendsVo tourFriendsVo = new TourFriendsVo(this.build(tourFans), tourFans.size());
            for (TourFansVo tourFansVo : tourFriendsVo.getDataList()) {
                tourFansVo.setFansStatus("2");
            }
            return ResponseResult.success(tourFriendsVo);
        }else {
            List<TourFans> pageList = tourFans.subList(pageNum, tourWebFansDto.getPageSize());
            TourFriendsVo tourFriendsVo = new TourFriendsVo(this.build(pageList), tourFans.size());
            for (TourFansVo tourFansVo : tourFriendsVo.getDataList()) {
                tourFansVo.setFansStatus("2");
            }
            return ResponseResult.success(tourFriendsVo);
        }

    }

    /**
     * 处理姓名头像映射
     * @param tourFansList
     * @return
     */
    public List<TourFansVo> build(List<TourFans> tourFansList) {
        //获取所有关注的id
        Set<Long> collect = tourFansList.stream().map(TourFans::getAttentionId).collect(Collectors.toSet());
        if (!collect.isEmpty()){
        //根据id查询user
            List<TourUser> tourUsers = tourUserService.listByIds(collect);
        //关注列表开始循环
            List<TourFans> tourFans = tourFansList.stream().map(item -> {
                //匹配相关user获取到唯一匹配值
                Optional<TourUser> first = tourUsers.stream().filter(i -> Objects.equals(item.getAttentionId(), i.getUserId())).findFirst();
                //匹配搭配了
                if (first.isPresent()) {
                    //获取对象
                    TourUser tourUser = first.get();
                    //设置头像
                    tourUser.setHeadImageUrl(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourUser.getHeadImageUrl()));
                    TourUserVo tourUserVo = MyModelUtil.copyTo(tourUser, TourUserVo.class);
                    //设置返回信息
                    item.setAttentionIdDictMap(JSON.parseObject(JSON.toJSONString(tourUserVo)));
                }
                return item;
            }).collect(Collectors.toList());
            //转换vo
            List<TourFansVo> tourFansVos = MyModelUtil.copyCollectionTo(tourFans, TourFansVo.class);
            //把关注自己的人列出来
            Set<Long> collected = tourFansVos.stream().map(TourFansVo::getCreateUserId).collect(Collectors.toSet());
            //查询 查询条件是关注我的人，根据关注我的人进行group by 去重，统计关注我的这个人有多少粉丝
            List<Map<String, Object>> maps = tourFansService.listMaps(new QueryWrapper<TourFans>()
                    .select("count(id) as num,attention_id")
                    .lambda()
                    .in(TourFans::getAttentionId, collected)
                    .eq(TourFans::getDeleteFlag, 1)
                    .groupBy(TourFans::getAttentionId)
            );
            //通过map 重新匹配 匹配到了把粉丝数据塞入进去
            List<TourFansVo> tourFansVoList = tourFansVos.stream().map(item -> {
                Optional<Map<String, Object>> first = maps.stream().filter(i -> i.get("attention_id").toString().equals(item.getCreateUserId().toString())).findFirst();
                if (first.isPresent()) {
                    Map<String, Object> stringObjectMap = first.get();
                    item.getAttentionIdDictMap().put("fansNum", stringObjectMap.get("num"));
                    item.setFansNum(stringObjectMap.get("num").toString());
                }
                return item;
            }).collect(Collectors.toList());
            return tourFansVoList;
        }

        //返回写的list
        List<TourFansVo> tourFansVos = MyModelUtil.copyCollectionTo(tourFansList, TourFansVo.class);
        return tourFansVos;
    }
}
