package com.ruoyi.frequency.follow.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.controller.req.FollowUserReq;
import com.ruoyi.controller.req.FollowerPageByOther;
import com.ruoyi.controller.resp.FollowPageResp;
import com.ruoyi.enums.message.InteractionMessageEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.enterprise.entity.Enterprise;
import com.ruoyi.frequency.enterprise.service.EnterpriseService;
import com.ruoyi.frequency.follow.entity.Follow;
import com.ruoyi.frequency.follow.mapper.FollowMapper;
import com.ruoyi.frequency.follow.service.FollowService;
import com.ruoyi.message.frequency.interactionmessagerecord.service.InteractionMessageRecordService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 关注Service业务层处理
 *
 * @author liwenlong
 * @date 2023-07-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow>  implements FollowService
{
    @Autowired
    private FollowMapper followMapper;

    /**
     * 查询关注
     *
     * @param id 关注主键
     * @return 关注
     */
    @Override
    public Follow selectFollowById(Long id)
    {
        return followMapper.selectFollowById(id);
    }

    @Autowired
    private EnterpriseService enterpriseService;
    /**
     * 查询关注列表
     *
     * @param follow 关注
     * @return 关注
     */
    @Override
    public List<Follow> selectFollowList(Follow follow)
    {

        if (SecurityUtils.hasRoleKey("enterprise")){
            Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().lambda()
                    .ne(Enterprise::getDelFlag, PublicCommon.删除)
                    .eq(Enterprise::getSysUserId, SecurityUtils.getUserId()));
            if (enterprise == null){
                return new ArrayList<>();
            }
            follow.setFollowerUserType(UserEnums.enterprise.getCode());
            follow.setFollowerUserId(enterprise.getId());
        }else {
            return new ArrayList<>();
        }
        List<Follow> follows = followMapper.selectFollowList(follow);

        if (!follows.isEmpty()){
            Set<UserVo> userVoSet = follows.stream().map(s -> new UserVo(s.getUserType(), s.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,null);

            follows.stream().forEach(s ->{
                s.setUserInfo(userMap.get(new UserVo(s.getUserType(), s.getUserId())));
            });
        }
        return follows;
    }

    /**
     * 新增关注
     *
     * @param follow 关注
     * @return 结果
     */
    @Override
    public int insertFollow(Follow follow)
    {
        follow.setCreateTime(DateUtils.getNowDate());
        return followMapper.insertFollow(follow);
    }

    /**
     * 修改关注
     *
     * @param follow 关注
     * @return 结果
     */
    @Override
    public int updateFollow(Follow follow)
    {
        follow.setUpdateTime(DateUtils.getNowDate());
        return followMapper.updateFollow(follow);
    }

    /**
     * 批量删除关注
     *
     * @param ids 需要删除的关注主键
     * @return 结果
     */
    @Override
    public int deleteFollowByIds(Long[] ids)
    {
        return followMapper.deleteFollowByIds(ids);
    }

    /**
     * 删除关注信息
     *
     * @param id 关注主键
     * @return 结果
     */
    @Override
    public int deleteFollowById(Long id)
    {
        return followMapper.deleteFollowById(id);
    }


    @Override
    public ResponseData followUser(FollowUserReq req, UserVo userVo) {

        //查询数据是否存在
        Follow follow = this.getOne(new QueryWrapper<Follow>().lambda()
                .eq(Follow::getUserType, userVo.getUserType())
                .eq(Follow::getUserId, userVo.getUserId())
                .eq(Follow::getFollowerUserType, req.getUserType())
                .eq(Follow::getFollowerUserId, req.getUserId())
        );

        //是否关注
        boolean isFollow = false;

        if (follow == null){
            follow = new Follow().setUserId(userVo.getUserId())
                    .setUserType(userVo.getUserType())
                    .setFollowerUserId(req.getUserId())
                    .setFollowerUserType(req.getUserType());
            follow.setUpdateTime(new Date());
            this.save(follow);

            //关注
            isFollow = true;
        }else {
            //是否关注
            isFollow = ObjectUtil.notEqual(PublicCommon.启用,follow.getDelFlag());

            this.lambdaUpdate().set(Follow::getDelFlag,isFollow? PublicCommon.启用:PublicCommon.删除 )
                    .eq(Follow::getId,follow.getId()).update();
        }

        //互动消息
        pushMessage(req,userVo,isFollow);

        return ResponseData.success();
    }

    @Autowired
    private InteractionMessageRecordService interactionMessageRecordService;

    /**
     * 推送消息
     * @param req
     * @param userVo
     * @param isPush
     */
    private void pushMessage(FollowUserReq req, UserVo userVo, Boolean isPush) {

        InteractionMessageEnums enums = InteractionMessageEnums.FOLLOW;

        Long userId = req.getUserId();

        //互动消息
        interactionMessageRecordService.addInteractionMessage(userVo,new UserVo(req.getUserType(),req.getUserId()),PublicCommon.InteractionMessage.关注,userId,isPush, enums);

    }

    @Autowired
    private UserService userService;

    @Override
    public ResponseData followerPageBySelf(FollowerPageByOther req, UserVo userVo) {

        //筛去拉黑与被拉黑用户
//        List<UserVo> blockUserList = userService.blockUserList(userVo);
//        req.setBlockUserList(blockUserList);
//
//        //筛去屏蔽用户
//        List<UserVo> shieldUserList = userService.shieldUserList(userVo);
//        req.setShieldUserList(shieldUserList);

        Page<FollowPageResp> page = baseMapper.followerPageBySelf(new Page<>(req.getPageNo(), req.getPageSize()), userVo,userVo,req);

        if (!page.getRecords().isEmpty()){
            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getUserType(), resp.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

            page.getRecords().stream().forEach(resp ->{
                resp.setUserInfo(userMap.get(new UserVo(resp.getUserType(), resp.getUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public ResponseData followerPageByOther(FollowerPageByOther req, UserVo userVo) {
        //筛去拉黑与被拉黑用户
//        List<UserVo> blockUserList = userService.blockUserList(userVo);
//        req.setBlockUserList(blockUserList);
//
//        //筛去屏蔽用户
//        List<UserVo> shieldUserList = userService.shieldUserList(userVo);
//        req.setShieldUserList(shieldUserList);

        Page<FollowPageResp> page = baseMapper.followerPageBySelf(new Page<>(req.getPageNo(), req.getPageSize()), new UserVo(req.getUserType(),req.getUserId()),userVo,req);

        if (!page.getRecords().isEmpty()){
            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getUserType(), resp.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

            page.getRecords().stream().forEach(resp ->{
                resp.setUserInfo(userMap.get(new UserVo(resp.getUserType(), resp.getUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public ResponseData fansPageBySelf(FollowerPageByOther req, UserVo userVo) {

        //筛去拉黑与被拉黑用户
//        List<UserVo> blockUserList = userService.blockUserList(userVo);
//        req.setBlockUserList(blockUserList);
//
//        //筛去屏蔽用户
//        List<UserVo> shieldUserList = userService.shieldUserList(userVo);
//        req.setShieldUserList(shieldUserList);

        Page<FollowPageResp> page = baseMapper.fansPageBySelf(new Page<>(req.getPageNo(), req.getPageSize()), userVo,req);
        if (!page.getRecords().isEmpty()){
            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getUserType(), resp.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

            page.getRecords().stream().forEach(resp ->{
                resp.setUserInfo(userMap.get(new UserVo(resp.getUserType(), resp.getUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public ResponseData fansPageByOther(FollowerPageByOther req, UserVo userVo) {

        //筛去拉黑与被拉黑用户
//        List<UserVo> blockUserList = userService.blockUserList(userVo);
//        req.setBlockUserList(blockUserList);
//
//        //筛去屏蔽用户
//        List<UserVo> shieldUserList = userService.shieldUserList(userVo);
//        req.setShieldUserList(shieldUserList);

        Page<FollowPageResp> page = baseMapper.fansPageBySelf(new Page<>(req.getPageNo(), req.getPageSize()), new UserVo(req.getUserType(),req.getUserId()),req);

        if (!page.getRecords().isEmpty()){
            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getUserType(), resp.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

            page.getRecords().stream().forEach(resp ->{
                resp.setUserInfo(userMap.get(new UserVo(resp.getUserType(), resp.getUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public ResponseData<PageResult<FollowPageResp>> notFollowerPageBySelf(FollowerPageByOther req, UserVo userVo) {

        //筛去拉黑与被拉黑用户
        List<UserVo> blockUserList = userService.blockUserList(userVo);
        req.setBlockUserList(blockUserList);

        //筛去屏蔽用户
        List<UserVo> shieldUserList = userService.shieldUserList(userVo);
        req.setShieldUserList(shieldUserList);

        Page<FollowPageResp> page = baseMapper.notFollowerPageBySelf(new Page<>(req.getPageNo(), req.getPageSize()), userVo,userVo,req);

        if (!page.getRecords().isEmpty()){
            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getUserType(), resp.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

            page.getRecords().stream().forEach(resp ->{
                resp.setUserInfo(userMap.get(new UserVo(resp.getUserType(), resp.getUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }
}
