const md5 = require("md5");
const API = require("../../../lib/API");
const { BaseStdResponse } = require("../../../BaseStdResponse");
const db = require("../../../plugin/DataBase/db");
const { getUserID } = require("../../../plugin/WXWork/GetInfo");

class WXWorkLogin extends API {
    constructor() {
        super();
        this.setMethod("POST");
        this.setPath("/User/WXWorkLogin");
    }

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

    async onRequest(req, res) {
        const { code } = req.body;
        if (!code) {
            res.json({ ...BaseStdResponse.MISSING_PARAMETER, endpoint: 7841686 });
            return;
        }

        try {
            const idRes = await getUserID(code);
            if (!idRes || !idRes.success) {
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894377, msg: `获取企微信息失败！${idRes.msg}` });
            }

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

            let sql = 'SELECT id, uuid, username, avatar, email FROM users WHERE wxid = ?';
            let rows = await db.query(sql, [wxid]);

            if (!rows || rows.length === 0)
                return res.json({
                    ...BaseStdResponse.USER_NOT_EXISTS
                })

            let { id, uuid, username, avatar, email } = rows[0];

            const updateQuery = 'UPDATE users SET session = ? WHERE id = ?';
            const result = await db.query(updateQuery, [session, id]);

            if (result && result.affectedRows > 0) {
                return res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        uuid,
                        username,
                        wxid,
                        email,
                        avatar,
                        session
                    }
                });
            } else {
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '登录失败！' });
            }
        } catch (error) {
            this.logger.error(`企业微信登录失败！${error.stack}`)
            return res.json({ ...BaseStdResponse.ERR, endpoint: 7894379, msg: '登录失败！' });
        }
    }
}

module.exports.WXWorkLogin = WXWorkLogin;
