const md5 = require("md5");
const API = require("../../../lib/API");
const bcryptjs = require('bcryptjs');
const db = require("../../../plugin/DataBase/db");
const { BaseStdResponse } = require("../../../BaseStdResponse");
const Redis = require('../../../plugin/DataBase/Redis');
const sendEmail = require('../../../plugin/Email/Email');

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

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

    createSession(uuid, salt) {
        return md5(`${uuid}${salt}${new Date().getTime()}`);
    }

    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]{2,8}$/;
        return regex.test(username);
    }

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

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

        if(!this.checkUsername(username))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '用户名需在2到8位之间，且只能含有英文字母和汉字'
            })

        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, [username]);
        if (EmailRows.length > 0)
            return res.json({
                ...BaseStdResponse.USER_ALREADY_EXISTS,
                msg: '该邮箱已被注册！'
            })

        // 查询users表中是否有用户
        const userCountQuery = 'SELECT COUNT(*) as count FROM users';
        const userCountResult = await db.query(userCountQuery);
        // 如果是第一个注册的用户 授予admin权限
        const admin = userCountResult[0].count === 0 ? 1 : 0;

        const uuid = md5(Date.now() + email + code);
        const session = this.createSession(code, Math.random().toFixed(6).slice(-6));
        const hashPassword = bcryptjs.hashSync(password, 10);
        const avatar = '/avatar/avatar.png';

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

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

            res.json({
                ...BaseStdResponse.OK
            });
            await sendEmail(email, '账号注册成功', `您已成功注册Double_X考勤账号，用户名${username}，注册时间：${new Date().toLocaleString()}`);
        } else {
            res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '注册失败！'});
        }
    }
}

module.exports.Register = Register;
