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

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

        this.setPath('/Power/Account')
        this.setMethod('DELETE')
    }

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

        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 sql = 'DELETE FROM power_task WHERE create_user = ? AND id = ?'
        let r = await db.query(sql, [uuid, id])

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK
                })
            } else {
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '删除电费提醒任务失败！数据库错误'
                })
            }
        } catch (err) {
            this.logger.error(`删除电费提醒任务失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "删除电费提醒任务失败！",
            })
        }
    }
}

module.exports.DeleteAccount = DeleteAccount