const API = require("../../lib/API");
const db = require('../../plugin/DataBase/db')
const Redis = require('../../plugin/DataBase/Redis')
const mq = require('../../plugin/mq')

const { BaseStdResponse } = require("../../BaseStdResponse");

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

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

    async onRequest(req, res) {
        try {
            res.json({
                ...BaseStdResponse.OK
            })

            const day = new Date().getDay()
            const hour = new Date().getHours()
            this.logger.info('开始执行自动乐跑任务')
            let sql = `
                        SELECT name, create_user, student_num, token, uid, school_id, state
                        FROM lepao_account
                        WHERE auto_run = 1
                            AND (auto_time = ? OR (auto_time = -1 AND today_auto_time = ?))
                            AND JSON_CONTAINS(auto_day, CAST(? AS JSON))
                        `
            let r = await db.query(sql, [hour, hour, day])
            if (!r)
                return this.logger.error('获取自动乐跑账号失败！')

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

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

                try {
                    const channel = await mq.getChannel('lepao_corn')
                    await channel.assertQueue('runforge_task_queue', { durable: true })

                    const taskId = `lepao:auto:${Date.now()}:${student_num}`
                    const payload = {
                        id: taskId,
                        type: 'lepao.startRun',
                        data: {
                            taskId,
                            account: student_num
                        },
                        retry: 0
                    }

                    channel.sendToQueue(
                        'runforge_task_queue',
                        Buffer.from(JSON.stringify(payload)),
                        { persistent: true, contentType: 'application/json' }
                    )
                    this.logger.info(`${name}(${student_num})已投递自动乐跑任务`)
                } catch (err) {
                    this.logger.error(`${name}(${student_num})乐跑失败：${err.message || err}`)
                }
            }
        } catch (error) {
            this.logger.error(error)
        }
    }
}

module.exports.StartAutoLepao = StartAutoLepao;
