<script lang="ts">
import type { DslDefinition } from '@oinone/kunlun-dsl';
import { type ActiveRecord, type ActiveRecords, type Pagination, translateValueByKey } from '@oinone/kunlun-engine';
import { EDirection, ISort } from '@oinone/kunlun-service';
import type { ReturnPromise } from '@oinone/kunlun-shared';
import { DEFAULT_PREFIX } from '@oinone/kunlun-theme';
import {
  type ActiveEditorContext,
  type CheckedChangeEvent,
  GROUP_TREE_KEY,
  OioColumn,
  OioTable,
  type OioTableInstance,
  type RadioChangeEvent,
  type RowContext,
  type SortChangeEvent,
  TableEditorCloseTrigger,
  TableEditorMode,
  TableEditorTrigger,
  TableRowClickMode,
  TableSelectTrigger,
  TableSize,
  useVxeCheckboxCell,
  useVxeCheckboxHeader,
  type VxeCheckboxCellRenderBodyParams,
  type VxeCheckboxHeaderRenderBodyParams,
  type VxeTableActiveEditorEventContext,
  VxeTableHelper
} from '@oinone/kunlun-vue-ui';
import {
  ListPaginationStyle,
  ListSelectMode,
  OioPagination,
  OioSpin,
  OioTooltip,
  PropRecordHelper,
  StyleHelper
} from '@oinone/kunlun-vue-ui-antd';
import { DslRender } from '@oinone/kunlun-vue-widget';
import { debounce } from 'lodash-es';
import {
  computed,
  createVNode,
  defineComponent,
  Fragment,
  nextTick,
  onActivated,
  onBeforeUnmount,
  onMounted,
  type PropType,
  ref,
  type Slot,
  type VNode,
  watch
} from 'vue';
import { VxeTableDefines, type VxeTablePropTypes } from 'vxe-table';
import { ManualWidget } from '../../basic';
import { TableLineHeightEnum, type UserTablePrefer } from '../../typing';
import DefaultTableClickContainer from './DefaultTableClickContainer.vue';
import DefaultTableFooterOperator from './DefaultTableFooterOperator.vue';
import DefaultTableGroupCollapse from './DefaultTableGroupCollapse.vue';

const SortDirections = {
  desc: EDirection.DESC,
  asc: EDirection.ASC
};

function sortColumnsByUserPrefer(
  columns: VxeTableDefines.ColumnInfo[],
  fieldOrder: string[]
): VxeTableDefines.ColumnInfo[] {
  if (fieldOrder && fieldOrder.length) {
    /**
     * 为了性能考虑, 此处的分类方式将假设字段全部在中间
     */
    const leftColumns: VxeTableDefines.ColumnInfo[] = [];
    const fieldColumns: { field: string; orderIndex: number; column: VxeTableDefines.ColumnInfo }[] = [];
    const rightColumns: VxeTableDefines.ColumnInfo[] = [];
    let isHandleFieldColumn = false;
    for (const column of columns) {
      const { field } = column;
      if (field) {
        isHandleFieldColumn = true;
        let orderIndex = fieldOrder.findIndex((v) => v === field);
        if (orderIndex === -1) {
          orderIndex = fieldColumns[fieldColumns.length - 1]?.orderIndex;
          if (orderIndex == null) {
            orderIndex = 0;
          }
        }
        fieldColumns.push({
          field,
          orderIndex,
          column
        });
      } else if (isHandleFieldColumn) {
        rightColumns.push(column);
      } else {
        leftColumns.push(column);
      }
    }
    return [
      ...leftColumns,
      ...fieldColumns
        .sort((a, b) => {
          if (a.orderIndex === -1) {
            return 1;
          }
          if (b.orderIndex === -1) {
            return -1;
          }
          return a.orderIndex - b.orderIndex;
        })
        .map((v) => v.column),
      ...rightColumns
    ];
  }
  return columns;
}

