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

// 获取商品列表
class GetGoodsList extends API {
    constructor() {
        super();
        this.setPath('/Admin/Goods/List');
        this.setMethod('get');
    }

    async onRequest(req, res) {
        let { uuid, session, pagesize, current, keyword } = 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 || isNaN(current) || current <= 0) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '参数错误'
            })
        }

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

        // 检查 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("product"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        let sql = `
            SELECT
                a.id,
                a.name,
                a.state,
                a.price,
                a.num,
                a.ic_count,
                a.lepao_count,
                a.views,
                a.create_time,
                a.update_time,
                a.limit,
                u1.username AS create_user,
                u2.username AS update_user
            FROM
                goods a
            LEFT JOIN
                users u1 ON a.create_user = u1.uuid
            LEFT JOIN
                users u2 ON a.update_user = u2.uuid
            WHERE 1=1
        `

        let countSql = `
            SELECT COUNT(*) AS total
            FROM goods a
            WHERE 1 = 1
        `

        let params = []
        let countParams = []

        if (keyword) {
            sql += ` AND a.name LIKE ?`
            countSql += ` AND a.name LIKE ?`
            params.push(`%${keyword}%`)
            countParams.push(`%${keyword}%`)
        }

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

        let rows = await db.query(sql, params);
        let countResult = await db.query(countSql, countParams)

        if (!rows || !countResult)
            return res.json({
                ...BaseStdResponse.MISSING_FILE,
                msg: '获取产品失败！'
            })

        let total = countResult[0].total
        const totalPages = Math.ceil(total / pagesize)

        res.json({
            ...BaseStdResponse.OK,
            data: rows,
            pagination: {
                current: current,
                pagesize: pagesize,
                total: total,
                totalPages: totalPages
            }
        })
    }
}

module.exports.GetGoodsList = GetGoodsList;