import type { ComputedRef } from 'vue';
import { computed, onUnmounted, ref, unref, watch } from 'vue';
import type { tableProp, ztTableProps } from '../types';
import type { FormProps } from '../../Form/types/form';
export function useTable(tableProps: ztTableProps): UseTableReturnType {
  const tableRef = ref<Nullable<TableMethods>>(null);
  function register(instance: TableMethods) {
    onUnmounted(() => {
      tableRef.value = null;
    });

    if (instance === unref(tableRef)) return;

    tableRef.value = instance;
    watch(
      () => tableProps,
      () => {
        if (tableProps) {
          instance.setSearchProps(tableProps.searchFormConfig as FormProps);
          instance.setTableConfig(tableProps.tableConfig);
        }
      },
      {
        immediate: true,
        deep: true
      }
    );
  }
  const methods: TableMethods = {
    refresh: async () => {
      await tableRef.value?.refresh();
    },
    getTableLoding: computed(() => tableRef.value?.getTableLoding ?? false),
    setSearchProps(props) {
      tableRef.value?.setSearchProps(props);
    },
    setTableLoading(loading) {
      tableRef.value?.setTableLoading(loading);
    },
    setTableConfig(config) {
      tableRef.value?.setTableConfig(config);
    },
    getTableCheckedRowKeys() {
      return tableRef.value?.getTableCheckedRowKeys() as string[];
    },
    getTableData() {
      return tableRef.value?.getTableData() as any[];
    },
    getSeachForm() {
      return tableRef.value?.getSeachForm() as Recordable;
    },
    setFieldsValue(values: Recordable) {
      return tableRef.value?.setFieldsValue(values);
    },
    // 添加设置已选中行的方法
    setTableCheckedRowKeys(keys: string[]) {
      tableRef.value?.setTableCheckedRowKeys(keys);
    }
  };
  return [register, methods];
}

export interface TableMethods {
  refresh: () => Promise<any>;
  setSearchProps: (props: FormProps) => void;
  setTableLoading: (loading: boolean) => void;
  setTableConfig: (config: tableProp) => void;
  getTableCheckedRowKeys: () => string[];
  getTableData: () => any[];
  getSeachForm: () => Recordable;
  setFieldsValue: (values: Recordable) => void;
  getTableLoding: ComputedRef<boolean>;
  // 添加设置已选中行的方法接口
  setTableCheckedRowKeys: (keys: string[]) => void;
}

export type RegisterFn = (TableInstance: TableMethods) => void;

export type UseTableReturnType = [RegisterFn, TableMethods];
