// import { onMounted, ref, unref } from 'vue'

import consola from 'consola';
import { KanKanInstance } from '/#/sdk';
import browser from '/@/utils/browser';

const instance = (window as any).KanKan;
let app: KanKanInstance;
let _num: string;
const deferred = instance.Deferred();
interface appOptions {
  region?: string;
  resource?: string;
  server?: string;
  dom: HTMLElement;
  mobile?: boolean;
  num: string;
}
// onMounted(() => {

// })

// let deferred = KanKan.Deferred()
export function createApp(options: appOptions): Promise<KanKanInstance> {
  if (!options?.region) {
    options.region = import.meta.env.VITE_APP_REGION_URL;
  }
  if (!options?.resource) {
    options.resource = import.meta.env.VITE_APP_RESOURCE_URL;
  }
  if (!options?.server) {
    options.server = '/';
  }
  console.log('options', options);

  _num = options.num;

  if (!instance) {
    consola.error('kankan SDK 没有引入!');
  }
  const _app = new instance(options);
  deferred.resolve(_app);
  (window as any).__sdk = _app;
  if (browser.isMobile()) {
    document.body.setAttribute('is-mobile', 'true');
  }

  app = _app;
  return Promise.resolve(app);
}

export function useApp(): Promise<KanKanInstance> {
  if (app) {
    return Promise.resolve(app);
  }
  return deferred;
}
export function getApp(): KanKanInstance {
  return app;
}

export function getNum(): string {
  return _num;
}
