package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.PageResult;
import com.zhentao.entity.CommentLikes;
import com.zhentao.entity.DynamicComments;
import com.zhentao.mapper.CommentLikesMapper;
import com.zhentao.mapper.DynamicCommentsMapper;
import com.zhentao.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private DynamicCommentsMapper commentsMapper;
    @Autowired
    private CommentLikesMapper commentLikesMapper;

    private static final Set<String> SENSITIVE = new HashSet<>(Arrays.asList("傻", "坏词", "违规"));

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addComment(Integer userId, Integer dynamicId, String content, String[] imageUrls, Integer parentCommentId) {
        // 简单敏感词过滤
        String filtered = filterContent(content);
        DynamicComments c = new DynamicComments();
        c.setUserId(userId);
        c.setDynamicId(dynamicId);
        c.setParentCommentId(parentCommentId == null ? 0 : parentCommentId);
        c.setContent(filtered);
        if (imageUrls != null && imageUrls.length > 0) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                c.setImageUrls(mapper.writeValueAsString(imageUrls));
            } catch (JsonProcessingException ignore) {
                // 忽略序列化异常
            }
        }
        c.setAuditStatus(1); // 直接通过，或改为待审核
        c.setStatus(1);
        c.setCreatedAt(LocalDateTime.now());
        commentsMapper.insert(c);

        // 如果是回复，给父评论回复数+1
        if (c.getParentCommentId() != null && c.getParentCommentId() > 0) {
            commentsMapper.update(null,
                    new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<DynamicComments>()
                            .eq("comment_id", c.getParentCommentId())
                            .setSql("reply_count = reply_count + 1"));
        }
    }

    @Override
    public PageResult<DynamicComments> listComments(Integer dynamicId, Integer pageNum, Integer pageSize) {
        Page<DynamicComments> page = new Page<>(pageNum, pageSize);
        Page<DynamicComments> pg = commentsMapper.selectPage(page, new QueryWrapper<DynamicComments>()
                .eq("dynamic_id", dynamicId)
                .eq("status", 1)
                .orderByDesc("created_at"));
        return new PageResult<>(pg.getRecords(), pg.getTotal(), pg.getCurrent(), pg.getSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void likeComment(Integer userId, Integer commentId) {
        CommentLikes cl = new CommentLikes();
        cl.setUserId(userId);
        cl.setCommentId(commentId);
        cl.setCreatedAt(LocalDateTime.now());
        try {
            commentLikesMapper.insert(cl);
            commentsMapper.update(null,
                    new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<DynamicComments>()
                            .eq("comment_id", commentId)
                            .setSql("like_count = like_count + 1"));
        } catch (DuplicateKeyException ignore) {
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlikeComment(Integer userId, Integer commentId) {
        commentLikesMapper.delete(new QueryWrapper<CommentLikes>()
                .eq("user_id", userId)
                .eq("comment_id", commentId));
        commentsMapper.update(null,
                new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<DynamicComments>()
                        .eq("comment_id", commentId)
                        .setSql("like_count = CASE WHEN like_count>0 THEN like_count-1 ELSE 0 END"));
    }

    private String filterContent(String content) {
        if (content == null) return "";
        String result = content;
        for (String w : SENSITIVE) {
            result = result.replaceAll(w, "*");
        }
        return result;
    }
}


