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

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

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

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

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

            let sql = `
            SELECT
                id,
                name,
                content,
                price,
                num,
                \`limit\`,
                icon,
                isHot,
                description,
                category,
                features
            FROM
                goods 
            WHERE id = ? AND state = 1
        `

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

        sql = 'UPDATE goods SET views = views + 1 WHERE id = ?'
        await db.query(sql, [id])
    }
}

module.exports.GetProduct = GetProduct;