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

// 获取产品
class GetGoods extends API {
    constructor() {
        super();

        this.setPath('/Admin/Goods')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id
        } = req.query

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

        // 检查 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.content,
                a.price,
                a.views,
                a.num,
                a.ic_count,
                a.lepao_count,
                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 a.id = ?
        `

        let rows = await db.query(sql, [id])

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

        res.json({
            ...BaseStdResponse.OK,
            data: rows[0]
        })
    }
}

module.exports.GetGoods = GetGoods