const API = require("../../lib/API");
const db = require('../../plugin/DataBase/db')
const mq = require('../../plugin/mq')
const {
    assertRunforgeTaskIngress,
    publishRunforgeTask
} = require('../../plugin/mq/runforgeTaskMq')
const mqNames = require('../../plugin/mq/jkesMqNames')
const { BaseStdResponse } = require("../../BaseStdResponse")
const { prepareAutoRunTask, buildStartRunPayload } = require('../../plugin/jkes/prepareAutoRunTask')

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, student_num, auto_day, token, target_count,
                               auto_run_distance_min_km, auto_run_distance_max_km, pace_min_sec_per_km, pace_max_sec_per_km
                        FROM lepao_account
                        WHERE auto_run = 1 AND state = 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, student_num } = item
                this.logger.info(`${name}(${student_num})开始补充乐跑`)

                const prepared = await prepareAutoRunTask(item)
                if (!prepared.run) {
                    this.logger.info(`${name}(${student_num}) JKES 补充乐跑跳过：${prepared.reason}`)
                    continue
                }

                try {
                    const channel = await mq.getChannel(mqNames.channelLepaoCorn)
                    await assertRunforgeTaskIngress(channel, this.logger)
                    const payload = buildStartRunPayload(student_num, prepared.task, { prefix: 'lepao:repair' })
                    publishRunforgeTask(channel, payload)
                    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
