package com.quinn.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quinn.common.Category;
import com.quinn.common.QuinnConstant;
import com.quinn.common.SourceType;
import com.quinn.pojo.*;
import com.quinn.service.CommentService;
import com.quinn.service.SourceCategoryService;
import com.quinn.service.SourceService;
import com.quinn.service.StarService;
import com.quinn.utils.QuinnUtils;
import com.quinn.vo.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author limqsh
 * @since 2022-05-03
 */
@Controller
public class SourceController extends BaseModelController {

    @Resource
    SourceService sourceService;

    @Resource
    SourceCategoryService sourceCategoryService;

    @Resource
    CommentService commentService;

    @Resource
    StarService starService;

    // 列表展示
    @GetMapping("/source")
    public String sourceList(Model model){
        QuerySource querySource = new QuerySource();
        MyPageParam myPageParam = new MyPageParam(1,10);
        List<SourceWithStar> sourceList = sourceService.listPageStar(querySource,myPageParam);
        // 结果
        model.addAttribute("sourceList",sourceList);
        model.addAttribute("pageParam",myPageParam);

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

        return "source/list";
    }

    @PostMapping("/source")
    public String blogListPage(QuerySourcePage querySource, Model model){
        int page = querySource.getPageNum();
        int limit = querySource.getLimit();
        if (querySource.getPageNum() < 1){
            page = 1;
        }
        MyPageParam myPageParam = new MyPageParam(page,limit);
        List<SourceWithStar> sourceList = sourceService.listPageStar(querySource,myPageParam);
        // 结果
        model.addAttribute("sourceList",sourceList);
        model.addAttribute("pageParam",myPageParam);

        return "source/list::s_table_refresh";
    }

    // 列表展示
    @GetMapping("/hotspot")
    public String sourceHotPot(Model model){
        Page<Source> pageParam = new Page<>(1, 21);
        QueryWrapper<Source> sourceQuery = new QueryWrapper<>();
        sourceQuery.orderByDesc("down_record");
        sourceService.page(pageParam,sourceQuery);
        // 结果
        List<Source> sourceList = pageParam.getRecords();
        if (!CollectionUtils.isEmpty(sourceList)){
            sourceList.forEach(x ->{
                x.setSourceLink(QuinnConstant.GUN);
                x.setSourceContent(QuinnConstant.GUN);
            });
        }
        model.addAttribute("sourceList",sourceList);
        return "source/hotspot";
    }


    /**
     * 查看下载资源的详情
     * @param sid
     * @param model
     * @return
     */
    @GetMapping("/source/view/{sid}")
    public String view(HttpServletRequest request, @PathVariable("sid") String sid, Model model){
        String sessionId = getSessionId(request);
        Source source = sourceService.view(sid,sessionId);
        if(source != null){
            source.setSourceLink(QuinnConstant.GUN);
        }
        model.addAttribute("source",source);

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

        List<CommentWithUser> commentList = commentService.getCommentList(sid, Category.SOURCE);
        model.addAttribute("commentList",commentList);
        return "source/view";
    }

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

    /**
     * 下载具体的文件
     * @param response
     * @param sid
     * @throws IOException
     */
    @PostMapping("/source/download/{sid}")
    public void download(HttpServletRequest request,HttpServletResponse response, @PathVariable("sid") String sid) throws IOException {
        String sessionId = getSessionId(request);
        Source source = sourceService.getOne(new QueryWrapper<Source>().eq("sid", sid));
        if (source!=null){
            if (SourceType.OSS.name().equals(source.getSourceType())){
                //通知浏览器以附件形式下载
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + source.getEnName() + QuinnConstant.LINK_SUFFIX + source.getFileType());
                sourceService.downloadSource(response,source,sessionId);
            }else {
                sourceService.downloadForBaidu(response,source,sessionId);
            }
        }
    }

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

}
