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

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

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

        // 检查 session 是否有效
        if (!await AccessControl.checkSession(uuid, session)) {
            return res.json({
                ...BaseStdResponse.ACCESS_DENIED,
                endpoint: 48153145
            });
        }

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

            const wxid = idRes.userid;

            let sql = 'UPDATE users SET wxid = ? WHERE uuid = ?';
            let result = await db.query(sql, [wxid, uuid]);
            if (!result || result.affectedRows !== 1)
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR
                })

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

            if (rows.length > 0) {
                let { id, uuid, username, avatar, email, session } = rows[0];
                res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        uuid,
                        username,
                        wxid,
                        email,
                        avatar,
                        session
                    }
                });
                
            } else {
                return res.json({
                    ...BaseStdResponse.USER_NOT_EXISTS
                })
            }
        } catch (error) {
            this.logger.error(`绑定企业微信失败!${error.stack}`)
            return res.json({ ...BaseStdResponse.ERR, endpoint: 7894379, msg: '绑定失败！' });
        }
    }
}

module.exports.BindWXWork = BindWXWork;
