package cn.reghao.tnb.search.app.comment.controller;

import cn.reghao.jutil.jdk.web.db.PageList;
import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.search.app.comment.model.dto.ArticlePublishSbt;
import cn.reghao.tnb.search.app.comment.model.po.ArticlePost;
import cn.reghao.tnb.search.app.comment.model.vo.AnswerCard;
import cn.reghao.tnb.search.app.comment.model.vo.ArticleHeader;
import cn.reghao.tnb.search.app.comment.service.ArticlePostService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author reghao
 * @date 2023-10-13 09:24:04
 */
@Tag(name = "文章接口")
@RestController
@RequestMapping("/api/search1/article")
public class ArticleController {
    private final ArticlePostService articleService;

    public ArticleController(ArticlePostService articleService) {
        this.articleService = articleService;
    }

    @Operation(summary = "获取文章列表")
    @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getArticles(@RequestParam("page") int page) {
        long userId = UserContext.getUserId();
        PageList<ArticleHeader> pageList = articleService.getArticleHeaders(userId, page);
        return WebResult.success(pageList);
    }

    @Operation(summary = "获取用户文章列表")
    @GetMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getUserArticles(@RequestParam("userId") long userId, @RequestParam("page") int page) {
        PageList<AnswerCard> pageList = articleService.getAnswerCards(userId, page);
        return WebResult.success(pageList);
    }

    @Operation(summary = "获取文章")
    @GetMapping(value = "/{articleId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getArticleInfo(@PathVariable("articleId") String articleId) {
        ArticlePost articlePost = articleService.getArticleInfo(articleId);
        String content = articlePost.getContent();
        content = content.replace("<noscript>", "").replace("</noscript>", "");
        articlePost.setContent(content);
        return WebResult.success(articlePost);
    }

    @Operation(summary = "添加文章贴")
    @PostMapping("/put")
    public String submitArticlePost(@RequestBody @Validated ArticlePublishSbt articlePublishSbt) {
        String content = articlePublishSbt.getContent();
        content = content.replace("<noscript>", "").replace("</noscript>", "");
        articlePublishSbt.setContent(content);

        articleService.submitArticle1(articlePublishSbt);
        return WebResult.success();
    }
}
