package com.ruoyi.generator.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.generator.domain.Community.CommunityArticleComment;
import com.ruoyi.generator.domain.Community.CommunityCommentLike;
import com.ruoyi.generator.domain.Community.CommunityCommentReply;
import com.ruoyi.generator.mapper.community.CommunityCommentLikeMapper;
import com.ruoyi.generator.service.ICommunityArticleCommentService;
import com.ruoyi.generator.service.ICommunityArticleService;
import com.ruoyi.generator.service.ICommunityCommentReplyService;
import com.ruoyi.generator.vo.CommunityArticleCommentVo;
import com.ruoyi.generator.vo.CommunityCommentReplyVo;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 评论接口
 *
 * @author fangzhen
 */
@Api(tags = "评论接口")
@RestController
@RequestMapping("/community/comment")
public class CommunityCommentController extends BaseController {

    @Autowired
    private ICommunityCommentReplyService communityCommentReplyService;

    @Autowired
    private ICommunityArticleCommentService communityArticleCommentService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CommunityCommentLikeMapper communityCommentLikeMapper;

    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private ICommunityArticleService communityArticleService;


    /**
     * 获取文章评论
     */
    @ApiOperation("获取文章评论")
    @GetMapping()
    @Transactional
    //@Anonymous
    public AjaxResult comment(String articleId, int currentPage, int limit) {
        if (Objects.isNull(articleId)) {
            return AjaxResult.error("参数异常!");
        }
        Page<CommunityArticleComment> page = new Page<>(currentPage, limit);
        List<CommunityArticleComment> records = communityArticleCommentService.page(page, new QueryWrapper<CommunityArticleComment>().eq("article_id", articleId).and((wrapper) -> {
            wrapper.ne("is_delete", true).or().isNull("is_delete");
        }).orderByDesc("create_time")).getRecords();

        CommunityArticleCommentVo commentVo = null;
        List<CommunityArticleCommentVo> commentVos = new ArrayList<>();
        for (CommunityArticleComment record : records) {
            commentVo = new CommunityArticleCommentVo();
            BeanUtils.copyProperties(record, commentVo);
            commentVos.add(commentVo);
        }

        Long userId = SecurityUtils.getUserId();
        for (CommunityArticleCommentVo vo : commentVos) {
            Long commentUserId = vo.getUserId();
            //获取评论的用户信息
            SysUser sysUser = sysUserMapper.selectUserById(commentUserId);
            vo.setNickName(sysUser.getNickName());
            vo.setAvatar(sysUser.getAvatar());
            //当前登录用户是否已点赞
            List<CommunityCommentLike> commentLikes = communityCommentLikeMapper.selectList(new QueryWrapper<CommunityCommentLike>().eq("comment_id", vo.getId()).eq("user_id", userId));
            vo.setCommentLike(!commentLikes.isEmpty());
            //该评论的点赞数量
            vo.setCommentLikeCount(communityCommentLikeMapper.selectList(new QueryWrapper<CommunityCommentLike>().eq("comment_id", vo.getId())).size());
            //设置首条评论
            List<CommunityCommentReply> replies = communityCommentReplyService.list(new QueryWrapper<CommunityCommentReply>().eq("comment_id", vo.getId()).and((wrapper) -> {
                wrapper.ne("is_delete", true).or().isNull("is_delete");
            }).orderByAsc("create_time"));

            CommunityCommentReplyVo replyVo = null;
            List<CommunityCommentReplyVo> replyVos = new ArrayList<>();
            for (CommunityCommentReply reply : replies) {
                replyVo = new CommunityCommentReplyVo();
                BeanUtils.copyProperties(reply, replyVo);
                replyVo.setNickName(sysUserService.selectUserById(replyVo.getUserId()).getNickName());
                replyVo.setReply(true);
                replyVos.add(replyVo);
                //设置点赞数量和当前登录用户是否已点赞
                List<CommunityCommentLike> commentLikeList = communityCommentLikeMapper.selectList(new QueryWrapper<CommunityCommentLike>()
                        .eq("reply_id", replyVo.getId()));
                replyVo.setLikeCount(commentLikeList.size());
                replyVo.setLike(commentLikeList.stream().anyMatch(item -> SecurityUtils.getUserId().equals(item.getUserId())));
                break;
            }
            vo.setFirstReply(replyVos);
            //设置还剩多少评论
            vo.setReplyCount(replies.isEmpty() ? 0 : replies.size() - 1);
            vo.setReply(false);
        }

        return AjaxResult.success(commentVos);
    }

