import { computed, defineComponent, PropType, inject, Ref, ref } from 'vue';
import { drawerKey, tableMountedKey } from '../utils/key';

const Table = defineComponent({
  props: {
    // 表格缩小时，需要显示的列索引
    visibleColumns: {
      type: Array as PropType<number[]>,
      default: () => [0, 1, 2]
    },
    // 表格缩小时，需要显示的操作列，可以传入 'last' 或者 具体的列索引
    visibleAction: {
      type: [Number, String]
    },
    // 表格缩小时，需要显示的操作列里的 button 索引
    visibleButton: {
      type: Number
    }
  },
  setup(props, { slots }) {
    const drawer = inject<Ref<boolean>>(drawerKey)!;

    // 通知 TlMain 这个组件被挂载
    const tableMounted = inject<Ref<boolean>>(tableMountedKey);
    // 需要判空
    if (tableMounted) tableMounted.value = true;

    const tlTable = ref();

    const clsVisibleColumns = computed(() => {
      const cls = props.visibleColumns
        .map(_ => `tl-visible-column--index-${_ + 1}`)
        .join(' ');
      return `${drawer.value ? `${cls}` : ''}`;
    });

    /**
     * 当显示抽屉时，指定要显示的操作列
     */
    const clsVisibleAction = computed(() => {
      if (drawer.value) {
        if (tlTable.value) {
          // .ant-table-cell-scrollbar（antd 用来处理表头对齐的fix手段）可能会没有这个元素，需要判断
          const $scrollbar = tlTable.value.querySelector(
            '.ant-table-thead > tr th.ant-table-cell-scrollbar'
          );
          // 当存在这一列 scrollbar 时且外部传递位置为 last 时，要切换 tr th:last-of-type 成 tr th:nth-last-of-type(2)
          if (props.visibleAction === 'last') {
            if ($scrollbar) {
              return 'tl-visible-action--index-nth-last-of-type-2';
            } else {
              return 'tl-visible-action--index-last';
            }
          } else {
            return `tl-visible-action--index-${
              (props.visibleAction as number) + 1
            }`;
          }
        }
        return '';
      }
      return '';
    });

    const clsVisibleButton = computed(() => {
      const cls = `tl-visible-button--index-${props.visibleButton! + 1}`;
      return `${
        drawer.value &&
        (props.visibleButton !== undefined || props.visibleButton !== null)
          ? `${cls}`
          : ''
      }`;
    });

    const clsTableWidthAuto = computed(() => {
      if (drawer.value) {
        if (tlTable.value) {
          // table 有设置了 :scroll 属性的才会有这个元素 .ant-table-body > table
          const $table = tlTable.value.querySelector('.ant-table-body > table');
          // 被设置了宽度，就改成 auto
          // @ts-ignore
          return $table?.style?.width ? 'tl-table-width-auto' : '';
        }
        return '';
      }
      return '';
    });

    return () => (
      <div
        ref={tlTable}
        class={`table-layout__table flex flex-col flex-1 ${clsVisibleColumns.value} ${clsVisibleAction.value} ${clsVisibleButton.value} ${clsTableWidthAuto.value}`}
      >
        {slots.default?.()}
      </div>
    );
  }
});

export { Table };
