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 { BaseStdResponse } = require("../../../BaseStdResponse.js")

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

        this.runpy = config.runpy
        this.noEncrypt()
        this.setPath('/Lepao/UpdateAccount')
        this.setMethod('POST')
    }

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

        if ([reqData, resData].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            })

        try {
            const endpoint = config.runpy + '/decrypted_data'
            const ReqData = await axios.post(endpoint, { data: reqData })
            let userData = ReqData.data
            if (userData?.code !== 200 || !userData.data)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '无法解析用户数据，请重试'
                })
            const { token } = userData.data
            if ([token].some(value => value === '' || value === null || value === undefined))
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '未提取出用户登录信息，请重试'
                })

            const ResData = await axios.post(endpoint, { data: resData })
            let userData2 = ResData.data
            if (userData2?.code !== 200 || !userData2.data)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '无法解析用户数据，请重试'
                })
            const { uid, user_avatar, student_num, school_id, grade_id, class_id, sex, name, academy_name } = userData2.data
            if ([uid, user_avatar, 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 email, create_user, auto_run FROM lepao_account WHERE student_num = ?'
            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系统中添加，请先前往 https://xxoo365.top/ 添加你的账户'
                })
            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 WHERE student_num = ?'
            let updateRows = await db.query(updateSql, [uid, token, school_id, name, grade_id, class_id, sex, academy_name, time, user_avatar, student_num])

            if (updateRows && updateRows.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        name,
                        academy_name,
                        grade_id,
                        auto_run: findRows[0].auto_run,
                        account: student_num
                    }
                })
                let emailData = {
                    name,
                    account: student_num,
                    academy_name,
                    grade_id,
                    auto_run: findRows[0].auto_run
                }

                await EmailTemplate.updateSuccess(findRows[0].email, emailData)

                if (findRows[0].auto_run === 1) {
                    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.UpdateAccount = UpdateAccount;
