const EmailTemplate = require('../Email/emailTemplate.js')
const { enqueueLepaoStartRun } = require('../mq/enqueueLepaoStartRun')
const mq = require('../mq')
const { BaseStdResponse } = require('../../BaseStdResponse.js')
const Redis = require('../DataBase/Redis.js')
const jkesRedisKeys = require('./redisKeys.js')
const { syncLepaoAccountFromToken } = require('./syncLepaoAccountFromToken.js')
const { prepareAutoRunTask, isAutoRunDayToday } = require('./prepareAutoRunTask.js')

async function executeLepaoTokenUpdate(ctx, req, res) {
    const { logger, messageQueue } = ctx
    const { token } = req.body

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

    try {
        const sync = await syncLepaoAccountFromToken(token)
        if (!sync.ok) {
            logger.error(`获取/更新用户信息失败: ${sync.msg}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: sync.msg
            })
        }

        const { student_num, findRows, profile } = sync

        try {
            await Redis.set(jkesRedisKeys.runnerFlag(student_num), '1')
        } catch (e) {
            logger.error(`${student_num} 写入 jkes_runner 标记失败：${e.message || e}`)
        }

        let msg
        if (findRows[0].auto_run === 1) {
            msg = `当前已开启自动乐跑，系统将自动进行乐跑。后续通知将发送到您预留的联系方式，请留意。`
        } else {
            msg = `当前未开启自动乐跑，如需进行乐跑，请前往 沐晨乐跑 手动执行乐跑操作。后续通知将发送到您预留的联系方式，请留意。`
        }

        res.json({
            ...BaseStdResponse.OK,
            data: {
                name: profile.name,
                user_avatar: profile.user_avatar,
                sex: profile.sex,
                academy_name: profile.academy_name,
                grade_id: profile.grade_id,
                class_id: profile.class_id,
                auto_run: findRows[0].auto_run,
                account: student_num,
                msg
            }
        })

        const emailData = {
            name: profile.name,
            type: 'lepao_update',
            umo: findRows[0].bot_umo,
            account: student_num,
            academy_name: profile.academy_name,
            grade_id: profile.grade_id,
            auto_run: findRows[0].auto_run
        }

        if (findRows[0].notice_type === 'bot' && findRows[0].bot_umo) {
            logger.info(`${student_num}发送乐跑更新Bot通知，UMO=${findRows[0].bot_umo}`)
            const ch = await mq.getChannel(messageQueue)
            await ch.assertQueue(messageQueue, { durable: true })
            await mq.sendToQueueSafe(
                messageQueue,
                messageQueue,
                Buffer.from(JSON.stringify(emailData)),
                { persistent: true, contentType: 'application/json' }
            )

            logger.info(`${student_num}乐跑更新Bot通知发送完成`)
        } else if (findRows[0].notice_type === 'email' && findRows[0].email) {
            await EmailTemplate.updateSuccess(findRows[0].email, emailData)
            logger.info(`${student_num}乐跑更新邮件发送完成`)
        }

        if (findRows[0].auto_run === 1 && isAutoRunDayToday(findRows[0].auto_day)) {
            prepareAutoRunTask(findRows[0])
                .then(async (prepared) => {
                    if (!prepared.run) {
                        logger.info(`${student_num} 登录后未触发 JKES 自动乐跑：${prepared.reason}`)
                        return
                    }
                    const ok = await enqueueLepaoStartRun(student_num, logger, prepared.task)
                    if (!ok) {
                        logger.error(`${student_num} 登录后自动乐跑投递失败`)
                    }
                })
                .catch((e) => {
                    logger.error(`${student_num} JKES 自动乐跑计划失败：${e.message || e}`)
                })
        }
    } catch (error) {
        logger.error(`更新用户信息时出错。${error.stack}`)
        return res.json({
            ...BaseStdResponse.ERR,
            msg: '更新用户信息失败，请重试'
        })
    }
}

module.exports = {
    executeLepaoTokenUpdate
}
