const API = require("../../../lib/API.js")
const db = require("../../../plugin/DataBase/db.js")
const { BaseStdResponse } = require("../../../BaseStdResponse.js")
const AccessControl = require("../../../lib/AccessControl.js")
const { lepaoAuth, lepaoUserInfo } = require('../../../lib/Lepao/lepaoAPI')

class AddAccount extends API {
    constructor() {
        super();

        this.setPath('/Lepao/Account')
        this.setMethod('POST')

        this.emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        this.banEmailList = ['icloud.com']
    }

    isQQ(str) {
        const reg = /^[1-9][0-9]{4,10}$/
        return reg.test(str)
    }

    async onRequest(req, res) {
        let { uuid, session, student_num, email, id, area, auto_time, auto_run, target_count, password, auto_day, notes } = req.body

        if ([uuid, session, student_num, email, auto_time, target_count, auto_day].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        if (isNaN(target_count) || target_count < 0 || target_count > 999) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '乐跑目标次数不在合法范围内'
            })
        }

        if (!this.emailRegex.test(email)) {
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '请检查邮箱格式是否正确'
            })
        }

        const emailDomain = email.split('@')[1].toLowerCase()
        if (this.banEmailList.includes(emailDomain))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: `暂不支持使用 ${emailDomain} 域名的邮箱，请更换其他邮箱后重试`
            })

        if (auto_run === 1 && (!Array.isArray(auto_day) || !auto_day.every(v => Number.isInteger(v) && v >= 0 && v <= 6)))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '自动乐跑日期格式不合法'
            })

        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED
            })

        let countSql = 'SELECT id, create_user, total_num FROM lepao_account WHERE student_num = ?'
        let countRows = await db.query(countSql, [student_num])

        if (!countRows)
            return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败！数据库错误' })

        // 判断是否重复注册
        if (!id) {
            if (!password) {
                return res.json({ ...BaseStdResponse.ERR, msg: '请输入乐跑账号密码' })
            }

            if (countRows.length !== 0 && countRows[0].create_user != null) {
                if (countRows[0].create_user !== uuid)
                    return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已被其他用户绑定，请联系客服解绑' })
                return res.json({ ...BaseStdResponse.ERR, msg: '该乐跑账号已添加' })
            }

            // 进行密码校验
            try {
                password = atob(password)
                await lepaoAuth(student_num, password)
            } catch (err) {
                this.logger.info(`乐跑账号验证失败！${err.message}`)
                return res.json({ ...BaseStdResponse.ERR, msg: err.message ?? '无法验证乐跑账号，请联系客服或稍后再试' })
            }
        }

        if (countRows.length !== 0) {
            if (auto_run && countRows[0].total_num >= target_count && target_count !== 0)
                return res.json({ ...BaseStdResponse.ERR, msg: `该账号累计跑步次数（${countRows[0].total_num}）已达到目标次数，请尝试修改目标次数` })
        }

        const time = new Date().getTime()

        let sql, r, user_avatar

        let userInfo = await lepaoUserInfo(student_num)

        try {
            if (auto_run && userInfo.frequency >= target_count && target_count !== 0)
                return res.json({ ...BaseStdResponse.ERR, msg: `该账号累计跑步次数（${userInfo.frequency}）已达到目标次数，请尝试修改目标次数` })
        } catch (error) {
            return res.json({ ...BaseStdResponse.ERR, msg: '获取用户信息失败，请联系客服或稍后再试' })
        }

        // 生成用户头像
        if (email.split('@')[1].toLowerCase() === 'qq.com' && this.isQQ(email.split('@')[0])) {
            user_avatar = `https://q2.qlogo.cn/headimg_dl?dst_uin=${email}&spec=640`
        } else {
            user_avatar = userInfo.sex === 0 ? 'https://lepao-cloud.xxoo365.top/view.php/aee85ff43fd30d0df03c6a7dd9797d22.png' : 'https://lepao-cloud.xxoo365.top/view.php/fcb54dcc5e6209381e972ef73bdb4a93.png'
        }

        if (!id) {
            if (countRows.length !== 0) {
                sql = 'UPDATE lepao_account SET create_user = ?, email = ?, area = ?, auto_time = ?, auto_run = ?, target_count = ?, create_time = ?, notes = ?, total_num = ?, auto_day = ?, user_avatar = ? WHERE id = ?'
                r = await db.query(sql, [uuid, email, area, auto_time, auto_run, target_count, time, notes ?? '', userInfo.frequency, JSON.stringify(auto_day), user_avatar, countRows[0].id])
            }
            else {
                sql = 'INSERT INTO lepao_account (student_num, name, user_avatar,  grade_id, uid, sex, total_num, email, area, auto_time, auto_run, target_count, create_user, create_time, notes, password, auto_day) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
                r = await db.query(sql, [student_num, userInfo.nickName, user_avatar, userInfo.department, userInfo.id, userInfo.sex, userInfo.frequency, email, area, auto_time, auto_run, target_count, uuid, time, notes ?? '', password ?? '', JSON.stringify(auto_day)])
            }
        } else {
            sql = 'UPDATE lepao_account SET student_num = ?, email = ?, area = ?, auto_time = ?, target_count = ?, total_num = ?, auto_run = ?, notes = ?, auto_day = ?, user_avatar = ? WHERE id = ?'
            r = await db.query(sql, [student_num, email, area, auto_time, target_count, userInfo.frequency, auto_run, notes ?? '', JSON.stringify(auto_day), user_avatar, id])
        }

        try {
            if (r && r.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK,
                    id: r.insertId
                })
            } else {
                return res.json({ ...BaseStdResponse.ERR, msg: '添加乐跑账号失败！数据库错误' })
            }
        } catch (err) {
            this.logger.error(`添加乐跑账号失败！${err.stack}`)
            res.json({
                ...BaseStdResponse.ERR,
                msg: "添加乐跑账号失败！",
            })
        }
    }
}

module.exports.AddAccount = AddAccount