const GetToken = require('./GetToken');
const axios = require('axios');
const path = require('path');
const Logger = require('../../lib/Logger');

const logger = new Logger(path.join(__dirname, '../../logs/WXWork.log'), 'INFO');

async function getUserID(code) {

    const token = await GetToken();
    if (!token)
        return { success: false, msg: '获取企微token失败！请联系管理员' };

    let response = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=${token}&code=${code}`);
    if (!response || response.data.errcode !== 0 || !response.data.userid) {
        logger.error(`获取企微用户信息失败！原因：${response.data.errmsg}`)
        return { success: false, msg: '获取企微用户信息失败！请联系管理员' };
    }

    return { success: true, userid: response.data.userid };
}

async function getUserInfo(userid) {

    const token = await GetToken();
    if (!token)
        return { success: false, msg: '获取企微token失败！请联系管理员' };

    let response = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=${token}&userid=${userid}`);
    if (!response || response.data.errcode !== 0 || !response.data.name) {
        logger.error(`获取企微用户信息失败！原因：${response.data.errmsg}`)
        return { success: false, msg: '获取企微用户信息失败！请联系管理员' };
    }

    let name = response.data.name;
    let avatar = response.data.avatar ? response.data.avatar : '';

    return { success: true, name, avatar }
}

module.exports = {
    getUserID,
    getUserInfo
}