package com.mcwl.communityCenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.communityCenter.domain.*;
import com.mcwl.communityCenter.domain.dto.CommentDelRes;
import com.mcwl.communityCenter.domain.dto.CommentDetailRes;
import com.mcwl.communityCenter.domain.dto.CommentLikeDetailRes;
import com.mcwl.communityCenter.domain.dto.CommentRes;
import com.mcwl.communityCenter.domain.vo.CommentVo;
import com.mcwl.communityCenter.mapper.CommunityUserMapper;
import com.mcwl.communityCenter.mapper.PublishCommentLikeMapper;
import com.mcwl.communityCenter.mapper.PublishCommentMapper;
import com.mcwl.communityCenter.mapper.PublishMapper;
import com.mcwl.communityCenter.service.PublishCommentLikeService;
import com.mcwl.communityCenter.service.PublishCommentService;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 评论区业务层
 *
 * @Author：ChenYan
 * @Project：mcwl-ai
 * @Package：com.mcwl.communityCenter.service.impl
 * @Filename：PublishCommissionServiceImpl
 * @Description TODO
 * @Date：2025/1/17 14:28
 */
@Service
@RequiredArgsConstructor
public class PublishCommentServiceImpl extends ServiceImpl<PublishCommentMapper, PublishComment> implements PublishCommentService {

    private final PublishCommentMapper publishCommentMapper;

    private final ISysUserService sysUserService;

    private final PublishMapper publishMapper;

    private final CommunityUserMapper communityUserMapper;

    private final PublishCommentLikeService publishCommentLikeService;

    @Override
    public R<List<CommentVo>> getComment(CommentDetailRes commentDetailRes) {
        Long tenantId = commentDetailRes.getTenantId();
        Long communityId = commentDetailRes.getCommunityId();
        Long publishId = commentDetailRes.getPublishId();

        // 查询评论
        List<PublishComment> publishComment = publishCommentMapper
                .selectByTenantIdAndCommunityIdAndPublishIdList(tenantId, communityId, publishId);

        List<CommentVo> commentVoList = BeanUtil.copyToList(publishComment, CommentVo.class);

        Map<Long, CommentVo> commentVoMap = commentVoList.stream()
                .collect(Collectors.toMap(CommentVo::getId, Function.identity()));

        // 收集所有需要查询的用户ID（包括回复对象ID）
        Set<Long> userIds = new HashSet<>();
        for (CommentVo commentVo : commentVoList) {
            userIds.add(commentVo.getUserId());
        }
        // 批量查询用户信息并建立缓存映射
        Map<Long, SysUser> userMap = sysUserService.selectUserByIds(userIds).stream()
                .collect(Collectors.toMap(SysUser::getUserId, Function.identity()));

        for (CommentVo commentVo : commentVoList) {
            Long userId = commentVo.getUserId();
            SysUser sysUser = userMap.get(userId);
            commentVo.setUserName(sysUser.getNickName());
            commentVo.setUserAvatar(sysUser.getAvatar());

            if (commentVo.getParentId() != null) {
                Long parentId = commentVo.getParentId();
                CommentVo parentCommentVo = commentVoMap.get(parentId);
                if (Objects.nonNull(parentCommentVo)) {
                    SysUser su = userMap.get(parentCommentVo.getUserId());
                    commentVo.setReplyUserName(su.getNickName());
                }
            }

            CommentLikeDetailRes commentLikeDetailRes = new CommentLikeDetailRes();
            commentLikeDetailRes.setTenantId(tenantId);
            commentLikeDetailRes.setCommunityId(communityId);
            commentLikeDetailRes.setPublishId(publishId);
            commentLikeDetailRes.setPublishCommentId(commentVo.getId());
            PublishCommentLike publishCommentLike = publishCommentLikeService.publishCommentLike(commentLikeDetailRes, SecurityUtils.getUserId());
            if (Objects.isNull(publishCommentLike)) {
                commentVo.setIsLike(0);
            } else {
                String delFlag = publishCommentLike.getDelFlag();
                if (Objects.equals(delFlag, "0")) {
                    commentVo.setIsLike(1);
                } else {
                    commentVo.setIsLike(0);
                }
            }
        }

        return R.ok(commentVoList);
    }

    @Override
    public R<Object> addComment(CommentRes commentRes) {
        Long tenantId = commentRes.getTenantId();
        Long communityId = commentRes.getCommunityId();
        Long publishId = commentRes.getPublishId();

        CommunityUser communityUser = communityUserMapper.selectCommunityUser(tenantId, communityId, SecurityUtils.getUserId());

        if (Objects.isNull(communityUser)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "评论失败，您不是该社区成员");
        }

        if ("1".equals(communityUser.getIsBlack())) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "评论失败，您已被拉黑");
        }

        Publish publish = publishMapper.selectByIdAndTenantIdAndCommunityId(publishId, tenantId, communityId);
        if (Objects.isNull(publish)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "评论失败，该内容不存在");
        }

        PublishComment publishComment = new PublishComment();
        BeanUtil.copyProperties(commentRes, publishComment);
//        publishComment.setPublishId(publishId);
        publishComment.setUserId(SecurityUtils.getUserId());

        publishCommentMapper.insert(publishComment);

        return R.ok(null, "评论成功");
    }

    @Override
    public R<Object> removeCommentById(CommentDelRes commentDelRes) {
        Long id = commentDelRes.getId();
        Long tenantId = commentDelRes.getTenantId();
        Long communityId = commentDelRes.getCommunityId();
        Long publishId = commentDelRes.getPublishId();

        PublishComment publishComment = publishCommentMapper.selectByIdAndTenantIdAndCommunityIdAndPublishId(id, tenantId, communityId, publishId);

        if (Objects.isNull(publishComment)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "删除失败，该评论不存在");
        }

        publishCommentMapper.deleteByIdAndTenantIdAndCommunityIdAndOperatorId(id, tenantId, communityId, publishId);

        return R.ok(null, "删除成功");
    }

}
