import { LINE_ALARMS_QUERY_KEY, LINE_DEVICES_QUERY_KEY, LINE_STATIONS_QUERY_KEY, NDM_POLLIING_STORE_ID } from '@/constants';
import { useQueryClient } from '@tanstack/vue-query';
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const usePollingStore = defineStore(
  NDM_POLLIING_STORE_ID,
  () => {
    const queryClient = useQueryClient();

    // 允许控制轮询
    const pollingEnabled = ref(true);
    const startPolling = () => {
      pollingEnabled.value = true;
    };
    const stopPolling = () => {
      pollingEnabled.value = false;
      queryClient.cancelQueries({ queryKey: [LINE_STATIONS_QUERY_KEY] });
      queryClient.cancelQueries({ queryKey: [LINE_DEVICES_QUERY_KEY] });
      queryClient.cancelQueries({ queryKey: [LINE_ALARMS_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [LINE_STATIONS_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [LINE_DEVICES_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [LINE_ALARMS_QUERY_KEY] });
    };

    return {
      pollingEnabled,
      startPolling,
      stopPolling,
    };
  },
  {
    persist: true,
  },
);
