import { app } from '../app/global-api';
import { createComputed } from './computed';
import { observable } from 'mobx';
import { _WEDA_CLOUD_SDK as WEDA_CLOUD_SDK, _getGeneralOptions as getGeneralOptions } from '@cloudbase/weda-client';
import { runtime } from './adapter';
const { createDataset } = WEDA_CLOUD_SDK;
// 防止页面重复引用
let isInit = false;
let options = observable({});
let loading = {};
export function getEnumOptions(optionName) {
    if (options[optionName]) {
        return options[optionName];
    }
    if (!loading[optionName]) {
        loading[optionName] = true;
        getGeneralOptions(optionName).then((data) => {
            var _a;
            options[optionName] = (_a = data === null || data === void 0 ? void 0 : data.Items[0]) === null || _a === void 0 ? void 0 : _a.Config;
        });
    }
    return '';
}
export function initGlobalVar({ common, state, computedFuncs, dataset = undefined }, initAppAPI = (app) => { }) {
    if (!isInit) {
        runtime['$$global'] = runtime['$$global'] || {};
        app.common = common;
        app.state = observable(state);
        app.computed = createComputed(computedFuncs);
        const _dataset = dataset || createDataset('$global');
        app.dataset = _dataset;
        app.state.dataset = _dataset;
        app.enumOptions = options;
        /**
         * 对 app 上方法进行覆盖
         */
        initAppAPI === null || initAppAPI === void 0 ? void 0 : initAppAPI(app);
        /**
         * 覆盖之后使用新方法更新值
         */
        const { isMobile, $w } = (app === null || app === void 0 ? void 0 : app.__internal__) || {};
        // 应用信息
        if ($w === null || $w === void 0 ? void 0 : $w.wedaContext) {
            const type = (isMobile === null || isMobile === void 0 ? void 0 : isMobile()) ? 'MOBILEWEB' : 'PCWEB';
            $w.wedaContext.platforms = ($w.wedaContext.platforms
                ? $w.wedaContext.platforms.filter((item) => item !== 'MOBILEWEB' && item !== 'PCWEB')
                : ['WEB']).concat([type]);
        }
    }
}
export function removeGlobalVar() {
    isInit = false;
    runtime['$$global'] = undefined;
}