export default defineComponent({
  name: 'DefaultTable',
  mixins: [ManualWidget],
  components: {
    OioTable,
    OioColumn,
    OioSpin,
    OioPagination,
    OioTooltip,
    DefaultTableFooterOperator,
    DefaultTableGroupCollapse,
    DefaultTableClickContainer
  },
  inheritAttrs: false,
  props: {
    setTableInstance: {
      type: Function as PropType<(tableInstance: OioTableInstance | undefined) => void>
    },
    loading: {
      type: Boolean,
      default: undefined
    },
    template: {
      type: Object as PropType<DslDefinition>
    },
    dataSource: {
      type: Array as PropType<ActiveRecord[]>
    },
    showDataSource: {
      type: Array as PropType<ActiveRecord[]>
    },
    height: {
      type: String
    },
    minHeight: {
      type: String
    },
    maxHeight: {
      type: String
    },
    rowClassName: {
      type: [String, Function] as PropType<VxeTablePropTypes.RowClassName>
    },
    cellClassName: {
      type: [String, Function] as PropType<VxeTablePropTypes.CellClassName>
    },
    headerRowClassName: {
      type: [String, Function] as PropType<VxeTablePropTypes.HeaderRowClassName>
    },
    headerCellClassName: {
      type: [String, Function] as PropType<VxeTablePropTypes.HeaderCellClassName>
    },
    footerRowClassName: {
      type: [String, Function] as PropType<VxeTablePropTypes.FooterRowClassName>
    },
    footerCellClassName: {
      type: [String, Function] as PropType<VxeTablePropTypes.FooterCellClassName>
    },
    /**
     * 给行附加样式，也可以是函数
     */
    rowStyle: {
      type: [Object, Function] as PropType<VxeTablePropTypes.RowStyle>
    },
    /**
     * 给表头行附加样式
     */
    headerRowStyle: {
      type: [Object, Function] as PropType<VxeTablePropTypes.HeaderRowStyle>
    },
    /**
     * 给单元格附加样式
     */
    cellStyle: {
      type: [Object, Function] as PropType<VxeTablePropTypes.CellStyle>
    },
    /**
     * 给表头单元格附加样式
     */
    headerCellStyle: {
      type: [Object, Function] as PropType<VxeTablePropTypes.HeaderCellStyle>
    },
    pagination: {
      type: Object as PropType<Pagination>
    },
    showPagination: {
      type: Boolean,
      default: undefined
    },
    paginationStyle: {
      type: String as PropType<ListPaginationStyle>
    },
    onPaginationChange: {
      type: Function as PropType<(currentPage: number, pageSize: number) => ReturnPromise<void>>
    },
    selectMode: {
      type: String as PropType<ListSelectMode>
    },
    checkMethod: {
      type: Function as PropType<(params: { row: ActiveRecord }) => boolean | string | undefined>
    },
    allowAllChecked: {
      type: [String, Boolean],
      default: undefined
    },
    isAllCheckedIndeterminate: {
      type: Boolean,
      default: undefined
    },
    onCheckedChange: {
      type: Function as PropType<(data: ActiveRecords, event?: CheckedChangeEvent) => void>
    },
    onCheckedAllChange: {
      type: Function as PropType<(selected: boolean, data: ActiveRecord[], event?: CheckedChangeEvent) => void>
    },
    onRadioChange: {
      type: Function as PropType<(data: ActiveRecord, event?: RadioChangeEvent) => void>
    },
    sortConfig: {
      type: Object as PropType<VxeTablePropTypes.SortConfig>
    },
    onSortChange: {
      type: Function as PropType<(sorts: ISort[]) => void>
    },
    editorTrigger: {
      type: String as PropType<TableEditorTrigger>
    },
    editorMode: {
      type: String as PropType<TableEditorMode>
    },
    editorCloseTrigger: {
      type: String as PropType<TableEditorCloseTrigger>
    },
    editorShowIcon: {
      type: Boolean,
      default: undefined
    },
    activeEditorBefore: {
      type: Function as PropType<(context: ActiveEditorContext) => boolean>
    },
    activeEditor: {
      type: Function as PropType<(context: ActiveEditorContext) => ReturnPromise<void>>
    },
    rowEditorClosed: {
      type: Function as PropType<(context: RowContext) => Promise<boolean>>
    },
    allowRowClick: {
      type: Boolean,
      default: undefined
    },
    rowClickMode: {
      type: Array as PropType<TableRowClickMode[]>
    },
    onCurrentChange: {
      type: Function
    },
    onRowClick: {
      type: Function
    },
    onCellClick: {
      type: Function
    },
    onRowDblClick: {
      type: Function
    },
    expandAccordion: {
      type: Boolean,
      default: undefined
    },
    expandAll: {
      type: Boolean,
      default: undefined
    },
    existExpandRow: {
      type: Boolean,
      default: undefined
    },
    expandMethod: {
      type: Function
    },
    onToggleRowExpand: {
      type: Function
    },
    onResizableChange: {
      type: Function
    },
    userPrefer: {
      type: Object as PropType<UserTablePrefer>
    },
    usingSimpleUserPrefer: {
      type: Boolean,
      default: undefined
    },
    lineHeight: {
      type: [String, Number]
    },
    lineHeightType: {
      type: String as PropType<TableLineHeightEnum>
    },
    minLineHeight: {
      type: Number
    },
    showFooter: {
      type: Boolean,
      default: undefined
    },
    footerMethod: {
      type: Function
    },
    spanMethod: {
      type: Function
    },
    mergeCells: {
      type: Array as PropType<VxeTablePropTypes.MergeCells>
    },
    scrollX: {
      type: Object
    },
    scrollY: {
      type: Object
    },
    emptyText: {
      type: String,
      default: ''
    },
    emptyImage: {
      type: String,
      default: undefined
    },
    pageSizeOptions: {
      type: Array as PropType<(number | string)[]>
    },
    treeConfig: {
      type: Object as PropType<VxeTablePropTypes.TreeConfig>
    },
    onToggleTreeExpand: {
      type: Function
    },
    autoLineHeight: {
      type: Boolean,
      default: false
    },

    /**
     * 推荐使用<element widget="checkboxColumn" />标签
     * @deprecated 5.0
     */
    checkbox: {
      type: Boolean,
      default: undefined
    },
    /**
     * 推荐使用<element widget="sequenceColumn" />标签
     * @deprecated 5.0
     */
    enableSequence: {
      type: Boolean,
      default: undefined
    },
    border: {
      type: String
    },
    stripe: {
      type: Boolean,
      default: false
    },
    isCurrent: {
      type: Boolean,
      default: true
    },
    isHover: {
      type: Boolean,
      default: false
    },
    showAddBtn: {
      type: Boolean,
      default: false
    },
    showQuickFill: {
      type: Boolean,
      default: false
    },
    onAddRow: {
      type: Function,
      required: true
    },
    enableGrouping: {
      type: Boolean,
      default: false
    },
    enabledGroupView: {
      type: Boolean,
      default: false
    },
    setAllGroupExpand: {
      type: Function
    },
    groupViewFooterExpandControl: {
      type: Boolean,
      default: false
    },
    groupViewFooterFoldControl: {
      type: Boolean,
      default: false
    },
    inline: {
      type: Boolean,
      default: false
    },
    enabledKeyboard: {
      type: Boolean,
      default: undefined
    },
    onKeydown: {
      type: Function
    },
    currentLineHeight: {
      type: Number
    },
    onLineHeightChange: {
      type: Function
    }
  },
  setup(props) {
    const defaultTableRef = ref<HTMLElement>(null as any);
    const table = ref<OioTableInstance | undefined>();

    const tableContentElement = computed(
      () => defaultTableRef.value && defaultTableRef.value.querySelector('.oio-table-content-wrapper')!
    );

    const pagination = computed<Pagination>(() => {
      return props.pagination || { current: 0, pageSize: 0, total: 0 };
    });

    const editorMode = computed(() => {
      const value = props.editorMode;
      if (value === TableEditorMode.column) {
        return TableEditorMode.cell;
      }
      return value;
    });

    const autoCloseEditor = computed(() => {
      return props.editorCloseTrigger === TableEditorCloseTrigger.auto;
    });

    const editorClosed = (event: VxeTableActiveEditorEventContext) => {
      let fn: ((rowContext: RowContext) => void) | undefined;
      if ([TableEditorMode.row, TableEditorMode.cell].includes(props.editorMode!)) {
        fn = props.rowEditorClosed;
      }
      if (fn) {
        const data = event.row as ActiveRecord;
        return fn({
          key: VxeTableHelper.getKey(data),
          data,
          index: event.rowIndex,
          origin: event
        });
      }
    };

    const checkboxDisabledTitles = ref<Record<string, string>>({});
    const checkMethod = (params: { row: ActiveRecord }): boolean => {
      let res = props.checkMethod?.(params);
      const key = params.row._X_ROW_KEY as string | undefined;
      if (res == null) {
        res = true;
      }
      if (typeof res === 'boolean') {
        if (key) {
          delete checkboxDisabledTitles.value[key];
        }
        return res;
      }
      if (key) {
        checkboxDisabledTitles.value[key] = translateValueByKey(res);
      }
      return false;
    };

    const onPaginationChange = (currentPage: number, pageSize: number) => {
      props.onPaginationChange?.(currentPage, pageSize);
      // nextTick(() => {
      //   table.value?.refreshColumn();
      // });
    };

    const onResizableChange = (...args) => {
      props.onResizableChange?.(...args);

      nextTick(calcTableColumnHeight);
    };

    const onSortChange = (event: SortChangeEvent) => {
      const { field, direction } = event;
      if (direction === false) {
        props.onSortChange?.([]);
      } else {
        props.onSortChange?.([
          {
            sortField: field,
            direction: SortDirections[direction]
          }
        ]);
      }
    };

    const onCheckedChange = (event: CheckedChangeEvent) => {
      const { records } = event;
      props.onCheckedChange?.(records, event);
    };

    const onCheckedAllChange = (event: CheckedChangeEvent) => {
      const { checked, records } = event;
      props.onCheckedAllChange?.(checked, records, event);
    };

    const onRadioChange = (event: RadioChangeEvent) => {
      const { newRecord } = event;
      props.onRadioChange?.(newRecord, event);
    };

    const style = computed(() => {
      return StyleHelper.parse(props.template?.style);
    });

    const $$calcHeight = ref('');
    const calcHeight = computed<string, number>({
      get() {
        if (props.currentLineHeight === undefined) {
          return $$calcHeight.value;
        }
        return `${props.currentLineHeight}px`;
      },
      set(val) {
        $$calcHeight.value = `${val}px`;
        props.onLineHeightChange?.(val);
      }
    });

    const tableLineHeight = computed(() => {
      if (typeof props.lineHeight === 'number') {
        if (props.lineHeight > 0) {
          return `${props.lineHeight}px`;
        }
      } else if (typeof props.lineHeight === 'string') {
        return props.lineHeight;
      }

      if (calcHeight.value) {
        return calcHeight.value;
      }

      return 'var(--oio-table-thead-height)';
    });

    // const calcHeaderHeight = ref('');
    // const tableHeaderHeight = computed(() => {
    //   if (calcHeaderHeight.value) {
    //     return calcHeaderHeight.value;
    //   }
    //
    //   return 'var(--oio-table-thead-height)';
    // });

    const onToggleTreeExpand = (...args) => {
      if (props.onToggleTreeExpand) {
        const res = props.onToggleTreeExpand(...args);
        if (res) {
          nextTick(() => {
            calcTableColumnHeight();
          });
        }
        return res;
      }
      nextTick(() => {
        calcTableColumnHeight();
      });
      return true;
    };

    const onToggleRowExpand = (...args) => {
      props.onToggleRowExpand?.(...args);
      nextTick(() => {
        table.value?.refreshColumn();
      });
    };

    const calcTableColumnHeight = debounce(() => {
      if (!table.value) {
        return;
      }

      const tableEle = table.value?.getOrigin().$el;
      const defaultColumn = tableEle.querySelector(
        '.vxe-table--main-wrapper > .vxe-table--body-wrapper .vxe-body--column'
      );
      const operationColumn = tableEle.querySelector('.vxe-table--fixed-right-wrapper .operation-column');
      if (defaultColumn && operationColumn) {
        const defaultHeight = defaultColumn?.getBoundingClientRect().height;
        const operationHeight = operationColumn?.getBoundingClientRect().height;

        if (defaultHeight > 0 && operationHeight > 0) {
          if (operationHeight >= defaultHeight) {
            calcHeight.value = operationHeight;
          } else if (defaultHeight) {
            calcHeight.value = defaultHeight;
          }
        }
      }

      // fixme @zbh 20260228 此处在处理多级表头高度时，无法判断单行高度和整体高度，暂时移除
      // const headerTable = tableEle.querySelector('.vxe-table--main-wrapper > .vxe-table--header-wrapper');
      // const fixedRightColumn = tableEle.querySelector(
      //   '.vxe-table--fixed-wrapper > .vxe-table--fixed-right-wrapper .vxe-header--column'
      // );
      // if (headerTable && fixedRightColumn) {
      //   const headerTableHeight = headerTable?.getBoundingClientRect().height;
      //   const fixedRightColumnHeight = fixedRightColumn?.getBoundingClientRect().height;
      //   if (headerTableHeight > 0 && fixedRightColumnHeight > 0) {
      //     if (headerTableHeight >= fixedRightColumnHeight) {
      //       calcHeaderHeight.value = `${headerTableHeight}px`;
      //     } else if (fixedRightColumnHeight) {
      //       calcHeaderHeight.value = `${fixedRightColumnHeight}px`;
      //     }
      //   }
      // }

      if (!props.autoLineHeight) {
        return;
      }

      nextTick(() => {
        const rows = tableEle.querySelectorAll(
          '.vxe-table--main-wrapper .vxe-table--body .vxe-body--row'
        ) as HTMLElement[];

        const leftFixedRows = tableEle.querySelectorAll(
          '.vxe-table--fixed-wrapper .vxe-table--fixed-right-wrapper .vxe-body--row'
        ) as HTMLElement[];

        const rightFixedRows = tableEle.querySelectorAll(
          '.vxe-table--fixed-wrapper .vxe-table--fixed-left-wrapper .vxe-body--row'
        ) as HTMLElement[];

        rows.forEach((row, index) => {
          row.style.height = 'auto';
          const height = row.clientHeight;

          const leftFixedRow = leftFixedRows[index];
          const rightFixedRow = rightFixedRows[index];

          leftFixedRow && (leftFixedRow.style.height = 'auto');
          rightFixedRow && (rightFixedRow.style.height = 'auto');

          const maxHeight = Math.max(
            height || 0,
            leftFixedRow?.clientHeight || 0,
            rightFixedRow?.clientHeight || 0,
            props.minLineHeight || 0
          );

          if (leftFixedRow && leftFixedRow.clientHeight !== maxHeight) {
            leftFixedRow.style.height = `${maxHeight}px`;
          }

          if (height !== maxHeight) {
            row.style.height = `${maxHeight}px`;
          }

          if (rightFixedRow && rightFixedRow.clientHeight !== maxHeight) {
            rightFixedRow.style.height = `${maxHeight}px`;
          }
        });
      });
    });

    let _height = 0;
    const resizeObserver = new ResizeObserver((entries) => {
      const target = entries.find((e) => e.target === tableContentElement.value);

      if (target) {
        const { height } = target.contentRect;
        const inPopupContainer =
          Array.from(document.querySelectorAll(`.${DEFAULT_PREFIX}-drawer`))?.some((el) =>
            el?.contains?.(tableContentElement.value)
          ) ||
          Array.from(document.querySelectorAll(`.${DEFAULT_PREFIX}-modal`))?.some((el) =>
            el?.contains?.(tableContentElement.value)
          );

        if (_height !== height || inPopupContainer) {
          _height = height;

          table.value?.refreshColumn();
        }
      }
    });

    let isMounted = false;

    onActivated(() => {
      if (isMounted) {
        isMounted = false;
        return;
      }
      table.value?.refreshColumn();
    });

    onMounted(async () => {
      isMounted = true;

      props.setTableInstance?.(table.value);

      await nextTick();
      calcTableColumnHeight();

      window.addEventListener('resize', calcTableColumnHeight);

      resizeObserver.observe(tableContentElement.value);
    });

    onBeforeUnmount(() => {
      window.removeEventListener('resize', calcTableColumnHeight);
      resizeObserver.unobserve(tableContentElement.value);
    });

    watch(
      () => props.lineHeightType,
      () => {
        nextTick(() => {
          calcTableColumnHeight();
        });
      }
    );

    const stop = watch(
      () => props.dataSource,
      (v) => {
        if (v && v.length) {
          nextTick(() => {
            calcTableColumnHeight();
          });
        }
      },
      { immediate: true }
    );

    const constructWatchUserPrefer = () => {
      return {
        fieldPrefer: props.userPrefer?.fieldPrefer || [],
        fieldOrder: props.userPrefer?.fieldOrder || [],
        fieldLeftFixed: props.userPrefer?.fieldLeftFixed || [],
        fieldRightFixed: props.userPrefer?.fieldRightFixed || []
      };
    };

    watch(
      () => constructWatchUserPrefer(),
      (value) => {
        const tableRef = table.value;
        if (!tableRef) {
          return;
        }
        nextTick(() => {
          let columns = tableRef.getAllColumns();
          columns = sortColumnsByUserPrefer(
            columns.map((v) => {
              v.resizeWidth = 0;
              return v;
            }),
            value.fieldOrder
          );
          tableRef.reloadColumns(columns);
        });
      },
      { immediate: true }
    );

    return {
      defaultTableRef,
      table,
      style,
      tableLineHeight,
      // tableHeaderHeight,

      pagination,
      editorMode,
      autoCloseEditor,
      checkboxDisabledTitles,
      checkMethod,

      onResizableChange,
      editorClosed,
      onPaginationChange,
      onSortChange,
      onCheckedChange,
      onCheckedAllChange,
      onRadioChange,
      onToggleTreeExpand,
      onToggleRowExpand
    };
  },
  render() {
    const {
      showDataSource,
      height,
      minHeight,
      maxHeight,
      lineHeightType,
      rowClassName,
      headerRowClassName,
      footerRowClassName,
      cellClassName,
      headerCellClassName,
      footerCellClassName,
      rowStyle,
      headerRowStyle,
      cellStyle,
      headerCellStyle,

      enableSequence,

      selectMode,
      checkbox,
      checkboxDisabledTitles,
      checkMethod,
      allowAllChecked,
      isAllCheckedIndeterminate,
      onCurrentChange,
      onCheckedChange,
      onCheckedAllChange,
      onRadioChange,

      sortConfig,
      onSortChange,

      showPagination,
      paginationStyle,
      pagination,
      onPaginationChange,

      allowRowClick,
      rowClickMode,
      onRowClick,
      onRowDblClick,
      onCellClick,

      expandAccordion,
      expandAll,
      existExpandRow,
      expandMethod,
      onToggleRowExpand,
      onResizableChange,

      editorTrigger,
      editorMode,
      autoCloseEditor,
      editorShowIcon,
      activeEditorBefore,
      activeEditor,
      editorClosed,

      enabledKeyboard,
      onKeydown,

      setAllGroupExpand,
      enabledGroupView,
      groupViewFooterExpandControl,
      groupViewFooterFoldControl,

      treeConfig,
      onToggleTreeExpand,
      scrollX,
      scrollY,

      usingSimpleUserPrefer,

      showFooter,
      footerMethod,
      spanMethod,
      mergeCells,

      emptyText,
      emptyImage,
      pageSizeOptions,
      stripe,
      isCurrent,
      isHover,
      showAddBtn,
      showQuickFill,
      onAddRow
    } = this;
    let { border = false } = this;
    const VEX_TABLE_BORDER_MODE = [true, false, 'default', 'outer', 'full', 'inner'];
    const tableCustomClass: string[] = [];
    if (!VEX_TABLE_BORDER_MODE.includes(border)) {
      tableCustomClass.push(border as string);
      border = 'inner';
    }
    if (lineHeightType === TableLineHeightEnum.AUTO) {
      tableCustomClass.push(`default-table-line-height-auto`);
    }

    const tableSlots: Record<string, Slot> = {
      default: () => {
        const children: VNode[] = [];
        if (checkbox !== false) {
          children.push(
            createVNode(
              OioColumn,
              {
                type: 'checkbox',
                className: 'table-column-checkbox',
                headerClassName: 'table-header-column-checkbox',
                width: 52,
                align: 'center',
                fixed: existExpandRow ? undefined : 'left'
              },
              {
                header: ({ origin }: { origin: VxeCheckboxHeaderRenderBodyParams }) => {
                  let { indeterminate } = origin;
                  if (isAllCheckedIndeterminate != null) {
                    indeterminate = isAllCheckedIndeterminate;
                  }
                  if (typeof allowAllChecked === 'boolean') {
                    if (allowAllChecked) {
                      return useVxeCheckboxHeader({
                        ...origin,
                        indeterminate
                      });
                    }
                    return useVxeCheckboxHeader({
                      ...origin,
                      indeterminate,
                      disabled: true
                    });
                  }
                  if (typeof allowAllChecked === 'string') {
                    return useVxeCheckboxHeader({
                      ...origin,
                      indeterminate,
                      disabled: true,
                      disabledTitle: allowAllChecked
                    });
                  }
                  return useVxeCheckboxHeader({
                    ...origin,
                    indeterminate
                  });
                },
                checkbox: (params: VxeCheckboxCellRenderBodyParams) => {
                  const key = params.row._X_ROW_KEY as string | undefined;
                  let disabledTitle: string | undefined;
                  if (key) {
                    disabledTitle = checkboxDisabledTitles[key];
                  }
                  if (disabledTitle) {
                    return useVxeCheckboxCell({
                      ...params,
                      disabledTitle: translateValueByKey(disabledTitle)
                    });
                  }
                  return useVxeCheckboxCell(params);
                }
              }
            )
          );
        }
        if (enableSequence) {
          children.push(
            createVNode(OioColumn, {
              type: 'seq',
              width: 58,
              label: translateValueByKey('序号'),
              align: 'center',
              fixed: existExpandRow ? undefined : 'left'
            })
          );
        }
        const columns = this.$slots?.default?.() || [];
        return [...children, ...columns];
      }
    };

    // 有分页器
    if (showPagination) {
      tableSlots.footer = () => {
        const footerVNodeChildren = [
          createVNode(OioPagination, {
            pageSizeOptions,
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showTotal: true,
            showJumper: paginationStyle !== ListPaginationStyle.SIMPLE,
            showLastPage: paginationStyle !== ListPaginationStyle.SIMPLE,
            onChange: onPaginationChange
          })
        ];

        // 分组展开折叠
        if (enabledGroupView) {
          footerVNodeChildren.unshift(
            createVNode(DefaultTableGroupCollapse, {
              groupViewFooterExpandControl,
              groupViewFooterFoldControl,
              setAllGroupExpand
            })
          );
        }

        const footerVNode = [createVNode('div', { class: 'default-table-footer-content' }, [footerVNodeChildren])];

        // 添加行、快速填报
        if (showAddBtn || showQuickFill) {
          const footerOperatorVNode = createVNode(DefaultTableFooterOperator, {
            showAddBtn,
            showQuickFill,
            onAddRow
          });
          footerVNode.unshift(footerOperatorVNode);
        }

        return footerVNode;
      };
    } else {
      const footerSlots = [] as VNode[];

      // 添加行、快速填报
      if (showAddBtn || showQuickFill) {
        const footerOperatorVNode = createVNode(DefaultTableFooterOperator, {
          showAddBtn,
          showQuickFill,
          onAddRow
        });
        footerSlots.push(footerOperatorVNode);
      }

      // 分组展开折叠
      if (enabledGroupView) {
        footerSlots.push(
          createVNode('div', { class: 'default-table-footer-content' }, [
            createVNode(DefaultTableGroupCollapse, {
              groupViewFooterExpandControl,
              groupViewFooterFoldControl,
              setAllGroupExpand
            })
          ])
        );
      }

      tableSlots.footer = () => {
        return [createVNode(Fragment, null, footerSlots)];
      };
    }

    const tableProps: Record<string, unknown> = {
      ref: 'table',
      loading: this.loading,
      size: TableSize.small,
      class: tableCustomClass,
      stripe,
      showOverflow: true,
      showHeaderOverflow: true,
      border,
      resizable: true,
      data: showDataSource,
      scrollX,
      scrollY,
      tooltipConfig: { enterable: true },
      height: 'auto',
      rowConfig: { isCurrent, isHover },
      sortConfig,
      rowClassName,
      headerRowClassName,
      footerRowClassName,
      cellClassName,
      headerCellClassName,
      footerCellClassName,
      rowStyle,
      headerRowStyle,
      cellStyle,
      headerCellStyle,
      expandConfig: { visibleMethod: expandMethod, accordion: expandAccordion, expandAll },
      editConfig: {
        trigger: editorTrigger,
        mode: editorMode,
        autoClear: autoCloseEditor,
        beforeEditMethod: activeEditorBefore,
        showIcon: editorShowIcon
      },
      emptyText,
      emptyImage,
      showFooter,
      footerMethod,
      spanMethod,
      mergeCells,
      onCurrentChange,
      onSortChange,
      onEditActived: activeEditor,
      onEditClosed: editorClosed,
      onToggleRowExpand,
      onResizableChange,
      customConfig: { usingSimpleUserPrefer }
    };
    if (treeConfig) {
      tableProps.treeConfig = {
        ...treeConfig,
        toggleMethod: onToggleTreeExpand
      };
    }
    if (selectMode) {
      const selectTrigger = allowRowClick ? TableSelectTrigger.cell : TableSelectTrigger.row;
      switch (selectMode) {
        case ListSelectMode.checkbox:
          tableProps.checkboxConfig = { trigger: selectTrigger, highlight: true, checkMethod };
          tableProps.onCheckedChange = onCheckedChange;
          tableProps.onCheckedAllChange = onCheckedAllChange;
          break;
        case ListSelectMode.radio:
          tableProps.radioConfig = { trigger: selectTrigger, highlight: true, checkMethod };
          tableProps.onRadioChange = onRadioChange;
          break;
      }
    }
    if (allowRowClick) {
      if (rowClickMode) {
        if (rowClickMode.includes(TableRowClickMode.click)) {
          tableProps.onCellClick = onRowClick;
        }
        if (rowClickMode.includes(TableRowClickMode.dblclick)) {
          tableProps.onCellDblclick = onRowDblClick;
        }
      } else {
        tableProps.onCellDblclick = onRowDblClick;
        tableProps.onCellClick = onCellClick;
      }
    }
    if (onKeydown && enabledKeyboard !== false) {
      tableProps.onKeydown = onKeydown;
    }

    const containerChildren: VNode[] = [];
    containerChildren.push(createVNode(OioTable, tableProps, tableSlots));

    if (allowRowClick) {
      const clickSlot = DslRender.fetchVNodeSlots(this.template, ['click'])?.click;
      if (clickSlot && (onRowClick || onRowDblClick)) {
        containerChildren.push(
          createVNode(
            DefaultTableClickContainer,
            {},
            {
              default: () => clickSlot()
            }
          )
        );
      }
    }

    const classs = ['default-table'];
    if (!this.inline) {
      classs.push('default-main-table');
    }
    if (this.treeConfig?.children === GROUP_TREE_KEY.CHILDREN_KEY && !this.enabledGroupView) {
      classs.push('default-table-group-hidden-expand');
    }

    return createVNode(
      createVNode(
        'div',
        {
          ...PropRecordHelper.collectionBasicProps(this.$attrs, classs, {
            height,
            minHeight,
            maxHeight
          }),
          ref: 'defaultTableRef'
        },
        containerChildren
      )
    );
  }
});
</script>
<style lang="scss">
.default-table .oio-table {
  .oio-table-content {
    > .vxe-table--render-default.size--mini .vxe-body--row .vxe-body--column.col--ellipsis,
    .vxe-table--render-default.vxe-editable.size--mini .vxe-body--column {
      height: v-bind(tableLineHeight);
    }
  }

  &.default-table-line-height-auto {
    .oio-column-wrapper:not(.oio-column-manual-editor) {
      overflow: unset;
      text-overflow: unset;
      text-wrap: auto;
    }
  }
}
</style>
