const API = require("../../lib/API.js")
const Redis = require('../../plugin/DataBase/Redis')
const db = require("../../plugin/DataBase/db.js")
const { BaseStdResponse } = require("../../BaseStdResponse.js")
const AccessControl = require("../../lib/AccessControl.js")
const lepao = require("../../lib/Lepao/cg_lepao").Lepao

// 单次乐跑
class SingleRun extends API {
    constructor() {
        super();

        this.setPath('/Lepao/SingleRun')
        this.setMethod('GET')
    }

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

        if ([uuid, session, student_num].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        // let hour = new Date().getHours()
        // if (hour < 7)
        //     return res.json({
        //         ...BaseStdResponse.ERR,
        //         msg: '当前不在有效乐跑时间范围内。请在7:00~24:00发起乐跑'
        //     })

        try {
            // 检查redis是否存在当天乐跑成功记录
            // const isSuccess = await Redis.get(`cgLepaoSuccess:${student_num}`)
            // if (isSuccess)
            //     return res.json({
            //         ...BaseStdResponse.ERR,
            //         msg: '该账号当天已乐跑成功！请勿重复乐跑'
            //     })

            const isProgress = await Redis.get(`cgLepaoProgress:${student_num}`)
            if (isProgress)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '该账号已进入乐跑任务队列，请等待乐跑完成后再进行乐跑操作'
                })

            let selectSql = 'SELECT create_user FROM lepao_account WHERE student_num = ?'
            let selectRows = await db.query(selectSql, [student_num])
            if (!selectRows || selectRows.length === 0)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '发起乐跑失败！未找到账户信息'
                })

            if (selectRows[0].create_user !== uuid) {
                let permission = await AccessControl.getPermission(uuid)
                if (!permission.includes("admin") && !permission.includes("service"))
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: '发起乐跑失败！未找到账户信息'
                    })
            }

            let sql = 'SELECT state FROM lepao_account WHERE student_num = ?'
            let rows = await db.query(sql, [student_num])
            if (!rows || rows.length === 0)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '发起乐跑失败！未找到对应的账号信息'
                })

            if (rows[0].state !== 1)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '账号状态异常，无法进行乐跑。请联系客服处理'
                })

            res.json({
                ...BaseStdResponse.OK
            })

            try {
                await lepao.beginLepao(selectRows[0].create_user, student_num)
            } catch (err) {
                this.logger.error(`后台乐跑任务异常：${err.stack}`)
            }

        } catch (err) {
            this.logger.error(`手动乐跑失败！${err.stack}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: "乐跑失败！数据库异常"
            })
        }
    }
}

module.exports.SingleRun = SingleRun
