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

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

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

    async onRequest(req, res) {
        let { uuid, session, email, code } = req.body;

        if ([uuid, session, email, code].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
            });
        }

        const VerifyCode = await Redis.get(`email:${email}`);
        if (!VerifyCode || VerifyCode != code)
            return res.json({
                ...BaseStdResponse.SMS_CHECK_FAIL,
                msg: '邮箱验证码输入错误或已过期'
            })

        let sql = 'SELECT email FROM users WHERE email = ?';
        let EmailRows = await db.query(sql, [email]);
        if (EmailRows.length > 0)
            return res.json({
                ...BaseStdResponse.USER_ALREADY_EXISTS,
                msg: '该邮箱已被注册！'
            })

        sql = 'UPDATE users SET email = ? WHERE uuid = ?';
        let result = await db.query(sql, [email, uuid]);

        if (result && result.affectedRows > 0) {
            // 注册成功后删除邮箱对应的验证码 避免注册失败后重复获取
            await Redis.del(`email:${email}`);

            sql = 'SELECT username, wxid, avatar FROM users WHERE uuid = ?';
            let rows = await db.query(sql, [uuid]);
            if(!rows || rows.length === 0)
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR
                })

            res.json({
                ...BaseStdResponse.OK,
                data: {
                    uuid,
                    username: rows[0].username,
                    wxid: rows[0].wxid,
                    email,
                    avatar: rows[0].avatar,
                    session
                }
            });
            await sendEmail(email, '换绑邮箱成功', `您的Double_X考勤账号换绑邮箱成功，操作时间：${new Date().toLocaleString()}`);
        } else {
            res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '操作失败！' });
        }
    }
}

module.exports.BindEmail = BindEmail;
