package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.PageResult;
import com.emotion.dto.request.comment.CommentCreateRequest;
import com.emotion.dto.request.comment.CommentUpdateRequest;
import com.emotion.dto.request.comment.CommentPageRequest;
import com.emotion.dto.response.comment.CommentResponse;
import com.emotion.entity.Comment;
import com.emotion.mapper.CommentMapper;
import com.emotion.service.CommentService;
import com.emotion.util.SnowflakeIdGenerator;
import com.emotion.util.UserContextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-24
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public PageResult<CommentResponse> getPage(CommentPageRequest request) {
        Page<Comment> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();

        // 根据请求参数构建查询条件
        if (StringUtils.hasText(request.getPostId())) {
            wrapper.eq(Comment::getPostId, request.getPostId());
        }

        if (StringUtils.hasText(request.getUserId())) {
            wrapper.eq(Comment::getUserId, request.getUserId());
        }

        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.like(Comment::getContent, request.getKeyword());
        }

        wrapper.eq(Comment::getIsDeleted, 0).orderByDesc(Comment::getCreateTime);
        page = this.page(page, wrapper);

        return convertPageToPageResult(page);
    }

    @Override
    public CommentResponse getById(String id) {
        Comment comment = this.getBaseMapper().selectById(id);
        if (comment == null) {
            return null;
        }
        return convertToResponse(comment);
    }

    @Override
    public CommentResponse create(CommentCreateRequest request) {
        Comment comment = new Comment();
        comment.setId(snowflakeIdGenerator.nextIdAsString()); // 使用雪花算法生成ID
        comment.setPostId(request.getPostId());

        // 从上下文中获取当前用户ID
        String currentUserId = UserContextUtils.getCurrentUserId();
        if (currentUserId != null) {
            comment.setUserId(currentUserId);
        } else if (request.getUserId() != null) {
            // 如果上下文中没有用户ID，则使用请求中的用户ID（向后兼容）
            comment.setUserId(request.getUserId());
        } else {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        comment.setContent(request.getContent());
        comment.setReplyToId(request.getReplyToId());
        comment.setLikes(0);

        this.save(comment);
        return convertToResponse(comment);
    }

    @Override
    public CommentResponse update(CommentUpdateRequest request) {
        Comment comment = this.getBaseMapper().selectById(request.getId());
        if (comment == null) {
            return null;
        }

        // 只更新非空字段
        if (StringUtils.hasText(request.getContent())) {
            comment.setContent(request.getContent());
        }

        this.updateById(comment);
        return convertToResponse(comment);
    }

    @Override
    public boolean delete(String id) {
        Comment comment = this.getBaseMapper().selectById(id);
        if (comment == null) {
            return false;
        }

        // 使用 MyBatis-Plus 的 removeById 方法，自动处理逻辑删除
        return this.removeById(id);
    }

    /**
     * 转换为响应对象
     */
    private CommentResponse convertToResponse(Comment comment) {
        CommentResponse response = new CommentResponse();
        BeanUtils.copyProperties(comment, response);
        response.setId(comment.getId());
        if (comment.getCreateTime() != null) {
            response.setCreateTime(comment.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (comment.getUpdateTime() != null) {
            response.setUpdateTime(comment.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }

    /**
     * 转换分页对象为PageResult对象
     */
    private PageResult<CommentResponse> convertPageToPageResult(Page<Comment> page) {
        PageResult<CommentResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());
        pageResult.setRecords(page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList()));
        return pageResult;
    }
}