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

// 出现异常情况时补充乐跑
class StartLepao extends API {
    constructor() {
        super();

        this.noEncrypt()
        this.setPath('/Corn/StartLepao');
        this.setMethod('GET');
    }

    async onRequest(req, res) {
        try {
            let { time } = req.query

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

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

            this.logger.info('开始执行补充乐跑任务')

            const day = new Date().getDay()
            let sql = `
                        SELECT name, create_user, student_num
                        FROM lepao_account
                        WHERE auto_run = 1
                            AND JSON_CONTAINS(auto_day, CAST(? AS JSON))
                            AND (auto_time = ? OR (auto_time = -1 AND today_auto_time = ?))
                        `
            let r = await db.query(sql, [day, time, time])
            if (!r)
                return this.logger.error('获取补充乐跑账号失败！')

            for (const item of r) {
                const { name, create_user, student_num } = item
                this.logger.info(`${name}(${student_num})开始补充乐跑`)

                const isProgress = await Redis.get(`cgLepaoProgress:${student_num}`)
                if (isProgress) {
                    this.logger.info(`${name}(${student_num})已进入乐跑任务队列，请等待乐跑完成后再进行乐跑操作`)
                    continue
                }

                const isSuccess = await Redis.get(`cgLepaoSuccess:${student_num}`)
                if (isSuccess) {
                    this.logger.info(`${name}(${student_num})当天已乐跑成功，不执行补充乐跑`)
                    continue
                }

                try {
                    await lepao.beginLepao(create_user, student_num)
                    this.logger.info(`${name}(${student_num})补充乐跑完成`)
                } catch (err) {
                    this.logger.error(`${name}(${student_num})补充乐跑失败：${err.message || err}`)
                }
            }

            this.logger.info('补充乐跑任务执行完毕')
        } catch (error) {
            this.logger.error(error)
        }
    }
}

module.exports.StartLepao = StartLepao
