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

class AddStarGroup extends API{
    constructor(){
        super()

        this.setPath('/IC/StarGroup')
        this.setMethod('POST')
    }

    async onRequest(req, res){

        let {
            uuid,
            session,
            id,
            seats,
            state,
            name,
            index
        } = req.body

        if ([uuid, session, seats, name, state].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 sql, r
        const time = new Date().getTime()

        if(!id) {
            sql = 'INSERT INTO ic_star_group (seats, create_user, create_time, \`name\`, state) VALUES (?, ?, ?, ?, ?)'
            r = await db.query(sql, [seats, uuid, time, name, state])
        } else {
            sql = 'UPDATE ic_star_group SET seats = ?, state = ?, \`name\` = ?, \`index\` = ?, update_time = ? WHERE id = ? AND create_user = ?'
            r = await db.query(sql, [seats, state, name, index, time, id, uuid])
        }

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK
                })
            } else {
                res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '添加志愿组失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`添加志愿组失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "添加志愿组失败！",
            });
        }
    }
}

module.exports.AddStarGroup = AddStarGroup