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

class GetSendCountRequestList extends API {
    constructor() {
        super()
        this.setPath("/Admin/Goods/SendCountRequest/List")
        this.setMethod("GET")
    }

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

        if ([uuid, session, pagesize, current].some(value => value === "" || value === null || value === undefined))
            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })

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

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

        if (!await AccessControl.canAccess(uuid, ['page.admin.goods.sendCountRequestList']))
            return res.json({ ...BaseStdResponse.PERMISSION_DENIED })

        const statusList = ["pending", "approved", "rejected"]
        if (status && !statusList.includes(status))
            return res.json({ ...BaseStdResponse.ERR, msg: "状态参数错误" })

        const offset = (Number(current) - 1) * Number(pagesize)

        let sql = `
            SELECT
                r.id,
                r.sender_uuid,
                su.username AS sender_username,
                r.receiver_user_id,
                ru.username AS receiver_username,
                r.count,
                r.status,
                r.created_at,
                r.reviewed_at,
                r.reviewer_uuid,
                rv.username AS reviewer_username,
                r.reject_reason
            FROM
                lepao_send_count_request r
            LEFT JOIN users su ON su.uuid = r.sender_uuid
            LEFT JOIN users ru ON ru.id = r.receiver_user_id
            LEFT JOIN users rv ON rv.uuid = r.reviewer_uuid
            WHERE 1 = 1
        `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM lepao_send_count_request r
            WHERE 1 = 1
        `

        const params = []
        const countParams = []

        if (status) {
            sql += ` AND r.status = ?`
            countSql += ` AND r.status = ?`
            params.push(status)
            countParams.push(status)
        }

        sql += `
            ORDER BY r.id DESC
            LIMIT ? OFFSET ?
        `
        params.push(String(pagesize), String(offset))

        const rows = await db.query(sql, params)
        const countRows = await db.query(countSql, countParams)

        if (!rows || !countRows)
            return res.json({ ...BaseStdResponse.MISSING_FILE, msg: "获取赠送审核列表失败！" })

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

module.exports.GetSendCountRequestList = GetSendCountRequestList
