import type {
  BasicTableProps,
  FetchParams,
  ColumnProps,
  Pagination,
  DynamicProps
} from '@/types/table'
import { getDynamicProps } from '@/utils'
import { ref, onUnmounted, unref, watch, toRaw } from 'vue'
import type { WatchStopHandle } from 'vue'
type Props = Partial<DynamicProps<BasicTableProps>>

export function useZtTable(tableProps?: Props): [(instance: any) => void, any] {
  const tableRef = ref<any>(null)
  const loadedRef = ref<Nullable<boolean>>(false)
  const formRef = ref<any>(null)

  //卸载清空


  let stopWatch: WatchStopHandle;

  function register(instance: any) {

    onUnmounted(() => {
      tableRef.value = null
      loadedRef.value = null
    })

    if (unref(loadedRef) && instance === unref(tableRef)) return

    tableRef.value = instance

    tableProps && instance.setProps(getDynamicProps(tableProps))
    loadedRef.value = true

    stopWatch?.()


    stopWatch = watch(
      () => tableProps,
      () => {
        tableProps && instance.setProps(getDynamicProps(tableProps))
      },
      {
        immediate: true,
        deep: true
      }
    )
  }


  function getTableInstance() {
    const table = unref(tableRef)
    if (!table) {
      throw new Error('尚未获取table实例!')
    }
    return table
  }

  const methods = {
    reload: async (opt?: FetchParams) => {
      return await getTableInstance().reload(opt)
    },
    setProps: (props: Partial<BasicTableProps>) => {
      getTableInstance().setProps(props)
    },

    setSelectedRows: (rows: Recordable[]) => {
      return toRaw(getTableInstance().setSelectedRows(rows))
    },
    setLoading: (loading: boolean) => {
      getTableInstance().setLoading(loading)
    },
    getDataSource: () => {
      return getTableInstance().getDataSource()
    },
    getRawDataSource: () => {
      return getTableInstance().getRawDataSource()
    },
    getColumns: ({ ignoreIndex = false }: { ignoreIndex?: boolean } = {}) => {
      const columns = getTableInstance().getColumns({ ignoreIndex }) || []
      return toRaw(columns)
    },
    setColumns: (columns: ColumnProps[]) => {
      getTableInstance().setColumns(columns)
    },
    setTableData: (values: any[]) => {
      return getTableInstance().setTableData(values)
    },
    setPagination: (info: Partial<Pagination>) => {
      return getTableInstance().setPagination(info)
    },
    deleteSelectRowByKey: (key: string) => {
      getTableInstance().deleteSelectRowByKey(key)
    },
    getSelectRowKeys: () => {
      return toRaw(getTableInstance().getSelectRowKeys())
    },
    getSelectRows: () => {
      return toRaw(getTableInstance().getSelectRows())
    },
    clearSelectedRowKeys: () => {
      getTableInstance().clearSelectedRowKeys()
    },
    setSelectedRowKeys: (keys: string[] | number[]) => {
      getTableInstance().setSelectedRowKeys(keys)
    },
    getPaginationRef: () => {
      return getTableInstance().getPaginationRef()
    },

    updateTableData: (index: number, key: string, value: any) => {
      return getTableInstance().updateTableData(index, key, value)
    },
    deleteTableDataRecord: (rowKey: string | number | string[] | number[]) => {
      return getTableInstance().deleteTableDataRecord(rowKey)
    },
    insertTableDataRecord: (record: Recordable | Recordable[], index?: number) => {
      return getTableInstance().insertTableDataRecord(record, index)
    },
    updateTableDataRecord: (rowKey: string | number, value:any,record: Recordable) => {
      return getTableInstance().updateTableDataRecord(rowKey,value, record)
    },
    findTableDataRecord: (rowKey: string | number) => {
      return getTableInstance().findTableDataRecord(rowKey)
    },
    getRowSelection: () => {
      return toRaw(getTableInstance().getRowSelection())
    },
    getCacheColumns: () => {
      return toRaw(getTableInstance().getCacheColumns())
    },

    setShowPagination: async (show: boolean) => {
      getTableInstance().setShowPagination(show)
    },
    getShowPagination: () => {
      return toRaw(getTableInstance().getShowPagination())
    },

  }

  return [register, methods]
}
