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

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

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

    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;
    }

    async onRequest(req, res) {
        try {
            let { uuid, session, oldpassword, password } = req.body;

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

            // 检查 session 是否有效
            if (!await AccessControl.checkSession(uuid, session)) {
                return res.status(401).json({
                    ...BaseStdResponse.ACCESS_DENIED,
                    endpoint: 48153145
                });
            }

            password = atob(password);

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

            if (oldpassword && oldpassword !== '') {
                oldpassword = atob(oldpassword);

                let sql = 'SELECT email, password FROM users WHERE uuid = ?';
                let rows = await db.query(sql, [uuid]);
                if (!rows || rows.length === 0)
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: '暂时无法重设密码，请联系客服'
                    })

                if (oldpassword !== '' && !bcryptjs.compareSync(oldpassword, rows[0].password))
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: '密码错误！'
                    })
            }

            const hashPassword = bcryptjs.hashSync(password, 10);
            let sql = 'UPDATE users SET password = ? WHERE uuid = ?';
            let result = await db.query(sql, [hashPassword, uuid]);

            if (result && result.affectedRows > 0) {
                res.json({
                    ...BaseStdResponse.OK
                });
            } else {
                res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '操作失败！' });
            }
        } catch (error) {
            console.log(error.stack)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '密码更新失败，请联系客服'
            })
        }

    }
}

module.exports.ChangePassword = ChangePassword;
