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

class AdminPopupList extends API {
    constructor() {
        super()
        this.setPath('/Admin/Popup/List')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        const { uuid, session, title, is_active, pagesize, current } = req.query
        if ([uuid, session, pagesize, current].some(v => v === '' || v === null || v === undefined))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        if (isNaN(pagesize) || Number(pagesize) <= 0 || isNaN(current) || Number(current) <= 0)
            return res.json({ ...BaseStdResponse.ERR, msg: '参数错误' })

        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("server"))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const offset = (Number(current) - 1) * Number(pagesize)
        const where = ['1 = 1']
        const params = []
        const countParams = []
        if (title) {
            where.push('p.title LIKE ?')
            params.push(`%${title}%`)
            countParams.push(`%${title}%`)
        }
        if (is_active !== undefined && is_active !== null && is_active !== '') {
            where.push('p.is_active = ?')
            params.push(Number(is_active) === 1 ? 1 : 0)
            countParams.push(Number(is_active) === 1 ? 1 : 0)
        }

        const whereSql = where.join(' AND ')
        const listSql = `
            SELECT
                p.id,
                p.title,
                p.content_html,
                p.priority,
                p.is_active,
                p.repeat_show,
                p.start_at,
                p.end_at,
                p.created_by,
                p.created_at,
                p.updated_at,
                (
                    SELECT COUNT(*)
                    FROM site_popup_read r
                    WHERE r.popup_id = p.id
                ) AS read_count
            FROM site_popup p
            WHERE ${whereSql}
            ORDER BY p.id DESC
            LIMIT ? OFFSET ?
        `
        const countSql = `SELECT COUNT(*) AS total FROM site_popup p WHERE ${whereSql}`
        params.push(String(pagesize), String(offset))

        const rows = await db.query(listSql, params)
        const countRows = await db.query(countSql, countParams)
        if (!rows || !countRows) return res.json({ ...BaseStdResponse.DATABASE_ERR })

        return res.json({
            ...BaseStdResponse.OK,
            data: rows,
            pagination: {
                current: Number(current),
                pagesize: Number(pagesize),
                total: countRows[0]?.total || 0
            }
        })
    }
}

module.exports.AdminPopupList = AdminPopupList
