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
            });
        }

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

        const 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);
        state = parseInt(state, 10);

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

        const offset = (current - 1) * pagesize;
        const filterAllTypes = type === 'all';

        let sql = `
            SELECT 
                a.id,
                a.slug,
                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.state = ?
        `;
        const params = [state];

        if (!filterAllTypes) {
            sql += ' AND a.type = ?';
            params.push(type);
        }

        sql += ' ORDER BY a.id DESC LIMIT ? OFFSET ?';
        params.push(String(pagesize), String(offset));

        let countSql = 'SELECT COUNT(*) AS total FROM article a WHERE a.state = ?';
        const countParams = [state];
        if (!filterAllTypes) {
            countSql += ' AND a.type = ?';
            countParams.push(type);
        }

        try {
            const articles = await db.query(sql, params);
            const countResult = await db.query(countSql, countParams);
            const total = countResult[0].total;
            const totalPages = Math.ceil(total / pagesize);

            res.json({
                ...BaseStdResponse.OK,
                data: articles || [],
                pagination: {
                    current,
                    pagesize,
                    total,
                    totalPages
                }
            });
        } catch (err) {
            this.logger.error(`获取文章列表失败！${err.stack}`);
            res.json({
                ...BaseStdResponse.ERR,
                msg: '获取文章列表失败！',
                endpoint: 153127
            });
        }
    }
}

module.exports.GetArticleList = GetArticleList;
