import * as sdk from '@tcwd/weapps-sdk';
import { createComputed } from 'utils';
import store, { subPackageName } from '../store';
import computed from '../store/computed';
import common from './common';
import { formatDate } from '../utils/date';
import { getter, setter, _isMobile } from '../utils';
import actionMap from './material-actions';
import { scanCodeApi } from '../utils/scan-code-action';
import { createWebApp, ACTIONS_KEY, ROUTER_KEY } from '@cloudbase/weda-client';
import { createDataset, EXTRA_API } from '../datasources/index'

const mainAppKey = '__weappsMainApp';
const appGlobal = process.env.isMiniprogram ? getApp() : window;

export const app = createGlboalApi();
export const $page = createPageApi();

export function setCurrentPage(pageCtx) {
  Object.assign($page, pageCtx);
}

function createGlboalApi() {
  const mpApp = createWebApp();
  const globalAPI = {
    id: '<%= appId %>',
    domain: '<%= domain %>',
    formActions: {},
    pages: {},
    session: {
      configure: sdk.configure,
      request: sdk.request,
      getSessionId: sdk.getSessionId,
    },
    state: store,
    computed: createComputed(computed.global),
    common,
    ...mpApp
    // ... other sdk apis & apis from mp
  }; // The global api exposed to lowcode

  const dataset = createDataset('$global');
  globalAPI.dataset = dataset;
  globalAPI.state.dataset = dataset;
  globalAPI.setState = (userSetState) => {
    Object.keys(userSetState).forEach((keyPath) => {
      globalAPI.utils.set(
        globalAPI.dataset.state,
        keyPath,
        userSetState[keyPath]
      );
    });
  };
  /**
   * 内部通用的设置状态变量值的方法
   *  varPath 结构为 $global.<变量名> 即全局变量
   *                $page.<变量名>  即当前页面变量
   *                <pageId>.<变量名> 指定页面 pageId 的变量 (应当避免修改非当前页面的变量值)
   */
  globalAPI._setStateVal = (config) => {
    EXTRA_API.setState(config.varPath, config.val);
  };
  if (subPackageName) {
    // is sub app
    globalAPI.mainApp = appGlobal[mainAppKey];
  } else {
    // is mainApp
    appGlobal.app = globalAPI;
    appGlobal[mainAppKey] = globalAPI;
  }

  // 挂运营平台上报对象到app里
  globalAPI.yyptReport = appGlobal.yyptReport;

  // # expose some sdk modules
  const sdkModsIncluded = ['flow', 'getPageOptions', 'getLaunchOptions'];
  sdkModsIncluded.forEach((key) => {
    globalAPI[key] = sdk[key];
  });

  return globalAPI;
}
function createPageApi() {
  const $page = {
    state: {},
    computed: {},
    handler: {},
    props: {},
    widgets: {},
    // 页面数据源变量存储位置
    dataVar: {},
  };
  return $page;
}

// 分app 和 wx 挂载app
export const mountAPIs = (sdks) => {
  Object.keys(sdks).forEach((item) => {
    let action = sdks[item];
    if (!(item in ACTIONS_KEY) && !(item in ROUTER_KEY)) {
      app[item] = action;
    }
  });
  return app;
};
