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 ForgetPassword extends API {
    constructor() {
        super();

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

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

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

    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.CheckPassword(password))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '密码需在8到16位之间，且包含字母和数字'
            })

        let sql = 'SELECT id FROM users WHERE username = ? AND email = ?';
        let Rows = await db.query(sql, [username, email]);
        if (Rows.length === 0)
            return res.json({
                ...BaseStdResponse.USER_NOT_EXISTS,
                msg: '用户名和邮箱不匹配！'
            })

        password = atob(password);

        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: '验证失败！'
            })
        }

        
        const session = this.createSession(code, Math.random().toFixed(6).slice(-6));
        const hashPassword = bcryptjs.hashSync(password, 10);

        sql = 'UPDATE users SET password = ? , session = ? WHERE id = ?';
        let result = await db.query(sql, [hashPassword, session, Rows[0].id]);

        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.ForgetPassword = ForgetPassword;
