usePaperBatchCondition.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {getPaperBatches} from "@/api/dz/papers.js";
  2. import {createEventHook, injectLocal, provideLocal} from "@vueuse/core";
  3. const key = Symbol('PaperBatchCondition')
  4. export const useProvidePaperBatchCondition = function (type, autoSelectFirst = false) {
  5. // 批次
  6. const buildType = type
  7. const batchId = ref('')
  8. const batchList = ref([])
  9. const batchEvent = createEventHook()
  10. let isInitialized = false
  11. onMounted(async () => {
  12. const res = await getPaperBatches()
  13. batchList.value = res.data
  14. // 如果启用自动选择且列表不为空,且是首次初始化,默认选中最新的第一个
  15. if (autoSelectFirst && batchList.value.length > 0 && !isInitialized && !batchId.value) {
  16. isInitialized = true
  17. // 按创建时间降序排序,选择最新的第一个
  18. const sorted = [...batchList.value].sort((a, b) => {
  19. const timeA = a.createTime || a.create_time || 0
  20. const timeB = b.createTime || b.create_time || 0
  21. return timeB - timeA
  22. })
  23. batchId.value = sorted[0].batchId
  24. }
  25. })
  26. watch(batchId, async (batchId) => {
  27. if (batchId) {
  28. const payload = {buildType, batchId}
  29. await batchEvent.trigger(payload)
  30. }
  31. })
  32. const payload = {buildType, batchId, batchList, onBatchReady: batchEvent.on}
  33. provideLocal(key, payload)
  34. return payload
  35. }
  36. export const useInjectPaperBatchCondition = function () {
  37. return injectLocal(key)
  38. }