package com.luojia_channel.modules.post.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luojia_channel.common.domain.page.PageResponse;
import com.luojia_channel.common.exception.PostException;
import com.luojia_channel.common.utils.PageUtil;
import com.luojia_channel.modules.post.dto.req.CommentPageQueryDTO;
import com.luojia_channel.modules.post.dto.resp.CommentInfoDTO;
import com.luojia_channel.modules.post.dto.resp.PostBasicInfoDTO;
import com.luojia_channel.modules.post.entity.Comment;
import com.luojia_channel.modules.post.entity.Post;
import com.luojia_channel.modules.post.mapper.CommentMapper;
import com.luojia_channel.modules.post.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private CommentMapper commentMapper;

    @Override
    public void saveComment(Comment comment) {
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        commentMapper.insert(comment);
    }

    @Override
    public void updateComment(Comment comment, Long userId) {
        validatePostOwnership(comment.getId(), userId);
        comment.setUpdateTime(LocalDateTime.now());
        if(!updateById(comment)){
            throw new PostException("更新帖子失败");
        }
    }

    @Override
    public void deleteComment(Long id, Long userId) {
        validatePostOwnership(id, userId);
        commentMapper.deleteById(id);
    }

    @Override
    public PageResponse<CommentInfoDTO> getCommentsByPostId(CommentPageQueryDTO commentPageQueryDTO) {
        LambdaQueryWrapper<Comment> queryWrapper = Wrappers.lambdaQuery(Comment.class)
                .eq(Comment::getPostId, commentPageQueryDTO.getPostId())
                .orderByDesc(Comment::getCreateTime);
        IPage<Comment> commentPage = commentMapper.selectPage(PageUtil.convert(commentPageQueryDTO), queryWrapper);
        return PageUtil.convert(commentPage, CommentInfoDTO.class);
    }

    @Override
    public List<CommentInfoDTO> getNestedCommentsByPostId(Long postId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getPostId, postId)
                .orderByAsc(Comment::getCreateTime);

        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return buildNestedComments(comments);
    }

    private void validatePostOwnership(Long commentId, Long userId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new PostException("评论不存在");
        }
        if (!userId.equals(comment.getUserId())) {
            throw new PostException("你无权操作他人的评论");
        }
    }

    private List<CommentInfoDTO> convertToDTO(List<Comment> comments) {
        List<CommentInfoDTO> dtos = new ArrayList<>();
        for (Comment comment : comments) {
            CommentInfoDTO dto = new CommentInfoDTO();
            BeanUtils.copyProperties(comment, dto);
            dtos.add(dto);
        }
        return dtos;
    }

    private List<CommentInfoDTO> buildNestedComments(List<Comment> comments) {
        Map<Long, CommentInfoDTO> map = new HashMap<>();
        List<CommentInfoDTO> rootComments = new ArrayList<>();

        for (Comment comment : comments) {
            CommentInfoDTO dto = new CommentInfoDTO();
            BeanUtils.copyProperties(comment, dto);

            map.put(comment.getId(), dto);

            if (comment.getParentCommentId() == null) {
                rootComments.add(dto);
            } else {
                CommentInfoDTO parentDto = map.get(comment.getParentCommentId());
                if (parentDto != null && parentDto.getCommentInfoDTOList() == null) {
                    parentDto.setCommentInfoDTOList(new ArrayList<>());
                }
                if (parentDto != null) {
                    parentDto.getCommentInfoDTOList().add(dto);
                }
            }
        }

        return rootComments;
    }
}
