zhou zhou
3 小时以前 46d872c1a5b77aa8799de4a64888a0a24a1422d6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, readonly } from 'vue'
import { useWindowSize } from '@vueuse/core'
import { useTableColumns } from './useTableColumns'
import { TableCache, CacheInvalidationStrategy } from '../../utils/table/tableCache'
import {
  defaultResponseAdapter,
  extractTableData,
  updatePaginationFromResponse,
  createSmartDebounce,
  createErrorHandler
} from '../../utils/table/tableUtils'
import { tableConfig } from '../../utils/table/tableConfig'
function useTable(config) {
  return useTableImpl(config)
}
function useTableImpl(config) {
  const {
    core: {
      apiFn,
      apiParams = {},
      excludeParams = [],
      immediate = true,
      columnsFactory,
      paginationKey
    },
    transform: { dataTransformer, responseAdapter = defaultResponseAdapter } = {},
    performance: {
      enableCache = false,
      cacheTime = 5 * 60 * 1e3,
      debounceTime = 300,
      maxCacheSize = 50
    } = {},
    hooks: { onSuccess, onError, onCacheHit, resetFormCallback } = {},
    debug: { enableLog = false } = {}
  } = config
  const pageKey = paginationKey?.current || tableConfig.paginationKey.current
  const sizeKey = paginationKey?.size || tableConfig.paginationKey.size
  const cacheUpdateTrigger = ref(0)
  const logger = {
    log: (message, ...args) => {
      if (enableLog) {
        console.log(`[useTable] ${message}`, ...args)
      }
    },
    warn: (message, ...args) => {
      if (enableLog) {
        console.warn(`[useTable] ${message}`, ...args)
      }
    },
    error: (message, ...args) => {
      if (enableLog) {
        console.error(`[useTable] ${message}`, ...args)
      }
    }
  }
  const cache = enableCache ? new TableCache(cacheTime, maxCacheSize, enableLog) : null
  const loadingState = ref('idle')
  const loading = computed(() => loadingState.value === 'loading')
  const error = ref(null)
  const data = ref([])
  let abortController = null
  let cacheCleanupTimer = null
  const searchParams = reactive(
    Object.assign(
      {
        [pageKey]: 1,
        [sizeKey]: 10
      },
      apiParams || {}
    )
  )
  const pagination = reactive({
    current: searchParams[pageKey] || 1,
    size: searchParams[sizeKey] || 10,
    total: 0
  })
  const { width } = useWindowSize()
  const mobilePagination = computed(() => ({
    ...pagination,
    small: width.value < 768
  }))
  const columnConfig = columnsFactory ? useTableColumns(columnsFactory) : null
  const columns = columnConfig?.columns
  const columnChecks = columnConfig?.columnChecks
  const hasData = computed(() => data.value.length > 0)
  const cacheInfo = computed(() => {
    void cacheUpdateTrigger.value
    if (!cache) return { total: 0, size: '0KB', hitRate: '0 avg hits' }
    return cache.getStats()
  })
  const handleError = createErrorHandler(onError, enableLog)
  const clearCache = (strategy, context) => {
    if (!cache) return
    let clearedCount = 0
    switch (strategy) {
      case CacheInvalidationStrategy.CLEAR_ALL:
        cache.clear()
        logger.log(`清空所有缓存 - ${context || ''}`)
        break
      case CacheInvalidationStrategy.CLEAR_CURRENT:
        clearedCount = cache.clearCurrentSearch(searchParams)
        logger.log(`清空当前搜索缓存 ${clearedCount} 条 - ${context || ''}`)
        break
      case CacheInvalidationStrategy.CLEAR_PAGINATION:
        clearedCount = cache.clearPagination()
        logger.log(`清空分页缓存 ${clearedCount} 条 - ${context || ''}`)
        break
      case CacheInvalidationStrategy.KEEP_ALL:
      default:
        logger.log(`保持缓存不变 - ${context || ''}`)
        break
    }
    cacheUpdateTrigger.value++
  }
  const fetchData = async (params, useCache = enableCache) => {
    if (abortController) {
      abortController.abort()
    }
    const currentController = new AbortController()
    abortController = currentController
    loadingState.value = 'loading'
    error.value = null
    try {
      let requestParams = Object.assign(
        {},
        searchParams,
        {
          [pageKey]: pagination.current,
          [sizeKey]: pagination.size
        },
        params || {}
      )
      if (excludeParams.length > 0) {
        const filteredParams = { ...requestParams }
        excludeParams.forEach((key) => {
          delete filteredParams[key]
        })
        requestParams = filteredParams
      }
      if (useCache && cache) {
        const cachedItem = cache.get(requestParams)
        if (cachedItem) {
          data.value = cachedItem.data
          updatePaginationFromResponse(pagination, cachedItem.response)
          const paramsRecord2 = searchParams
          if (paramsRecord2[pageKey] !== pagination.current) {
            paramsRecord2[pageKey] = pagination.current
          }
          if (paramsRecord2[sizeKey] !== pagination.size) {
            paramsRecord2[sizeKey] = pagination.size
          }
          loadingState.value = 'success'
          if (onCacheHit) {
            onCacheHit(cachedItem.data, cachedItem.response)
          }
          logger.log(`缓存命中`)
          return cachedItem.response
        }
      }
      const response = await apiFn(requestParams)
      if (currentController.signal.aborted) {
        throw new Error('请求已取消')
      }
      const standardResponse = responseAdapter(response)
      let tableData = extractTableData(standardResponse)
      if (dataTransformer) {
        tableData = dataTransformer(tableData)
      }
      data.value = tableData
      updatePaginationFromResponse(pagination, standardResponse)
      const paramsRecord = searchParams
      if (paramsRecord[pageKey] !== pagination.current) {
        paramsRecord[pageKey] = pagination.current
      }
      if (paramsRecord[sizeKey] !== pagination.size) {
        paramsRecord[sizeKey] = pagination.size
      }
      if (useCache && cache) {
        cache.set(requestParams, tableData, standardResponse)
        cacheUpdateTrigger.value++
        logger.log(`数据已缓存`)
      }
      loadingState.value = 'success'
      if (onSuccess) {
        onSuccess(tableData, standardResponse)
      }
      return standardResponse
    } catch (err) {
      if (err instanceof Error && err.message === '请求已取消') {
        loadingState.value = 'idle'
        return { records: [], total: 0, current: 1, size: 10 }
      }
      loadingState.value = 'error'
      data.value = []
      const tableError = handleError(err, '获取表格数据失败')
      throw tableError
    } finally {
      if (abortController === currentController) {
        abortController = null
      }
    }
  }
  const getData = async (params) => {
    try {
      return await fetchData(params)
    } catch {
      return Promise.resolve()
    }
  }
  const getDataByPage = async (params) => {
    pagination.current = 1
    searchParams[pageKey] = 1
    clearCache(CacheInvalidationStrategy.CLEAR_CURRENT, '搜索数据')
    try {
      return await fetchData(params, false)
    } catch {
      return Promise.resolve()
    }
  }
  const debouncedGetDataByPage = createSmartDebounce(getDataByPage, debounceTime)
  const resetSearchParams = async () => {
    debouncedGetDataByPage.cancel()
    const paramsRecord = searchParams
    const defaultPagination = {
      [pageKey]: 1,
      [sizeKey]: paramsRecord[sizeKey] || 10
    }
    Object.keys(searchParams).forEach((key) => {
      delete paramsRecord[key]
    })
    Object.assign(searchParams, apiParams || {}, defaultPagination)
    pagination.current = 1
    pagination.size = defaultPagination[sizeKey]
    error.value = null
    clearCache(CacheInvalidationStrategy.CLEAR_ALL, '重置搜索')
    await getData()
    if (resetFormCallback) {
      await nextTick()
      resetFormCallback()
    }
  }
  const replaceSearchParams = (params) => {
    const paramsRecord = searchParams
    const currentSize = pagination.size || (paramsRecord[sizeKey] ?? 10)
    Object.keys(searchParams).forEach((key) => {
      if (key !== pageKey && key !== sizeKey) {
        delete paramsRecord[key]
      }
    })
    Object.assign(
      searchParams,
      {
        [pageKey]: 1,
        [sizeKey]: currentSize
      },
      params || {}
    )
    pagination.current = 1
    pagination.size = currentSize
  }
  let isCurrentChanging = false
  const handleSizeChange = async (newSize) => {
    if (newSize <= 0) return
    debouncedGetDataByPage.cancel()
    const paramsRecord = searchParams
    pagination.size = newSize
    pagination.current = 1
    paramsRecord[sizeKey] = newSize
    paramsRecord[pageKey] = 1
    clearCache(CacheInvalidationStrategy.CLEAR_CURRENT, '分页大小变化')
    await getData()
  }
  const handleCurrentChange = async (newCurrent) => {
    if (newCurrent <= 0) return
    if (isCurrentChanging) {
      return
    }
    if (pagination.current === newCurrent) {
      logger.log('分页页码未变化,跳过请求')
      return
    }
    try {
      isCurrentChanging = true
      const paramsRecord = searchParams
      pagination.current = newCurrent
      if (paramsRecord[pageKey] !== newCurrent) {
        paramsRecord[pageKey] = newCurrent
      }
      await getData()
    } finally {
      isCurrentChanging = false
    }
  }
  const refreshCreate = async () => {
    debouncedGetDataByPage.cancel()
    pagination.current = 1
    searchParams[pageKey] = 1
    clearCache(CacheInvalidationStrategy.CLEAR_PAGINATION, '新增数据')
    await getData()
  }
  const refreshUpdate = async () => {
    clearCache(CacheInvalidationStrategy.CLEAR_CURRENT, '编辑数据')
    await getData()
  }
  const refreshRemove = async () => {
    const { current } = pagination
    clearCache(CacheInvalidationStrategy.CLEAR_CURRENT, '删除数据')
    await getData()
    if (data.value.length === 0 && current > 1) {
      pagination.current = current - 1
      searchParams[pageKey] = current - 1
      await getData()
    }
  }
  const refreshData = async () => {
    debouncedGetDataByPage.cancel()
    clearCache(CacheInvalidationStrategy.CLEAR_ALL, '手动刷新')
    await getData()
  }
  const refreshSoft = async () => {
    clearCache(CacheInvalidationStrategy.CLEAR_CURRENT, '软刷新')
    await getData()
  }
  const cancelRequest = () => {
    if (abortController) {
      abortController.abort()
    }
    debouncedGetDataByPage.cancel()
  }
  const clearData = () => {
    data.value = []
    error.value = null
    clearCache(CacheInvalidationStrategy.CLEAR_ALL, '清空数据')
  }
  const clearExpiredCache = () => {
    if (!cache) return 0
    const cleanedCount = cache.cleanupExpired()
    if (cleanedCount > 0) {
      cacheUpdateTrigger.value++
    }
    return cleanedCount
  }
  if (enableCache && cache) {
    cacheCleanupTimer = setInterval(() => {
      const cleanedCount = cache.cleanupExpired()
      if (cleanedCount > 0) {
        logger.log(`自动清理 ${cleanedCount} 条过期缓存`)
        cacheUpdateTrigger.value++
      }
    }, cacheTime / 2)
  }
  if (immediate) {
    onMounted(async () => {
      await getData()
    })
  }
  onUnmounted(() => {
    cancelRequest()
    if (cache) {
      cache.clear()
    }
    if (cacheCleanupTimer) {
      clearInterval(cacheCleanupTimer)
    }
  })
  return {
    // 数据相关
    /** 表格数据 */
    data,
    /** 数据加载状态 */
    loading: readonly(loading),
    /** 错误状态 */
    error: readonly(error),
    /** 数据是否为空 */
    isEmpty: computed(() => data.value.length === 0),
    /** 是否有数据 */
    hasData,
    // 分页相关
    /** 分页状态信息 */
    pagination: readonly(pagination),
    /** 移动端分页配置 */
    paginationMobile: mobilePagination,
    /** 页面大小变化处理 */
    handleSizeChange,
    /** 当前页变化处理 */
    handleCurrentChange,
    // 搜索相关 - 统一前缀
    /** 搜索参数 */
    searchParams,
    /** 替换搜索参数(适用于表单查询,避免旧字段残留) */
    replaceSearchParams,
    /** 重置搜索参数 */
    resetSearchParams,
    // 数据操作 - 更明确的操作意图
    /** 加载数据 */
    fetchData: getData,
    /** 获取数据 */
    getData: getDataByPage,
    /** 获取数据(防抖) */
    getDataDebounced: debouncedGetDataByPage,
    /** 清空数据 */
    clearData,
    // 刷新策略
    /** 全量刷新:清空所有缓存,重新获取数据(适用于手动刷新按钮) */
    refreshData,
    /** 轻量刷新:仅清空当前搜索条件的缓存,保持分页状态(适用于定时刷新) */
    refreshSoft,
    /** 新增后刷新:回到第一页并清空分页缓存(适用于新增数据后) */
    refreshCreate,
    /** 更新后刷新:保持当前页,仅清空当前搜索缓存(适用于更新数据后) */
    refreshUpdate,
    /** 删除后刷新:智能处理页码,避免空页面(适用于删除数据后) */
    refreshRemove,
    // 缓存控制
    /** 缓存统计信息 */
    cacheInfo,
    /** 清除缓存,根据不同的业务场景选择性地清理缓存: */
    clearCache,
    // 支持4种清理策略
    // clearCache(CacheInvalidationStrategy.CLEAR_ALL, '手动刷新')     // 清空所有缓存
    // clearCache(CacheInvalidationStrategy.CLEAR_CURRENT, '搜索数据') // 只清空当前搜索条件的缓存
    // clearCache(CacheInvalidationStrategy.CLEAR_PAGINATION, '新增数据') // 清空分页相关缓存
    // clearCache(CacheInvalidationStrategy.KEEP_ALL, '保持缓存')      // 不清理任何缓存
    /** 清理已过期的缓存条目,释放内存空间 */
    clearExpiredCache,
    // 请求控制
    /** 取消当前请求 */
    cancelRequest,
    // 列配置 (如果提供了 columnsFactory)
    ...(columnConfig && {
      /** 表格列配置 */
      columns,
      /** 列显示控制 */
      columnChecks,
      /** 新增列 */
      addColumn: columnConfig.addColumn,
      /** 删除列 */
      removeColumn: columnConfig.removeColumn,
      /** 切换列显示状态 */
      toggleColumn: columnConfig.toggleColumn,
      /** 更新列配置 */
      updateColumn: columnConfig.updateColumn,
      /** 批量更新列配置 */
      batchUpdateColumns: columnConfig.batchUpdateColumns,
      /** 重新排序列 */
      reorderColumns: columnConfig.reorderColumns,
      /** 获取指定列配置 */
      getColumnConfig: columnConfig.getColumnConfig,
      /** 获取所有列配置 */
      getAllColumns: columnConfig.getAllColumns,
      /** 重置所有列配置到默认状态 */
      resetColumns: columnConfig.resetColumns
    })
  }
}
import { CacheInvalidationStrategy as CacheInvalidationStrategy2 } from '../../utils/table/tableCache'
export { CacheInvalidationStrategy2 as CacheInvalidationStrategy, useTable }