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

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

        this.setPath('/IC/GetSeatMenu')
        this.setMethod('GET')
    }

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

        if ([uuid, session, username].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)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '教务系统账号未绑定或未激活'
            })

        try {
            const cookie = await ic.getCookie(username, password)
            const data = await ic.getSeatMenu(cookie)

            if (data.code || data.code === 300) {
                cookie = await ic.resetCookie(username, password)
                data = await ic.getSeatMenu(cookie)
            }

            res.json({
                ...BaseStdResponse.OK,
                data
            })
        } catch (error) {
            res.json({
                ...BaseStdResponse.ERR,
                msg: error.message || '获取位置信息失败！请稍后再试'
            })
        }
    }
}

module.exports.GetSeatMenu = GetSeatMenu;