const express = require('express');
const router = express.Router();
const {Article} = require('../../models')
const {Op} = require('sequelize')

/* 
    查询文章列表
    GET /admin/articles
 */
router.get('/', async function(req, res, next) {
    try {
        const query = req.query
        
        //当前是第几页,如果不传,那就是第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1

        //每页显示多少条数据,如果不传,那就显示10条
        const pageSize = Math.abs(Number(query.pageSize)) || 10

        //计算 offset
        const offset = (currentPage - 1) * pageSize

        const condition = {
            order:[['id','DESC']],
            limit:pageSize,
            offset
        }

        if(query.title){
            condition.where = {
                title:{
                    [Op.like]:`%${query.title}%`
                }
            }
        }

        const {count ,rows} = await Article.findAndCountAll(condition)

        res.json({
            status:true,
            message:'成功',
            data:{
                articles:rows,
                pagination:{
                    total:count,
                    currentPage,
                    pageSize
                }
            }
        });
    }catch(error){
        res.status(500).json({
            status:false,
            message:'失败',
            errors:[error.message]
        });
    }
});

/* 
    查询文章详情
    GET /admin/articles/:id
 */
router.get('/:id', async function(req, res, next) {
    try {
        //获取文章id
        const {id} = req.params

        //查询文章
        const article = await Article.findByPk(id)

        if(article){
            res.json({
                status:true,
                message:'成功',
                data:article
            });
        }else{
            res.status(404).json({
                status:false,
                message:'文章未找到',
            });
        }
    }catch(error){
        res.status(500).json({
            status:false,
            message:'失败',
            errors:[error.message]
        });
    }
});

/* 
    创建文章
    POST /admin/articles/
 */
router.post('/', async function(req, res, next) {
    try {
        //白名单过滤
        const body = filterBody(req)

        const article = await Article.create(body)
        res.status(201).json({
            status:true,
            message:'成功',
            data:article
        }); 
    }catch(error){
        if(error.name === 'SequelizeValidationError'){
            const errors = error.errors.map(e =>e.message)

            res.status(400).json({ 
                status:false,
                message:'请求参数错误',
                errors
            });
        }else{
            res.status(500).json({ 
                status:false,
                message:'失败',
                errors:[error.message]
            });
        }
        
    }
});

/* 
    删除文章
    GET /admin/articles/:id
 */
router.delete('/:id', async function(req, res, next) {
    try {
        //获取文章id
        const {id} = req.params

        //查询文章
        const article = await Article.findByPk(id)

        if(article){
            await article.destroy()

            res.json({
                status:true,
                message:'成功',
            });
        }else{
            res.status(404).json({
                status:false,
                message:'文章未找到',
            });
        }
    }catch(error){
        res.status(500).json({
            status:false,
            message:'失败',
            errors:[error.message]
        });
    }
});

/* 
    更新文章
    GET /admin/articles/:id
 */
router.put('/:id', async function(req, res, next) {
    try {
        //获取文章id
        const {id} = req.params

        //查询文章
        const article = await Article.findByPk(id)

        //白名单过滤
        const body = filterBody(req)

        if(article){
            await article.update(body)
            
            res.json({
                status:true,
                message:'成功',
                data:article
            });
        }else{
            res.status(404).json({
                status:false,
                message:'文章未找到',
            });
        }
    }catch(error){
        res.status(500).json({
            status:false,
            message:'失败',
            errors:[error.message]
        });
    }
});

function filterBody(req){
    return {
        title:req.body.title,
        content:req.body.content,
        type:req.body.type,
        img:req.body.img,
        date:req.body.date
    }
}

module.exports = router;