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

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))

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

        this.noEncrypt()
        this.setPath('/Corn/UpdateState')
        this.setMethod('GET')

        this.runpy = config.runpy
    }

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

            this.logger.info('开始更新乐跑账号登录状态')

            const zoneUrl = this.runpy + '/set_zone'

            let sql = `SELECT id, uid, token, school_id, name, student_num FROM lepao_account WHERE state = 0 AND auto_run = 1 AND token IS NOT NULL`

            let r = await db.query(sql)
            if (!r)
                return this.logger.error('更新乐跑账号登录状态失败！')

            for (const item of r) {
                const { name, student_num, token, uid, school_id } = item
                this.logger.info(`${name}(${student_num})开始更新乐跑登录状态`)

                await sleep(2000)

                try {
                    const ossData = { uid, token, school_id, student_id: student_num, random_id: 1, run_end_time: 1 }
                    const zoneRes = await axios.post(zoneUrl, ossData)
                    const { data } = zoneRes

                    this.logger.info(`${student_num}更新乐跑登录状态返回结果: ${JSON.stringify(data)}`)

                    if (!data || data.status != 1 || !data.data) {
                        this.logger.info(`${name}(${student_num})数据获取失败，不更新`)
                        continue
                    }

                    const sql = 'UPDATE lepao_account SET state = 1 WHERE student_num  = ?'
                    await db.query(sql, [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.UpdateState = UpdateState
