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

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

        this.setPath('/Lepao/ChangePathState')
        this.setMethod('POST')
    }

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

        if ([uuid, session, id, 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 permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin") && !permission.includes("path"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED
            })

        try {
            let sql = 'UPDATE path_data SET state = ? WHERE id = ?'
            let r = await db.query(sql, [state, id])

            if (r && r.affectedRows > 0) {
                let sql = `
                        SELECT
                            id
                        FROM
                            path_data
                        WHERE id > ? AND state = 0
                        LIMIT 1
                    `
                let rows = await db.query(sql, [id])

                if (!rows || rows.length === 0)
                    return res.json({
                        ...BaseStdResponse.OK,
                        msg: '审核完毕！无未审核路径'
                    })

                res.json({
                    ...BaseStdResponse.OK,
                    data: rows[0].id,
                    msg: '正在转到下一未审核路径'
                })
            } else {
                res.json({ ...BaseStdResponse.ERR, msg: '改变路径状态失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`改变路径状态失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "改变路径状态失败!",
            });
        }
    }

}

module.exports.ChangePathState = ChangePathState