import { computed, ref, unref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { omit } from 'lodash-es';
import { Table } from 'ant-design-vue';
import type { Slots } from 'vue';
import type { DynamicTableProps, DynamicTableEmitFn } from '../dynamic-table';
import type { SchemaFormInstance } from '@/components/lt-a-form/src';
import type { TableProps } from 'ant-design-vue';
import { isArray } from '@/utils/is';
export type Pagination = TableProps['pagination'];
export type TableState = ReturnType<typeof useTableState>;

export type UseTableStateParams = {
  props: DynamicTableProps;
  slots: Slots;
  tableID: string;
  emit: DynamicTableEmitFn;
};

export const useTableState = ({ props, tableID }: UseTableStateParams) => {
  const { t } = useI18n();
  tableID;
  /** 表格数据 */
  const tableData = ref<any[]>([]);

  /** 表格实例 */
  const tableRef = ref<InstanceType<typeof Table>>();
  /** 查询表单实例 */
  const queryFormRef = ref<SchemaFormInstance>();
  /** 编辑表格的表单实例 */
  const editTableFormRef = ref<SchemaFormInstance>();

  /** 内部属性 */
  const innerPropsRef = ref<Partial<DynamicTableProps>>();
  /** 分页配置参数 */
  const paginationRef = ref<NonNullable<Pagination>>(false);
  /** 表格加载 */
  const loadingRef = ref<boolean>(!!props.loading);
  /** 编辑表单model */
  const editFormModel = ref<Recordable>({});
  /** 所有验证不通过的表单项 */
  const editFormErrorMsgs = ref(new Map());
  /** 当前所有正在被编辑的行key的格式为：`${recordKey}`  */
  const editableRowKeys = ref(new Set<Key>());
  /** 当前所有正在被编辑的单元格key的格式为：`${recordKey}.${dataIndex}`，仅`editableType`为`cell`时有效  */
  const editableCellKeys = ref(new Set<Key>());

  if (!Object.is(props.pagination, false)) {
    paginationRef.value = {
      current: 1,
      pageSize: 25,
      total: 0,
      pageSizeOptions: ['10', '15', '20', '25', '30', '50', '100', '500', '1000'],
      showQuickJumper: true,
      showSizeChanger: true, // 显示可改变每页数量
      showTotal: (total) => t('component.table.total', { total }), // 显示总数
      // onChange: (current, pageSize) => pageOption?.pageChange?.(current, pageSize),
      // onShowSizeChange: (current, pageSize) => pageOption?.pageChange?.(current, pageSize),
      ...props.pagination,
    };
  }

  const getProps = computed(() => {
    return { ...props, ...unref(innerPropsRef) };
  });

  const getBindValues = computed(() => {
    const props = unref(getProps);
    let propsData: Recordable = {
      ...props,
      rowKey: props.rowKey ? props.rowKey : '_tableKey',
      loading: unref(loadingRef),
      tableLayout: 'fixed',
      pagination: unref(paginationRef),
    };
    // if (slots.expandedRowRender) {
    //   propsData = omit(propsData, 'scroll');
    // }
    propsData = omit(propsData, ['class', 'onChange']);
    return propsData;
  });

  const setTableKey = function (data) {
    if (!isArray(data)) {
      return data;
    }
    for (let i = 0; i < data.length; i++) {
      data[i]._tableKey = i + 1;
    }
  };

  watch(
    [() => props.dataSource],
    () => {
      if (props.dataSource) {
        tableData.value = props.dataSource;
        setTableKey(tableData.value);
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  return {
    tableRef,
    loadingRef,
    tableData,
    queryFormRef,
    innerPropsRef,
    getProps,
    getBindValues,
    paginationRef,
    editTableFormRef,
    editFormModel,
    editFormErrorMsgs,
    editableCellKeys,
    editableRowKeys,
  };
};
