const md5 = require("md5");
const API = require("../../lib/API");
const { BaseStdResponse } = require("../../BaseStdResponse");
const db = require("../../plugin/DataBase/db");
const {
    getUserInfo,
    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 uuid, username, avatar FROM users WHERE wxid = ?';
            let rows = await db.query(sql, [wxid]);

            let result, uuid, username, avatar;
            if (rows.length > 0) {
                // 用户存在，更新 session
                ({ uuid, username, avatar } = rows[0]);
                avatar = avatar && avatar != '' ? avatar : 'https://git.vthc.cn/avatars/1';
                const updateQuery = 'UPDATE users SET session = ? WHERE wxid = ?';
                result = await db.query(updateQuery, [session, wxid]); 
            } else {
                // 用户不存在，注册用户
                const infoRes = await getUserInfo(wxid);
                if (!infoRes || !infoRes.success) {
                    return res.json({ ...BaseStdResponse.ERR, endpoint: 7894198, msg: `登录失败！${infoRes.msg}` });
                }

                ({ name: username, avatar } = infoRes);

                // TODO 企微扫码登录不会返回用户头像 这里疏忽了 后面再改 
                avatar = avatar && avatar != '' ? avatar : 'https://git.vthc.cn/avatars/1';
                uuid = md5(Date.now() + wxid + code);

                // 查询users表中是否有用户
                const userCountQuery = 'SELECT COUNT(*) as count FROM users';
                const [userCountResult] = await db.query(userCountQuery);
                const userCount = userCountResult.count;

                // 如果是第一个注册的用户 授予admin权限
                const admin = userCount === 0 ? 1 : 0;

                const insertQuery = 'INSERT INTO users (uuid, username, wxid, avatar, session, admin) VALUES (?, ?, ?, ?, ?, ?)';
                result = await db.query(insertQuery, [uuid, username, wxid, avatar, session, admin]);
            }

            if (result && result.affectedRows > 0) {
                return res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        uuid,
                        username,
                        wxid,
                        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;
