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';
import { getViewComponentName } from '@/util';

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);
    const viewComponentName = ref('');

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

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