const API = require("../../lib/API.js")
const db = require('../../plugin/DataBase/db.js')
const { BaseStdResponse } = require("../../BaseStdResponse.js")

class SetAutoTime extends API {
    constructor() {
        super()

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

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

            this.logger.info('开始更换随机乐跑时间段')

            const deleteSql = 'UPDATE lepao_account SET today_auto_time = NULL'
            const deleteR = await db.query(deleteSql)
            if (!deleteR)
                this.logger.error('重置随机乐跑时间段失败！')

            const sql = `
                        UPDATE lepao_account
                        SET today_auto_time = FLOOR(7 + (RAND() * 15))
                        WHERE auto_time = -1 AND auto_run = 1 AND JSON_CONTAINS(auto_day, CAST(? AS JSON));
                    `

            const day = new Date().getDay()
            const r = await db.query(sql, [day])
            if (!r)
                return this.logger.error('更换随机乐跑时间段失败！')
            this.logger.info('更换随机乐跑时间段完成')
        } catch (error) {
            this.logger.error(error)
        }
    }
}

module.exports.SetAutoTime = SetAutoTime
