const API = require("../../../lib/API");
const AccessControl = require("../../../lib/AccessControl");
const ic = require("../../../lib/IC/IC").IC;
const { BaseStdResponse } = require("../../../BaseStdResponse");

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

        this.setPath('/IC/Seat')
        this.setMethod('delete')
    }

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

        if ([uuid, session, username, seatuuid].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
            })

        const password = await AccessControl.checkJwAccount(uuid, username)
        if(!password)
            res.json({
                ...BaseStdResponse.ERR,
                msg: '教务系统账号未绑定或未激活'
            })

        try {
            let cookie = await ic.getCookie(username, password)
            let resdata = await ic.deleteSeat(cookie, seatuuid)
            if (resdata.code === 300) {
                cookie = await ic.resetCookie(username, password)
                resdata = await ic.deleteSeat(cookie, seatuuid)
            }

            res.json({
                ...BaseStdResponse.OK,
                data: resdata.data
            })
        } catch (error) {
            res.json({
                ...BaseStdResponse.ERR,
                msg: error.message || '取消预约失败！请稍后再试'
            })
        }
    }
}

module.exports.DeleteSeat = DeleteSeat