import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  inject,
  Ref,
  ref
} from 'vue';

const Filter = defineComponent({
  setup(props, { slots }) {
    // 左右布局模式或者普通模式
    const mode = ref<'lr' | ''>('lr');
    const hasTlFilterSecond = () => {
      const instance = getCurrentInstance();
      // @ts-ignore
      const children = instance?.subTree?.children?.[0]?.children;
      mode.value = children?.find((_: any) => _.type?.name === 'TlFilterLeft')
        ? 'lr'
        : '';
    };
    onMounted(() => {
      hasTlFilterSecond();
    });

    return () => (
      <div class="table-layout__filter flex">
        {mode.value === 'lr' ? (
          slots.default?.()
        ) : (
          <FilterCore v-slots={slots} />
        )}
      </div>
    );
  }
});

/**
 * 搜索栏核心
 */
const FilterCore = defineComponent({
  setup(props, { slots }) {
    const more = inject<Ref<boolean>>('tl-more')!;
    const open = inject<Ref<boolean>>('tl-open')!;
    const updateOpen = inject<(val: boolean) => void>('tl-updateOpen')!;

    const handleToggle = () => {
      updateOpen(!open.value);
    };

    return () => (
      <a-form layout="inline">
        {slots.default?.()}
        {more.value ? (
          <a-button onClick={handleToggle}>
            {open.value ? '收起' : ''}更多条件
          </a-button>
        ) : null}
      </a-form>
    );
  }
});

/**
 * 搜索栏左
 */
const FilterLeft = defineComponent({
  setup(props, { slots }) {
    return () => (
      <div class="table-layout__filter-left flex-1">
        <FilterCore>{slots.default?.()}</FilterCore>
      </div>
    );
  }
});

/**
 * 搜索栏右，一般放置一些按钮如：导出
 */
const FilterRight = defineComponent({
  setup(props, { slots }) {
    return () => (
      <div class="table-layout__filter-right">{slots.default?.()}</div>
    );
  }
});

export { Filter, FilterLeft, FilterRight };
