const API = require("../../../../lib/API.js")
const db = require("../../../../plugin/DataBase/db.js")
const axios = require('axios')
const EmailTemplate = require('../../../../plugin/Email/emailTemplate.js')
const config = require('../../../../config.json')
const lepao = require("../../../../lib/Lepao/Lepao.js").lepao
const mq = require('../../../../plugin/mq')
const { BaseStdResponse } = require("../../../../BaseStdResponse.js")
const { dataDecrypt } = require('../../../../plugin/Lepao/Crypto')

// 客户端上传数据接口
class UpdateAccountiPhone extends API {
    constructor() {
        super()

        this.messageQueue = 'runforge_message_queue'
        this.runpy = config.runpy
        this.noEncrypt()
        this.setPath('/Lepao/UpdateAccountiPhone')
        this.setMethod('POST')
    }

    async onRequest(req, res) {
        let { reqData, resData, headers } = req.body

        if ([reqData, resData, headers].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                msg: '账号信息不完整，请稍后再试获联系客服处理'
            })

        try {
            const userData = JSON.parse(dataDecrypt(reqData) || '{}')
            if (!userData || Object.keys(userData).length === 0)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '无法解析用户数据，请重试'
                })
            const { token } = userData
            if ([token].some(value => value === '' || value === null || value === undefined))
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '未提取出用户登录信息，请重试'
                })

            const userData2 = JSON.parse(dataDecrypt(resData) || '{}')
            if (!userData2 || Object.keys(userData2).length === 0)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '无法解析用户数据，请重试'
                })

            const { uid, user_avatar, student_num, school_id, grade_id, class_id, sex, name, academy_name } = userData2
            if ([uid, student_num, school_id, grade_id, class_id, sex, name, academy_name].some(value => value === '' || value === null || value === undefined))
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '未提取出用户登录信息，请重试'
                })

            let findSql = `
                SELECT 
                    a.email, a.create_user, a.auto_run, a.auto_day, a.notice_type, e.bot_umo
                FROM
                    lepao_account a
                LEFT JOIN
                    lepao_extra e
                ON
                    a.student_num = e.student_num
                WHERE
                    a.student_num = ? AND a.create_user IS NOT NULL
                `
            let findRows = await db.query(findSql, [student_num])
            if (!findRows)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '无法解析用户数据，请重试'
                })
            if (findRows.length === 0)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '该乐跑账号尚未在RunForge系统中添加，请先添加你的账户'
                })

            const time = new Date().getTime()
            let updateSql = 'UPDATE lepao_account SET uid = ?, token = ?, school_id = ?, name = ?, grade_id = ?, class_id = ?, sex = ?, academy_name = ?, update_time = ?, user_avatar = ?, state = 1, userAgent = ?, deviceModel = ? WHERE student_num = ?'
            let updateRows = await db.query(updateSql, [uid, token, school_id, name, grade_id, class_id, sex, academy_name, time, user_avatar ?? 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png', headers["User-Agent"] ?? 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.29(0x18001d21) NetType/WIFI Language/zh_CN wxwork/5.0.6', 'unknown<iPhone18,3>', student_num])

            if (updateRows && updateRows.affectedRows > 0) {
                let msg
                if (findRows[0].auto_run === 1) {
                    msg = `当前已开启自动乐跑，系统将自动进行乐跑。后续通知将发送到您的邮箱：${findRows[0].email}。请留意邮箱提醒。`
                }
                else {
                    msg = `当前未开启自动乐跑，如需进行乐跑，请前往 RunForge 手动执行乐跑操作。后续通知将发送到您的邮箱：${findRows[0].email}，请留意邮箱提醒。`
                }
                res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        name,
                        user_avatar,
                        sex,
                        academy_name,
                        grade_id,
                        auto_run: findRows[0].auto_run,
                        account: student_num,
                        msg
                    }
                })

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

                if (findRows[0].notice_type === 'bot' && findRows[0].bot_umo) {
                    this.logger.info(`${student_num}发送乐跑更新Bot通知，UMO=${findRows[0].bot_umo}`)
                    const ch = await mq.getChannel(this.messageQueue)

                    await ch.assertQueue(this.messageQueue, {
                        durable: true
                    })

                    ch.sendToQueue(
                        this.messageQueue,
                        Buffer.from(JSON.stringify(emailData)),
                        {
                            persistent: true,
                            contentType: 'application/json'
                        }
                    )

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

                if (findRows[0].auto_run === 1 && Array.isArray(findRows[0].auto_day) && findRows[0].auto_day.includes(new Date().getDay())) {
                    lepao.beginLepao(findRows[0].create_user, student_num, token, uid, school_id, 1)
                }
            }

            // 获取新加账号中存在的路径
            try {
                let sql = 'SELECT id FROM lepao_record WHERE lepao_account = ?'
                let rows = await db.query(sql, [student_num])

                // 不是老帐号就不获取
                if (!rows || rows.length !== 0) return

                const reqData = { uid, token, school_id, student_id: student_num }
                this.logger.info(`开始请求获取跑步记录 uid=${uid} student_id=${student_num}`)
                const recordUrl = this.runpy + '/get_path_data'
                await axios.post(recordUrl, reqData)
            } catch (error) {
                this.logger.info(`获取跑步记录出错 ${error.stack}`)
            }

        } catch (error) {
            this.logger.error(`更新用户信息时出错。${error.stack}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '更新用户信息失败，请重试'
            })
        }
    }
}

module.exports.UpdateAccountiPhone = UpdateAccountiPhone
