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

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

        this.setPath('/IC/Seat/MyOrder')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        let { uuid, session, username, beginDate, endDate, page, pageNum } = req.body

        if ([uuid, session, username, beginDate, endDate, page, pageNum].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: '教务系统账号未绑定或未激活'
            })

        const data = {
            beginDate, endDate, page, pageNum
        }

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

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

module.exports.MyOrder = MyOrder