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

// 添加用户
class AddUser extends API {
    constructor() {
        super();

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

    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 { uuid, session, username, password, permissions } = req.body;

        if ([uuid, session, username, 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位之间，且包含字母和数字'
            })

        // TODO 检查是否存在权限
        if (permissions.length === 0)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '请选择用户权限'
            })
        
        // 检查 session
        if (!await AccessControl.checkSession(uuid, session))
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED,
                endpoint: 48153145
            })

        // 检查权限
        let permission = await AccessControl.getPermission(uuid)
        if (!permission.includes("admin"))
            return res.json({
                ...BaseStdResponse.PERMISSION_DENIED,
                endpoint: 4815478,
            })

        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: '用户名已被占用！'
            })

        uuid = uuidv4();
        session = uuidv4();
        const hashPassword = bcryptjs.hashSync(password, 10);

        sql = 'INSERT INTO users (uuid, username, session, password, permission) VALUES (?, ?, ?, ?, ?)';
        
        let result = await db.query(sql, [uuid, username, session, hashPassword, JSON.stringify(permissions)]);

        if (result && result.affectedRows > 0) {            
            res.json({
                ...BaseStdResponse.OK
            })
        } else {
            res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '添加用户失败！' });
        }
    }
}

module.exports.AddUser = AddUser
