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

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

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

    async onRequest(req, res){

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

        if ([uuid, session, devId, name].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 = 'SELECT id FROM ic_star WHERE create_user = ? AND devId = ?'
            const rows = await db.query(sql, [uuid, devId])
            if (!rows)
                return res.json({ ...BaseStdResponse.ERR, endpoint: 794378, msg: '添加志愿失败！数据库错误' })
            if(rows.length > 0)
                return res.json({ ...BaseStdResponse.ERR, endpoint: 789378, msg: '您已添加过该位置' })

            sql = 'INSERT INTO ic_star (devId, create_user, create_time, \`name\`) VALUES (?, ?, ?, ?)'
            r = await db.query(sql, [devId, uuid, time, name])
        } else {
            sql = 'UPDATE ic_star SET devId = ?, state = ?, \`name\` = ?, \`index\` = ? WHERE id = ? AND create_user = ?'
            r = await db.query(sql, [devId, state, name, index, 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.AddStar = AddStar;