import { IViewProvider } from '@ibiz-template/controller';
import { ModelUtil } from '@ibiz-template/model';
import { useNamespace } from '@ibiz-template/vue-util';
import { computed, defineComponent, PropType, ref } from 'vue';
import '@ibiz-template/theme/style/components/view-shell/view-shell.scss';
import { IModal } from '@ibiz-template/runtime';

export const ViewShell = defineComponent({
  name: 'ViewShell',
  props: {
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams> },
    modal: { type: Object as PropType<IModal> },
    isRouter: { type: Boolean },
    modelPath: { type: String, required: true },
    noLoadDefault: { type: Boolean, default: false },
  },
  setup(props) {
    const provider = ref<IViewProvider>();
    ModelUtil.getViewModel(props.modelPath, props.context).then(
      async viewModel => {
        provider.value = await ibiz.register.view.get(viewModel.source);
      },
    );
    const ns = useNamespace('view-shell');

    // 路由绘制的视图，添加一个上下文isRouter
    const cloneContext = computed(() => {
      const temp = props.context.clone();
      temp.isRouter = props.isRouter === true;
      return temp;
    });
    return { ns, provider, cloneContext };
  },
  render(h) {
    if (this.provider) {
      const opts = {
        attrs: {
          ...this.$props,
          ...this.$attrs,
          context: this.cloneContext,
        },
        on: this.$listeners,
      };
      return h('AppTransition', {}, [h(this.provider.component, opts)]);
    }
    return (
      <div class={this.ns.b()}>
        <i-spin size='large' fix></i-spin>
      </div>
    );
  },
});
