package com.gxwebsoft.love.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.love.entity.UserProfile;
import com.gxwebsoft.love.mapper.UserProfileMapper;
import com.gxwebsoft.love.param.UserProfileParam;
import com.gxwebsoft.love.service.UserProfileService;
import com.gxwebsoft.shop.entity.UserFollow;
import com.gxwebsoft.shop.entity.UserLike;
import com.gxwebsoft.shop.service.UserFollowService;
import com.gxwebsoft.shop.service.UserLikeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员资料表Service实现
 *
 * @author 科技小王子
 * @since 2023-06-09 21:42:26
 */
@Service
public class UserProfileServiceImpl extends ServiceImpl<UserProfileMapper, UserProfile> implements UserProfileService {
    @Resource
    private UserService userService;
    @Resource
    private UserFollowService userFollowService;
    @Resource
    private UserLikeService userLikeService;

    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public PageResult<UserProfile> pageRel(UserProfileParam param) {
        PageParam<UserProfile, UserProfileParam> page = new PageParam<>(param);


        // 我关注的人
        final List<UserFollow> myFollows = userFollowService.list(new LambdaQueryWrapper<UserFollow>().eq(UserFollow::getUserId, param.getLoginUserId()).orderByDesc(UserFollow::getCreateTime));
        List<Integer> followIds = myFollows.stream().map(UserFollow::getShopId).collect(Collectors.toList());
        // 我点赞的人
        final List<UserLike> myLikes = userLikeService.list(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, param.getLoginUserId()));
        Set<Integer> likeUserIds = myLikes.stream().map(UserLike::getToUserId).collect(Collectors.toSet());

        // 搜素条件
        if (param.getScene() != null) {
            // 推荐recommend
            if (param.getScene().equals("recommend")) {
                param.setRecommend(true);
                param.setCityMate(null);
                param.setNUserIds(likeUserIds); // 排除点赞的人
                page.setDefaultOrder("create_time desc");
            }
            // 同城intraCity
            if (param.getScene().equals("intraCity")) {
                param.setRecommend(null);
                param.setNUserIds(likeUserIds); // 排除点赞的人
                page.setDefaultOrder("create_time desc");
            }
            // 关注focus
            if (param.getLoginUserId() != null && param.getScene().equals("focus")) {

                if (!CollectionUtils.isEmpty(followIds)) {
                    // 分页处理
                    param.setUserIds(followIds);
                    param.setRecommend(null);
                    param.setCityMate(null);
                    List<UserProfile> list = baseMapper.selectPageRel(page, param);
                    final List<User> userList = userService.listByIds(followIds);
                    final Map<Integer, List<User>> collect = userList.stream().collect(Collectors.groupingBy(User::getUserId));
                    // 重新排序
                    List<UserProfile> newList = new ArrayList<>();
                    for (Integer id : followIds) {
                        Optional<UserProfile> first = list.stream().filter(p -> p.getUserId().equals(id)).findFirst();
                        if (first.isPresent()) {
                            UserProfile userProfile = first.get();
                            userProfile.setUserInfo(collect.get(id).get(0));
                            final boolean isLike = likeUserIds.stream().filter(f -> f.equals(id)).findFirst().isPresent();
                            userProfile.setFollow(true);
                            userProfile.setLiked(isLike);
                            newList.add(userProfile);
                        }else {
                            logger.error("用户{}不存在", id);
                        }

                    }
                    return new PageResult<>(newList, (long) myFollows.size());
                } else {
                    return new PageResult<>(new ArrayList<>(), (long) myFollows.size());
                }
            }
            // 相册是否为空
            param.setAlbums(true);
        } else {
            param.setCityMate(null);
        }
        List<UserProfile> list = baseMapper.selectPageRel(page, param);
        if (CollectionUtils.isEmpty(list)) {
            return new PageResult<>(list, page.getTotal());
        }


        final Set<Integer> userIds = list.stream().map(UserProfile::getUserId).collect(Collectors.toSet());
        final List<User> userList = userService.listByIds(userIds);
        final Map<Integer, List<User>> collect = userList.stream().collect(Collectors.groupingBy(User::getUserId));
        list.forEach(d -> {
            // 附加用户基本信息
            d.setUserInfo(collect.get(d.getUserId()).get(0));
            // 是否关注
            final boolean isFollows = myFollows.stream().filter(f -> f.getShopId().equals(d.getUserId())).findFirst().isPresent();
            final boolean isLike = likeUserIds.stream().filter(f -> f.equals(d.getUserId())).findFirst().isPresent();
            d.setFollow(isFollows);
            d.setLiked(isLike);

        });

        return new PageResult<>(list, page.getTotal());
    }


    @Override
    public List<UserProfile> listRel(UserProfileParam param) {
        List<UserProfile> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<UserProfile, UserProfileParam> page = new PageParam<>();
        page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public UserProfile getByIdRel(Integer id) {
        UserProfileParam param = new UserProfileParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

}
