import { defineComponent, getCurrentInstance, ref } from 'vue';
import { ModelUtil } from '@ibiz-template/model';
import {
  IRouteViewData,
  parseRouteViewData,
  useRoute,
  useRouter,
} from '@ibiz-template/vue-util';
import { Route } from 'vue-router';

export default defineComponent({
  name: 'RouterShell',
  props: {
    level: {
      type: Number,
      default: 0,
    },
  },
  setup(props, ctx) {
    const { proxy } = getCurrentInstance()!;
    const route = useRoute(proxy) as Route;
    const router = useRouter(proxy);
    const viewData = ref<IRouteViewData>({});
    const isLoaded = ref(false);

    // 根据应用模型解析视图参数
    ModelUtil.getModelService().then(async service => {
      const appModel = service.app;
      if (appModel) {
        // 获取视图
        try {
          viewData.value = parseRouteViewData(appModel, route, props.level);
          // 确定视图组件
          isLoaded.value = true;
          ctx.emit('viewFound', { modelPath: viewData.value.viewPath });
        } catch (error) {
          router.replace(`/${route.params.view1}/404`);
        }
      }
    });

    // 视图初始化事件，往上抛
    const onNeuronInit = (...args: IData[]) => {
      ctx.emit('neuronInit', ...args);
    };
    return {
      route,
      viewData,
      isLoaded,
      onNeuronInit,
    };
  },
  render(h) {
    if (!this.isLoaded) {
      return null;
    }
    return h('ViewShell', {
      props: {
        context: this.viewData.context,
        params: this.viewData.params,
        modelPath: this.viewData.viewPath,
      },
      on: {
        neuronInit: this.onNeuronInit,
      },
    });
  },
});
