import { MDViewController } from '@ibiz-template/controller';
import { defineComponent, PropType } from 'vue';

export const MDViewBase = defineComponent({
  props: {
    controller: {
      type: Object as PropType<MDViewController>,
      required: true,
    },
  },
  setup() {
    return {};
  },
  render(h) {
    const c = this.controller;

    // 外面的插槽同样传给view-layout
    const inheritSlots: IData = {};
    Object.keys(this.$scopedSlots).forEach(key => {
      inheritSlots[key] = (arg: IData) => this.$scopedSlots[key]!(arg);
    });

    const slots: IData = {
      quickSearch: () => {
        if (c.complete && c.model.source.enableQuickSearch) {
          return (
            <quick-search
              value={c.query}
              viewMode={c.modal.mode}
              placeholder={c.model.placeholder}
              on-update={(val: string) => {
                c.query = val;
              }}
              on-search={() => c.onSearch()}
            ></quick-search>
          );
        }
      },
    };
    if (c.showSearchForm) {
      const { searchForm } = this.controller.model;
      slots.searchForm = () => {
        if (c.complete && searchForm) {
          if (c.providers[searchForm.name]) {
            return h(c.providers[searchForm.name].component, {
              props: {
                controller: c,
                context: c.context,
                params: c.params,
                modelData: searchForm,
              },
              on: {
                neuronInit: c.nerve.onNeuronInit(searchForm.source.name),
              },
            });
          }
          return (
            <search-form-control
              v-show={c.showSearchForm}
              modelData={c.model.searchForm}
              context={c.context}
              params={c.params}
              controller={c}
              on-neuronInit={c.nerve.onNeuronInit(searchForm.source.name)}
            ></search-form-control>
          );
        }
      };
    }

    return (
      <view-base
        controller={c}
        scopedSlots={{
          ...slots,
          ...inheritSlots,
        }}
      />
    );
  },
});
