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

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

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

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

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

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

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

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

        pagesize = parseInt(pagesize, 10)
        offset = parseInt(offset, 10)

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

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

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

            // 获取总记录数
            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;
