package com.quinn.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quinn.common.Category;
import com.quinn.pojo.*;
import com.quinn.service.*;
import com.quinn.utils.ContentUtil;
import com.quinn.utils.CovertEmojStr;
import com.quinn.utils.QuinnUtils;
import com.quinn.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author limqsh
 * @since 2020-06-29
 */
@Controller
public class BlogController extends BaseModelController{

    private static final Logger log = LoggerFactory.getLogger(BlogController.class);

    @Autowired
    BlogCategoryService blogCategoryService;
    @Autowired
    BlogService blogService;
    @Autowired
    CommentService commentService;
    @Resource
    StarService starService;

    // 列表展示
    @GetMapping("/blog")
    public String blogList(HttpServletRequest request,Model model){
        String loginUserId = getLoginUserId(request);
        MyPageParam myPageParam = new MyPageParam(1, 10);
        List<BlogWithUser> blogList = blogService.getBlogWithUserOrderBySort(loginUserId,myPageParam);
        // 结果
        model.addAttribute("blogList",blogList);
        model.addAttribute("pageParam",myPageParam);

        List<Blog> topBlogList = blogService.getTopBlog();
        model.addAttribute("topBlogList",topBlogList);

        // 分类信息
        List<BlogCategory> categoryList = blogCategoryService.list(null);
        model.addAttribute("categoryList",categoryList);

        return "blog/list";
    }

    @PostMapping("/blog")
    public String blogListPage(HttpServletRequest request,NavReq navReq, Model model){
        String loginUserId = getLoginUserId(request);
        // 用户的论坛列表
        if (navReq.getPageNum() < 1){
            navReq.setPageNum(1);
        }
        MyPageParam myPageParam = new MyPageParam(navReq.getPageNum(),navReq.getLimit());
        List<BlogWithUser> blogList = blogService.getBlogWithUserOrderBySort(loginUserId,myPageParam);
        // 结果
        model.addAttribute("blogList",blogList);
        model.addAttribute("pageParam",myPageParam);

        List<Blog> topBlogList = blogService.getTopBlog();
        model.addAttribute("topBlogList",topBlogList);

        // 分类信息
        List<BlogCategory> categoryList = blogCategoryService.list(null);
        model.addAttribute("categoryList",categoryList);

        return "blog/list::s_table_refresh";
    }

    // 写文章
    @GetMapping("/blog/write")
    public String toWrite(Model model){
        List<BlogCategory> categoryList = blogCategoryService.list(null);
        model.addAttribute("categoryList",categoryList);
        return "blog/write";
    }

    @PostMapping("/blog/write")
    public synchronized String write(QuestionWriteForm questionWriteForm){
        // 构建问题对象
        Blog blog = new Blog();

        blog.setBid(QuinnUtils.getUuid());
        blog.setTitle(questionWriteForm.getTitle());
        blog.setContent(CovertEmojStr.coverStr(questionWriteForm.getContent()));

        String s = ContentUtil.toTextContentFromWangEdit(questionWriteForm.getContentJson());
        blog.setContentJson(CovertEmojStr.coverStr(s));

        blog.setSort(0);
        blog.setViews(0);

        blog.setAuthorId(questionWriteForm.getAuthorId());

        BlogCategory category = blogCategoryService.getById(questionWriteForm.getCategoryId());
        blog.setCategoryId(questionWriteForm.getCategoryId());
        blog.setCategoryName(category.getCategory());
        blog.setGmtCreate(QuinnUtils.getTime());
        blog.setGmtUpdate(QuinnUtils.getTime());
        // 存储对象
        blogService.save(blog);

        // 重定向到列表页面
        return "redirect:/blog";
    }

    // 阅读文章
    @GetMapping("/blog/read/{bid}")
    public String read(HttpServletRequest request, @PathVariable("bid") String bid, Model model){
        Blog blog = blogService.getOne(new QueryWrapper<Blog>().eq("bid", bid));
        String sessionId = getSessionId(request);
        blogService.addRecord(blog,sessionId);
        model.addAttribute("blog",blog);

        StarValue starValue = starService.isStar(bid, getLoginUserId(request), Category.BLOG);
        model.addAttribute("starValue",starValue);

        List<CommentWithUser> commentList = commentService.getCommentList(bid, Category.BLOG);
        model.addAttribute("commentList",commentList);
        return "blog/read";
    }

    // 收藏
    @PostMapping("/blog/star")
    public synchronized String toStar(StarReq starReq, Model model){
        StarValue starValue = starService.starTopic(starReq.getTopicId(), starReq.getUserId(), Category.BLOG);
        model.addAttribute("starValue",starValue);
        return "blog/read::star_refresh";
    }

    // 编辑问题
    @GetMapping("/blog/editor/{bid}")
    public synchronized String toEditor(HttpServletRequest request,@PathVariable("bid") String bid,Model model){
        String uid = getLoginUserId(request);
        Blog blog = blogService.getOne(new QueryWrapper<Blog>().eq("bid", bid));

        if (!blog.getAuthorId().equals(uid)){
            log.error("非法编辑{0},{1}",uid,bid);
            return "redirect:/blog";
        }

        model.addAttribute("blog",blog);

        List<BlogCategory> categoryList = blogCategoryService.list(null);
        model.addAttribute("categoryList",categoryList);

        return "blog/editor";
    }

    @PostMapping("/blog/editor")
    public String editor(Blog blog){
        Blog queryBlog = blogService.getOne(new QueryWrapper<Blog>().eq("bid", blog.getBid()));
        queryBlog.setTitle(blog.getTitle());
        queryBlog.setCategoryId(blog.getCategoryId());
        queryBlog.setContent(CovertEmojStr.coverStr(blog.getContent()));
        String s = ContentUtil.toTextContentFromWangEdit(CovertEmojStr.coverStr(blog.getContentJson()));
        queryBlog.setContentJson(s);
        queryBlog.setGmtUpdate(QuinnUtils.getTime());

        blogService.updateById(queryBlog);

        return "redirect:/blog/read/"+blog.getBid();
    }

    // 删除问题
    @GetMapping("/blog/delete/{bid}")
    public String delete(HttpServletRequest request,
                         @PathVariable("bid") String bid){
        String uid = getLoginUserId(request);
        Blog blog = blogService.getOne(new QueryWrapper<Blog>().eq("bid", bid));

        if (!blog.getAuthorId().equals(uid)){
            log.error("禁止非法删除{0},{1}",uid,bid);
            return "redirect:/blog";
        }

        blogService.removeById(blog);
        // 重定向到列表页面
        return "redirect:/blog";
    }

    // 评论
    @PostMapping("/blog/comment/{bid}")
    public String comment(@PathVariable("bid") String bid, Comment comment){
        // 存储评论
        comment.setCommentId(QuinnUtils.getUuid());
        comment.setTopicCategory(Category.BLOG.name());
        comment.setGmtCreate(QuinnUtils.getTime());
        commentService.save(comment);
        // 重定向到列表页面
        return "redirect:/blog/read/"+bid;
    }

}

