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

// 通过企业微信更新用户信息 已废弃
class UpdateInfo extends API {
    constructor() {
        super();
        this.setMethod("POST");
        this.setPath("/User/UpdateInfo");
    }

    async onRequest(req, res) {
        let { 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 = 'SELECT wxid FROM users WHERE uuid = ?';
            let { rows } = await db.query(sql, [uuid]);

            if (rows.length !== 1 || !rows[0].wxid || !rows[0].session) 
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894188, msg: `更新失败！` });
            if(rows[0].wxid !== wxid)
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894188, msg: `更新失败！当前登录的企业微信账号与绑定的企业微信账号不一致` });

            const infoRes = await getUserInfo(wxid);
            if (!infoRes || !infoRes.success) {
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894198, msg: `更新失败！${infoRes.msg}` });
            }

            let { name: username, avatar } = infoRes;

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

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

            if (result && result.affectedRows > 0) {
                return res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        uuid,
                        username,
                        wxid,
                        avatar,
                        session
                    }
                });
            } else {
                return res.json({ ...BaseStdResponse.ERR, endpoint: 7894377, msg: '更新失败！' });
            }
        } catch (error) {
            this.logger.error(`更新个人信息时出错！${error.stack}`);
            return res.json({ ...BaseStdResponse.ERR, endpoint: 7894377, msg: '更新失败！' });
        }
    }
}

module.exports.UpdateInfo = UpdateInfo;
