import { ref, onUnmounted } from 'vue';
import { queryDevicePropertiesHistoryApi } from '@/api/sensor-group';
import type { DevicePropertiesHistoryItem } from '@/api/sensor-group/type';

export type SensorRealtimeData = Record<number, DevicePropertiesHistoryItem[]>;

const FIXED_HISTORY_PARAMS = {
  startTime: '1742109231',
  endTime: '1836803631',
  page: 1,
  size: 3,
} as const;

export function useSensorRealtime() {
  const sensorData = ref<SensorRealtimeData>({});

  async function connect(deviceIds: number[]) {
    if (!deviceIds.length) return;

    await Promise.all(
      deviceIds.map(async (deviceId) => {
        try {
          const res = await queryDevicePropertiesHistoryApi({
            deviceId,
            ...FIXED_HISTORY_PARAMS,
          });

          sensorData.value = {
            ...sensorData.value,
            [deviceId]: res?.list || [],
          };
        } catch {
          // 忽略单个设备失败，避免影响其他设备展示
        }
      }),
    );
  }

  function close() {
    return;
  }

  onUnmounted(() => {
    sensorData.value = {};
  });

  return { sensorData, connect, close };
}
