package top.lejings.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.lejings.demo.pojo.Posts;
import top.lejings.demo.pojo.Result;
import top.lejings.demo.service.PostsService;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/post")
public class PostsController {
    @Autowired
    private PostsService postsService;

    //概览 Overview
    @GetMapping("/overview")
    public Result PostsOverview(@RequestParam(defaultValue = "byLike") String by,@RequestHeader String token) {
        log.info("查询文章所有概览");
        List<Posts> postsOverviewList = postsService.postsOverview(by,token);
        System.out.println(postsOverviewList);
        // 遍历列表，处理 username 为空或 null 的情况
        for (Posts post : postsOverviewList) {
            if (post.getUsername() == null || post.getUsername().isEmpty()) {
                post.setUsername("账号已注销");
            }
        }
        return Result.success(postsOverviewList);
    }
    //具体文章，接收参数 文章id essay
    //请求url:127.0.0.1:8080/post/essay/4
    @GetMapping("/essay")
    public Result PostsEssay(Integer post_id){
        log.info("查询id为{}的文章",post_id);
        Posts posts = postsService.postsEssay(post_id);
        return Result.success(posts);
    }

    //新建文章,前端传来token,title,content。修改和创建时间由数据库完成
    @PostMapping("/new")
    @CrossOrigin(origins = "http://localhost:82")
    public Result PostsNew(@RequestBody Posts posts){
        log.info("新建文章");
        postsService.postsNew(posts);
        return Result.success();
    }

    // 删除文章,接收参数 文章id post_id
    // 请求url:127.0.0.1:8080/post/delete?post_id=4
    @DeleteMapping("/delete")
    public Result deletePost(@RequestParam Integer post_id) {
        log.info("删除id为{}的文章", post_id);
        postsService.deletePost(post_id);
        return Result.success();
    }

    //修改文章
    @PostMapping("/update")
    public Result update(@RequestBody Posts posts){
        log.info("修改文章");
        postsService.postsUpdate(posts);
        return Result.success("修改成功");
    }

    @GetMapping("/search")
    public Result search(String title,String username){
        log.info("特定条件查询");

        List<Posts> postList = postsService.search(title,username);
        // 遍历列表，处理 username 为空或 null 的情况
        for (Posts post : postList) {
            if (post.getUsername() == null || post.getUsername().isEmpty()) {
                post.setUsername("账号已注销");
            }
        }
        return Result.success(postList);
    }

}
