const { v4: uuidv4 } = require('uuid');
const API = require("../../lib/API");
const bcryptjs = require('bcryptjs');
const { BaseStdResponse } = require("../../BaseStdResponse");
const db = require("../../plugin/DataBase/db");
const Redis = require('../../plugin/DataBase/Redis');
const EmailTemplate = require('../../plugin/Email/emailTemplate')

// 用户注册
class Register extends API {
    constructor() {
        super();

        this.setMethod("POST");
        this.setPath("/User/Register");
    }

    CheckPassword(password) {
        if (password.length < 8 || password.length > 16) {
            return false;
        }

        const hasLetter = /[a-zA-Z]/.test(password);
        const hasNumber = /\d/.test(password);

        return hasLetter && hasNumber;
    }

    checkUsername(username) {
        const regex = /^[\u4e00-\u9fa5A-Za-z0-9]{3,12}$/;
        return regex.test(username);
    }

    async onRequest(req, res) {
        let { username, password, code, email } = req.body

        if ([username, password, code, email].some(value => value === '' || value === null || value === undefined))
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER
            })

        if (!this.checkUsername(username))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '用户名需在3到12位之间，且不能含有特殊字符'
            })

        password = atob(password);

        if (!this.CheckPassword(password))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '密码需在8到16位之间，且包含字母和数字'
            })

        try {
            const VerifyCode = await Redis.get(`email:${email}`);
            if (!VerifyCode || VerifyCode != code)
                return res.json({
                    ...BaseStdResponse.SMS_CHECK_FAIL,
                    msg: '邮箱验证码输入错误或已过期'
                })

        } catch (err) {
            this.logger.error(`验证邮箱验证码失败！${err.stack}`);
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg: '验证失败！'
            })
        }

        let sql = 'SELECT username FROM users WHERE username = ?';
        let UsernameRows = await db.query(sql, [username]);
        if (UsernameRows.length > 0)
            return res.json({
                ...BaseStdResponse.USER_ALREADY_EXISTS,
                msg: '用户名已被占用！'
            })

        sql = 'SELECT email FROM users WHERE email = ?';
        let EmailRows = await db.query(sql, [email]);
        if (EmailRows.length > 0)
            return res.json({
                ...BaseStdResponse.USER_ALREADY_EXISTS,
                msg: '该邮箱已被注册！'
            })

        const uuid = uuidv4()
        const hashPassword = bcryptjs.hashSync(password, 10);
        const time = new Date().getTime()

        sql = 'INSERT INTO users (uuid, username, email, password, registTime) VALUES (?, ?, ?, ?, ?)';
        let result = await db.query(sql, [uuid, username, email, hashPassword, time]);

        if (result && result.affectedRows > 0) {
            // 注册成功后删除邮箱对应的验证码 避免注册失败后重复获取
            await Redis.del(`email:${email}`);

            res.json({
                ...BaseStdResponse.OK
            })
            await EmailTemplate.registerSuccess(email, username)
        } else {
            res.json({ ...BaseStdResponse.ERR, msg: '注册失败！' });
        }
    }
}

module.exports.Register = Register;
