const API = require("../../../lib/API");
const db = require("../../../plugin/DataBase/db");
const AccessControl = require("../../../lib/AccessControl");
const { BaseStdResponse } = require("../../../BaseStdResponse");

class GetArticleList extends API {
    constructor() {
        super();

        this.setPath('/Admin/Article/List')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { uuid, session, pagesize, current, type, state } = req.query

        if ([uuid, session, pagesize, current, type, state].some(value => value === '' || value === null || value === undefined)) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            })
        }

        // 检查 session
        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        // 检查权限
        let permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("article"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        // 转换参数类型
        pagesize = parseInt(pagesize, 10)
        current = parseInt(current, 10)

        // 校验分页参数
        if (isNaN(pagesize) || pagesize <= 0) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

        if (isNaN(current) || current <= 0) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

        // 计算分页的 offset
        const offset = (current - 1) * pagesize

        let sql = `
            SELECT 
                a.id,
                a.title,
                a.cover,
                a.describe,
                a.type,
                a.time,
                a.views,
                a.state,
                u.username AS author
            FROM 
                article a
            LEFT JOIN 
                users u 
            ON 
                a.author = u.uuid
            WHERE 
                a.type = ?
                AND a.state = ?
            ORDER BY 
                a.id DESC
        `

        // 查询文章总数，方便返回总页数
        let countSql = `
            SELECT COUNT(*) AS total
            FROM article a
            WHERE a.type = ?;
        `

        try {
            // 获取文章列表
            let articles = await db.query(sql, [type, state])

            // 获取总记录数
            let countResult = await db.query(countSql, [type])
            let total = countResult[0].total;

            // 计算总页数
            const totalPages = Math.ceil(total / pagesize)

            // 返回结果
            res.json({
                ...BaseStdResponse.OK,
                data: articles || [],
                pagination: {
                    current: current,
                    pagesize: pagesize,
                    total: total,
                    totalPages: totalPages
                }
            })

        } catch (err) {
            this.logger.error(`获取文章列表失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: '获取文章列表失败！',
                endpoint: 153127
            })
        }
    }
}

module.exports.GetArticleList = GetArticleList;
