import { getAllDevicesApi, initStationDevices, type Station } from '@/apis';
import { LINE_DEVICES_QUERY_KEY, STATION_DEVICES_MUTATION_KEY } from '@/constants';
import { useDeviceStore, usePermissionStore } from '@/stores';
import { parseErrorFeedback } from '@/utils';
import { CancelledError, useMutation, useQuery } from '@tanstack/vue-query';
import { isCancel } from 'axios';
import { computed } from 'vue';

export const useStationDevicesMutation = () => {
  const deviceStore = useDeviceStore();

  return useMutation({
    mutationKey: [STATION_DEVICES_MUTATION_KEY],
    mutationFn: async (params: { station: Station; signal?: AbortSignal }) => {
      const { station, signal } = params;
      if (!station.online) {
        return initStationDevices();
      }
      return await getAllDevicesApi({ stationCode: station.code, signal });
    },
    onSuccess: (devices, { station }) => {
      deviceStore.setStationDevices(station.code, devices);
    },
    onError: (error) => {
      if (isCancel(error) || error instanceof CancelledError) return;
      console.error(error);
      const errorFeedback = parseErrorFeedback(error);
      window.$message.error(errorFeedback);
    },
  });
};

/**
 * 由 `useLineStationsQuery` 显式触发
 * @see [use-line-stations-query.ts](./use-line-stations-query.ts)
 */
export const useLineDevicesQuery = () => {
  const permissionStore = usePermissionStore();
  const stations = computed(() => permissionStore.stations.VIEW ?? []);

  const { mutateAsync: getStationDevices } = useStationDevicesMutation();

  return useQuery({
    queryKey: computed(() => [LINE_DEVICES_QUERY_KEY]),
    enabled: false,
    queryFn: async ({ signal }) => {
      const startTime = performance.now();
      for (const station of stations.value) {
        await getStationDevices({ station, signal }).catch(() => {});
      }
      const endTime = performance.now();
      console.log(`${LINE_DEVICES_QUERY_KEY}: ${endTime - startTime} ms`);

      return null;
    },
  });
};
