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

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

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

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

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

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

        password = atob(password);

        try {
            const code = await Redis.get(`captcha:${id}`);
            if (!code || code != text)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '验证码错误或已过期！'
                })
        } catch (err) {
            this.logger.error(`验证图片验证码失败！${err.stack}`);
            return res.json({
                ...BaseStdResponse.DATABASE_ERR,
                msg: '验证失败！'
            })
        }

        let sql = 'SELECT * FROM users WHERE username = ? OR email = ?';
        let rows = await db.query(sql, [username, username]);

        if (!rows || rows.length !== 1 || !bcryptjs.compareSync(password, rows[0].password))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '用户名或密码错误'
            })

        const session = this.createSession(text, Math.random().toFixed(6).slice(-6));

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

        if (result && result.affectedRows > 0) {
            res.json({
                ...BaseStdResponse.OK,
                data: {
                    uuid: rows[0].uuid,
                    username: rows[0].username,
                    wxid: rows[0].wxid,
                    email: rows[0].email,
                    avatar: rows[0].avatar,
                    session
                }
            });
            await Redis.del(`captcha:${id}`);
            await sendEmail(rows[0].email, '账户登录提醒', `您的Double_X考勤账号${rows[0].username}在${new Date().toLocaleString()}登录了Double_X考勤系统，登录ip：${req.headers['x-forwarded-for'] || req.ip}`);
        } else {
            res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '登录失败！' });
        }
    }
}

module.exports.Register = Register;
