import { useLineDevicesQuery } from './use-line-devices-query';
import { useLineAlarmsQuery } from './use-line-alarms-query';
import { pagePermissionApi } from '@/apis';
import { USER_PERMISSION_QUERY_KEY } from '@/constants';
import { PERMISSION_TYPE_LITERALS } from '@/enums';
import { usePermissionStore, useSettingStore, useStationStore, useUserStore } from '@/stores';
import { useQuery } from '@tanstack/vue-query';
import { storeToRefs } from 'pinia';
import { computed, watch } from 'vue';
import { useLineStationsQuery } from './use-line-stations-query';

export const useUserPermissionQuery = () => {
  const settingStore = useSettingStore();
  const { pollingStations, activeRequests } = storeToRefs(settingStore);

  const userStore = useUserStore();
  const { userInfo } = storeToRefs(userStore);

  const stationStore = useStationStore();
  const { stations } = storeToRefs(stationStore);

  const permissionStore = usePermissionStore();
  const { permissions } = storeToRefs(permissionStore);

  const { dataUpdatedAt: stationsUpdatedTime } = useLineStationsQuery();
  const { refetch: refetchLineDevicesQuery } = useLineDevicesQuery();
  const { refetch: refetchLineAlarmsQuery } = useLineAlarmsQuery();

  watch([permissions, stationsUpdatedTime], async ([newPermissions, newUpdatedTime], [oldPermissions, oldUpdatedTime]) => {
    const newPermissionsJson = JSON.stringify(newPermissions);
    const oldPermissionsJson = JSON.stringify(oldPermissions);
    if (newPermissionsJson === oldPermissionsJson && newUpdatedTime === oldUpdatedTime) return;
    // 设备查询和告警查询依赖pollingEnabdled
    // 当关闭轮询时，只会取消当前正在执行的查询，
    // 所以如果在关闭轮询时refetch还未执行，那么这一次取消就是无效的，refetch依然会执行，
    // 所以在每个refetch被调用前都需要检查pollingEnabled，否则就可能会取消失败
    if (!pollingStations.value) return;
    await refetchLineDevicesQuery();
    if (!pollingStations.value) return;
    await refetchLineAlarmsQuery();
  });

  return useQuery({
    queryKey: computed(() => [USER_PERMISSION_QUERY_KEY]),
    // 启用【车站轮询】或【主动请求】时，都认为查询被启用
    enabled: computed(() => (pollingStations.value || activeRequests.value) && userInfo.value?.['employeeId'] && stations.value.length > 0),
    // 当启用【车站轮询】时，刷新间隔为10秒，缓存时间为5秒
    refetchInterval: computed(() => (pollingStations.value ? 10 * 1000 : undefined)),
    staleTime: computed(() => (pollingStations.value ? 5 * 1000 : undefined)),
    queryFn: async ({ signal }) => {
      const { records } = await pagePermissionApi(
        {
          model: {
            employeeId: userInfo.value['employeeId'],
          },
          current: 1,
          size: Object.keys(PERMISSION_TYPE_LITERALS).length * stations.value.length,
        },
        {
          signal,
        },
      );
      permissionStore.setPermRecords(records);
      return null;
    },
  });
};
