import { ref, computed, watch, nextTick, unref } from 'vue' import { isDefine } from '@/utils/common' import type { Ref, ShallowRef, UnwrapRef } from 'vue' import type { InstanceTable } from 'global-type' import type { MultipleResult } from 'api-type' type ArrayObjectType = Array> type MultipleResultType> = MultipleResult type InputDataType = MultipleResultType | ArrayObjectType type TableDataType = Ref | ShallowRef type ArrayData = T extends MultipleResultType ? D : ExtractArrayValue type RowType> = ArrayData> & { index: number } function isMultipleData(data: any): data is MultipleResultType { return isDefine(data?.result) && isDefine(data?.totalCount) } const useTableCheck = >(data: T, auto = true) => { const tableRef = ref() const elTableRef = computed(() => { return tableRef?.value?.tableRef }) const tableData = computed(() => { const d = unref(data) let result: RowType[] = [] if (d) { if (isMultipleData(d)) { result = d?.result?.map((d, index) => ({ ...d, index: d.index ?? index })) as RowType[] } else { result = d?.map((d, index) => ({ ...d, index: d.index ?? index })) as RowType[] } } return result }) const current = ref>() const currentView = ref>() const visibleHistory = ref(false) watch( tableData, () => { current.value = void 0 currentView.value = void 0 if (tableData?.value?.length && auto) { nextTick(() => { elTableRef?.value?.setCurrentRow(tableData.value[0]) }) } }, { immediate: true } ) /** 表格选中 */ const onCurrentChange = (row: RowType) => { current.value = row } /** 表格行双击 */ const onDbClick = (row: RowType) => { currentView.value = row visibleHistory.value = true } /** 下一份 */ const next = () => { elTableRef?.value?.setCurrentRow(tableData.value[((current.value?.index || 0) + 1) % tableData.value.length]) } return { tableRef, elTableRef, tableData, current, currentView, visibleHistory, onCurrentChange, onDbClick, next, } } export default useTableCheck