import type { LineDevices, NdmDeviceResultVO, Station } from '@/apis';
import { tryGetDeviceType, type DeviceType } from '@/enums';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

export const useDeviceSelection = () => {
  const route = useRoute();
  const router = useRouter();

  const selectedStationCode = ref<Station['code']>();
  const selectedDeviceType = ref<DeviceType>();
  const selectedDevice = ref<NdmDeviceResultVO>();

  // 从路由参数同步选中的车站、设备类型以及设备
  const syncFromRoute = (lineDevices: LineDevices) => {
    // console.log('sync from route');
    const { stationCode: routeStationCode, deviceType: routeDeviceType, deviceDbId: routeDeviceDbId } = route.query;
    if (routeStationCode) {
      selectedStationCode.value = routeStationCode as Station['code'];
    }
    if (routeDeviceType) {
      selectedDeviceType.value = routeDeviceType as DeviceType;
    }
    if (routeDeviceDbId && selectedStationCode.value && selectedDeviceType.value) {
      const selectedDeviceDbId = routeDeviceDbId as string;
      const stationDevices = lineDevices[selectedStationCode.value];
      if (stationDevices) {
        const classifiedDevices = stationDevices[selectedDeviceType.value];
        if (classifiedDevices) {
          const device = classifiedDevices.find((device) => device.id === selectedDeviceDbId);
          if (device) {
            selectedDevice.value = device;
          }
        }
      }
    }
  };

  const selectDevice = (device: NdmDeviceResultVO, stationCode: Station['code']) => {
    selectedDevice.value = device;
    selectedStationCode.value = stationCode;
    const deviceType = tryGetDeviceType(device.deviceType);
    if (deviceType) {
      selectedDeviceType.value = deviceType;
    }
  };

  // 将选中的车站、设备类型以及设备ID同步到路由参数
  const syncToRoute = () => {
    // console.log('sync to route');
    const query = { ...route.query };
    // 当选中的设备发生变化时，删除fromPage参数
    if (selectedDevice.value?.id && route.query.deviceDbId !== selectedDevice.value.id) {
      delete query['fromPage'];
    }
    if (selectedStationCode.value) {
      query['stationCode'] = selectedStationCode.value;
    }
    if (selectedDeviceType.value) {
      query['deviceType'] = selectedDeviceType.value;
    }
    if (selectedDevice.value?.id) {
      query['deviceDbId'] = selectedDevice.value.id;
    }
    router.replace({ query });
  };

  return {
    selectedStationCode,
    selectedDeviceType,
    selectedDevice,

    syncFromRoute,
    syncToRoute,
    selectDevice,
  };
};

export type UseDeviceSelectionReturn = ReturnType<typeof useDeviceSelection>;
