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) => {
      options[optionName] = data?.Items[0]?.Config;
    });
  }
  return '';
}
export function initGlobalVar({
  common,
  state,
  computedFuncs,
  dataset = undefined,
}) {
  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;
  }
}
export function removeGlobalVar() {
  isInit = false;
  runtime['$$global'] = undefined;
}
