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

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

        this.setPath('/Lepao/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 selectSql = 'SELECT create_user FROM lepao_account WHERE id = ?'
        let selectRows = await db.query(selectSql, [id])
        if (!selectRows || selectRows.length === 0)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '解绑账号失败！未找到账户信息'
            })

        if (selectRows[0].create_user !== uuid) {
            let permission = await AccessControl.getPermission(uuid)
            if (!permission.includes("admin") && !permission.includes("service"))
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '解绑账号失败！未找到账户信息'
                })
        }

        let snRows = await db.query('SELECT student_num FROM lepao_account WHERE id = ?', [id])
        const sn = snRows?.[0]?.student_num

        const progressKey = jkesRedisKeys.lepaoProgress(req.account)
        const inProgress = await Redis.get(progressKey)
        if (inProgress) 
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '该账号已进入乐跑任务队列，请等待乐跑完成后再进行解绑操作'
            })

        let sql = 'UPDATE lepao_account SET create_user = NULL, auto_run = 0 WHERE id = ?'
        let r = await db.query(sql, [id])

        try {
            if (r && r.affectedRows > 0) {
                if (sn) {
                    try {
                        await Redis.del(jkesRedisKeys.runnerFlag(sn))
                    } catch (e) {
                        this.logger.error(`解绑清理 jkes_runner 失败 ${sn}: ${e.message || e}`)
                    }
                }
                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