const API = require("../../../lib/API");
const db = require("../../../plugin/DataBase/db");
const { BaseStdResponse } = require("../../../BaseStdResponse");
const sendEmail = require('../../../plugin/Email/Email');
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) {
        let { uuid, session, oldpassword, password } = req.body;

        if ([uuid, session, oldpassword, 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.json({
                ...BaseStdResponse.ACCESS_DENIED,
                endpoint: 48153145
            });
        }

        oldpassword = atob(oldpassword);
        password = atob(password);

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

        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.DATABASE_ERR
            })

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

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

        if (result && result.affectedRows > 0) {
            res.json({
                ...BaseStdResponse.OK
            });
            await sendEmail(rows[0].email, '更改成功', `您的Double_X考勤账号更改密码成功，操作时间：${new Date().toLocaleString()}`);
        } else {
            res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '操作失败！' });
        }
    }
}

module.exports.ChangePassword = ChangePassword;
