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
import { computed, watch, onUnmounted, ref } from 'vue'
import { defineStore } from 'pinia'
import { getProductProgress } from '@/api'
import type { ProductProgressParams } from '@/api'
import { useRequest } from 'vue-hooks-plus'
import { useTasksStore } from '@/stores/tasks'
import type { PLCResponse } from '@/api/plc'
import { PLC_POLLING_DURATION } from '@/common/constants'
 
// 全局 watcher ref 防止多次调用 usePLCStore 时重复注册侦听器
const unwatch = ref()
 
export const usePLCStore = defineStore('plc', () => {
  const taskStore = useTasksStore()
 
  const plcInfo = computed(() => {
    return plcRes?.value?.data as PLCResponse
  })
 
  /**
   * 如果任务状态是进行中, 则轮询 plc 取进度
   */
  const {
    data: plcRes,
    run: startPLCPolling,
    cancel: cancelPLCPolling
  } = useRequest(
    () =>
      getProductProgress({
        channel: taskStore.activeChannel ?? 0,
        procedureId: taskStore.activeTask?.Procedure.ID ?? undefined
      } as ProductProgressParams),
    {
      manual: true,
      pollingInterval: PLC_POLLING_DURATION,
      pollingWhenHidden: false
    }
  )
 
  if (!unwatch.value) {
    /**
     * 如果切换到其他通道的任务,则重新轮询plc
     */
    unwatch.value = watch(
      () => taskStore.activeChannel,
      () => {
        cancelPLCPolling()
        startPLCPolling()
      }
    )
  }
 
  function startPollingPLC() {
    cancelPLCPolling()
    startPLCPolling()
  }
 
  onUnmounted(() => {
    cancelPLCPolling()
  })
 
  return { plcInfo, startPollingPLC }
})