package top.lejings.demo.service.impl;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lejings.demo.mapper.PostsMapper;
import top.lejings.demo.pojo.Posts;
import top.lejings.demo.service.PostsService;
import top.lejings.demo.utils.JwtUtils;

import java.util.List;
@Slf4j
@Service
public class PostsServiceImpl implements PostsService {

    @Autowired
    private PostsMapper postsMapper;

    @Override
    public List<Posts> postsOverview(String by,String token) {
        if(by.equals("byLike"))by="p.priority";
        else by="p.updated_at";
        log.info("根据{}查询",by);
        if(token == null || token.equals("")){
            return postsMapper.postsOverview(by);
        }
        else{
            //解析令牌，返回user_id
            Claims claims = JwtUtils.parseJWT(token);
            Integer user_id = claims.get("user_id", Integer.class); // 假设 user_id 是字符串类型
            log.info("id为{}",user_id);
            return postsMapper.postsOverviewAndId(by,user_id);
        }
    }

    @Override
    public Posts postsEssay(Integer post_id) {return postsMapper.postsEssay(post_id);}

    //新建文章，在这里解析token，得到写作者的id
    @Override
    public void postsNew(Posts posts) {
        // 解析 token 获取 user_id
        String token = posts.getToken();
        if (token != null) {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = (Integer) claims.get("user_id");
            posts.setUser_id(userId);
        } else {
            throw new IllegalArgumentException("Token cannot be null");
        }


        postsMapper.postsNew(posts);
    }

    @Override
    public void deletePost(Integer postId) {
        postsMapper.deletePost(postId);
    }

    @Override
    public void postsUpdate(Posts posts) {
        //本来还有解析token，判断逻辑。但是懒得写了
        postsMapper.postsUpdate(posts);
    }

    @Override
    public List<Posts> search(String title, String username) {
        if (title == null || title.equals("")) {
            // by作者名
            return postsMapper.searchByTitle(username);
        }
        else{
//            by 标题
            return postsMapper.searchByUser(title);
        }
    }
}