    /**
     * 获取评论回复
     */
    @ApiOperation("获取评论回复")
    @GetMapping("/reply")
    @Transactional
    //@Anonymous
    public AjaxResult reply(String commentId, int currentPage, int limit) {
        if (Objects.isNull(commentId)) {
            return AjaxResult.error("参数异常!");
        }
        Page<CommunityCommentReply> page = new Page<>(currentPage, limit);
        List<CommunityCommentReply> replies = communityCommentReplyService.page(page, new QueryWrapper<CommunityCommentReply>().eq("comment_id", commentId).and((wrapper) -> {
            wrapper.ne("is_delete", true).or().isNull("is_delete");
        }).orderByAsc("create_time")).getRecords();
        CommunityCommentReplyVo replyVo = null;
        List<CommunityCommentReplyVo> replyVos = new ArrayList<>();
        for (final CommunityCommentReply reply : replies) {
            replyVo = new CommunityCommentReplyVo();
            SysUser sysUser = sysUserService.selectUserById(reply.getUserId());
            final Long parentReplyId = reply.getParentReplyId();
            BeanUtils.copyProperties(reply, replyVo);
            if (Objects.nonNull(parentReplyId) && !commentId.equalsIgnoreCase(Long.toString(parentReplyId))) {
                CommunityCommentReply communityCommentReply = replies.stream().filter(item -> item.getId().equals(parentReplyId)).collect(Collectors.toList()).get(0);
                SysUser sysUser1 = sysUserService.selectUserById(communityCommentReply.getUserId());
                replyVo.setParentNickName(sysUser1.getNickName());
                replyVo.setParentUserId(sysUser1.getUserId());
                replyVo.setParentAvatar(sysUser1.getAvatar());
            }
            replyVo.setNickName(sysUser.getNickName());
            replyVo.setAvatar(sysUser.getAvatar());
            replyVo.setReply(true);
            //设置点赞数量和当前登录用户是否已点赞
            List<CommunityCommentLike> commentLikes = communityCommentLikeMapper.selectList(new QueryWrapper<CommunityCommentLike>()
                    .eq("reply_id", replyVo.getId()));
            replyVo.setLikeCount(commentLikes.size());
            replyVo.setLike(commentLikes.stream().anyMatch(item -> SecurityUtils.getUserId().equals(item.getUserId())));
            replyVos.add(replyVo);
        }
        return AjaxResult.success(replyVos);
    }


    /**
     * 对文章评论进行回复
     */
    @ApiOperation("对文章评论进行回复")
    @PostMapping("/reply")
    @Transactional
    //@Anonymous
    public AjaxResult reply(@RequestBody CommunityCommentReply communityCommentReply) throws ParseException {
        if (Objects.isNull(communityCommentReply.getCommentId()) || Objects.isNull(communityCommentReply.getContent())) {
            return AjaxResult.error("参数异常!");
        }
        Long userId = SecurityUtils.getUserId();
        Boolean aBoolean = communityArticleService.checkCommentPermission(userId, communityCommentReply.getCommentId(), null);
        if (!aBoolean) {  // 当 aBoolean 为 false 时，进入这个条件
            return AjaxResult.success("您没有权限评论此文章，因为只允许关注的人评论您!");
        }
        communityCommentReply.setUserId(userId);
        communityCommentReply.setDelete(false);
        communityCommentReply.setCreateBy(userId);
        communityCommentReply.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityCommentReplyService.save(communityCommentReply);
        return AjaxResult.success(communityCommentReply);
    }

    /**
     * 删除回复
     */
    @ApiOperation("删除回复")
    @DeleteMapping("/deleteReply")
    @Transactional
    //@Anonymous
    public AjaxResult deleteReply(String replyId) {
        if (Objects.isNull(replyId)) {
            return AjaxResult.error("参数异常!");
        }

        CommunityCommentReply communityCommentReply = communityCommentReplyService.getOne(new QueryWrapper<CommunityCommentReply>().eq("id", replyId).and((wrapper) -> {
            wrapper.ne("is_delete", true).or().isNull("is_delete");
        }));
        if (Objects.isNull(communityCommentReply)) {
            return AjaxResult.error("未找到该回复!");
        }

        Long userId = SecurityUtils.getUserId();
        communityCommentReply.setDelete(true);
        communityCommentReply.setUpdateBy(userId);
        communityCommentReply.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        communityCommentReplyService.updateById(communityCommentReply);
        return AjaxResult.success("删除回复成功!");
    }
}
