package top.lejings.demo.service.impl;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lejings.demo.mapper.CommentsMapper;
import top.lejings.demo.pojo.Comments;
import top.lejings.demo.service.CommentsService;
import top.lejings.demo.utils.JwtUtils;

import java.util.List;

@Service
public class CommentsServiceImpl implements CommentsService {
    @Autowired
    CommentsMapper commentsMapper;
    @Override
    public List<Comments> getComment(Integer postId) {
        return commentsMapper.getComment(postId);
    }

    @Override
    public void addComment(Comments comments) {
        String token = comments.getToken();
        if (token != null) {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = (Integer) claims.get("user_id");
            comments.setUser_id(userId);
            commentsMapper.addComment(comments);
        } else {
            throw new IllegalArgumentException("Token cannot be null");
        }
    }

    @Override
    public List<Comments> search(String content, String username) {
        if (content == null || content.equals("")) {
            // by作者名
            return commentsMapper.searchByUser(username);
        }
        else{
//            by 内容
            return commentsMapper.searchByContent(content);
        }
    }

    @Override
    public void delete(Comments comments) {
        //解析jwt令牌，获得user_id
        Claims claims = JwtUtils.parseJWT(comments.getToken());
        Integer userId = (Integer) claims.get("user_id");
        comments.setUser_id(userId);
        commentsMapper.delete(comments);
    }
}
