import {
  filterCustomSwitchKey,
  filterLeftMountedKey,
  filterSecondMountedKey,
  filterSecondOpenKey
} from '../utils/key';
import {
  defineComponent,
  inject,
  PropType,
  provide,
  ref,
  Ref,
  toRef
} from 'vue';

/**
 * 判断当前是否有挂载 filter-second 组件的行为
 */
const Filter = defineComponent({
  inheritAttrs: false,
  props: {
    role: {
      type: String as PropType<'' | 'tabs'>,
      default: ''
    }
  },
  setup(props, { slots, attrs }) {
    const filterLeftMounted = inject<Ref<boolean>>(filterLeftMountedKey)!;
    const renderDefault = () => {
      /* 如果是左右布局的场景就直接渲染默认的 slots */
      return filterLeftMounted.value ? (
        slots.default?.()
      ) : (
        // 不是左右布局，直接渲染过滤核心
        <FilterCore {...attrs} v-slots={slots} />
      );
    };

    const render = () => {
      let dom = null;
      switch (props.role) {
        case 'tabs':
          dom = <a-form layout="inline">{slots.default?.()}</a-form>;
          break;
        default:
          dom = renderDefault();
          break;
      }
      return dom;
    };

    return () => (
      <div
        class={`table-layout__filter flex w-full ${
          props.role !== ''
            ? `table-layout__filter-render-custom ${props.role}`
            : ''
        }`}
      >
        {render()}
      </div>
    );
  }
});

/**
 * 搜索栏核心
 */
const FilterCore = defineComponent({
  setup(props, { slots }) {
    const filterSecondMounted = inject<Ref<boolean>>(filterSecondMountedKey)!;
    const filterSecondOpen = inject<Ref<boolean>>(filterSecondOpenKey)!;
    const filterCustomSwitch = inject<Ref<boolean>>(filterCustomSwitchKey)!;

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

    return () => (
      <a-form layout="inline">
        {slots.default?.()}
        {/* 外部自定义按钮控制二级过滤栏，这里就不再显示 */}
        {filterSecondMounted.value && !filterCustomSwitch.value ? (
          <a-button onClick={handleToggle}>
            {filterSecondOpen.value ? '收起' : ''}更多条件
          </a-button>
        ) : null}
      </a-form>
    );
  }
});

/**
 * 搜索栏左
 */
const FilterLeft = defineComponent({
  inheritAttrs: false,
  setup(props, { slots, attrs }) {
    const filterLeftMounted = inject<Ref<boolean>>(filterLeftMountedKey)!;
    filterLeftMounted.value = true;
    return () => (
      <div class="table-layout__filter-left flex-1">
        <FilterCore {...attrs} v-slots={slots} />
      </div>
    );
  }
});

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

export { Filter, FilterLeft, FilterRight };
