import { __awaiter } from "tslib";
import { LoginSource } from './types';
/**
 * 判断是否在企微内部打开
 */
export const inWxWork = () => {
    const ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('wxwork') !== -1) {
        return true;
    }
    return false;
};
export function getJson(url, data = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const response = yield fetch(url, data);
        return yield response.json();
    });
}
export function getConfig(router) {
    return __awaiter(this, void 0, void 0, function* () {
        const source = router.getUrlParams('source');
        const staticOrigin = getStaticOrigin(router);
        try {
            let config;
            if (source === LoginSource.PORTAL) {
                // const systemConfig = await getJson(`${staticOrigin}/adminportal/systemConfig.json`);
                // config = formatPortalConfig(systemConfig[getPortalEnvType()]);
            }
            else if (source === LoginSource.APIS) {
                // config = APIS_CONFIG;
            }
            else {
                const version = router.getUrlParams('config_version') || '';
                const hashVersion = version.split('_')[0];
                const path = `${router.getUrlParams('app_id')}/${getConfigName(version)}.json`;
                if (hashVersion === 'v1') {
                    config = yield getJson(`${staticOrigin}/__auth/app/${path}`);
                }
                else {
                    // 兼容老版本配置存储规则
                    config = yield getJson(`${staticOrigin}/${path}`);
                }
                return config;
            }
            throw new Error(`加载配置失败 source error ${source}`);
        }
        catch (e) {
            throw new Error('加载配置失败');
        }
    });
}
let staticOrigin;
export function getStaticOrigin(router) {
    if (!staticOrigin) {
        staticOrigin = location.origin;
        try {
            if (router.getUrlParams('s_domain')) {
                const url = new URL(`https://${router.getUrlParams('s_domain')}`);
                if (url.origin.endsWith('.tcloudbaseapp.com') || url.origin === '127.0.0.1') {
                    staticOrigin = url.origin;
                }
            }
        }
        catch (e) {
            throw new Error('s_domain参数错误');
        }
    }
    return staticOrigin;
}
export function getConfigName(version) {
    return `login.config${version ? `.${version}` : ''}`;
}
