const { v4: uuidv4 } = require('uuid')
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')

// 用户登录
class Login extends API {
    constructor() {
        super();

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

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

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

        password = atob(password);

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

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

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

        const session = uuidv4()
        await Redis.set(`userSession:${rows[0].uuid}`, session, {
            EX: 2592000
        })

        res.json({
            ...BaseStdResponse.OK,
            data: {
                uuid: rows[0].uuid,
                username: rows[0].username,
                session,
                roles: rows[0].permission || [],
                lepao_count: Number(rows[0].lepao_count) || 0,
                avatar: rows[0].avatar,
                email: rows[0].email
            }
        })

        const time = new Date().getTime()
        sql = 'UPDATE users SET lastTime = ? WHERE id = ?';
        await db.query(sql, [time, rows[0].id]);
    }
}

module.exports.Login = Login;
