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

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

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

    async onRequest(req, res) {
        let {
            uuid,
            session,
            id,
            name,
            loop,
            mode,
            day_of_week,
            state,
            users,
            beginTime,
            endTime
        } = req.body

        if ([uuid, session, name, loop, mode, users, beginTime, endTime].some(value => value === '' || value === null || value === undefined) || (loop && !day_of_week))
            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_rule (\`name\`, create_user, create_time, \`loop\`, \`mode\`, day_of_week, users, beginTime, endTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
            r = await db.query(sql, [name, uuid, time, loop, mode, day_of_week, users, beginTime, endTime])
        } else {
            // 确保只有一个规则生效
            // if(state == 1) {
            //     sql = 'UPDATE ic_rule SET \`state\` = 0 WHERE create_user = ?'
            //     await db.query(sql, [uuid])
            // }

            sql = 'UPDATE ic_rule SET \`name\` = ?, \`loop\` = ?, \`mode\` = ?, day_of_week = ?, update_time = ?, \`state\` = ?, users = ?, beginTime = ?, endTime = ? WHERE id = ? AND create_user = ?'
            r = await db.query(sql, [name, loop, mode, day_of_week, time, state, users, beginTime, endTime, 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.AddRule = AddRule;