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

let token = '';
let tokenExpiresAt = 0; // 用于跟踪token的过期时间
const logger = new Logger(path.join(__dirname, '../../logs/WXWork.log'), 'INFO');

const GetToken = async () => {
    const currentTime = Date.now();

    // 如果 token 未过期，直接返回 token
    if (token && tokenExpiresAt > currentTime) {
        logger.info('返回已有企业微信token');
        return Promise.resolve(token);
    }

    // 否则重新获取 token
    try {
        logger.info('企业微信token不存在或已过期，正在重新获取token');
        const response = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${config.wxwork.corpid}&corpsecret=${config.wxwork.corpsecret}`);

        const body = response.data;

        if (body.errcode === 0) {
            token = body.access_token;
            // 设置新的过期时间
            tokenExpiresAt = currentTime + (body.expires_in * 1000);
            logger.info('获取企业微信 token 成功！');
            return token;
        } else {
            logger.error(`获取企业微信 token 失败！原因：${body.errmsg}`);
            throw new Error(body.errmsg);
        }
    } catch (error) {
        logger.error(`获取企业微信 token 失败！原因：${error.stack}`);
        throw error;
    }
};

module.exports = GetToken;
