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

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

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

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

        if ([uuid, session, username, roomId, date].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 {
            let cookie = await ic.getCookie(username, password)
            let data = await ic.getSeatInfo(cookie, roomId, date)
            if(data.code === 300) {
                cookie = await ic.resetCookie(username, password)
                data = await ic.getSeatInfo(cookie, roomId, date)
            }

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

module.exports.GetSeatInfo = GetSeatInfo