<script setup lang="ts">
import { getHighAvailableApi, type NdmServerResultVO, type Station } from '@/apis';
import { DEVICE_TYPE_LITERALS, tryGetDeviceType } from '@/enums';
import { useSettingStore } from '@/stores';
import { useQuery, useQueryClient } from '@tanstack/vue-query';
import { NAlert, NFlex } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, toRefs, watch } from 'vue';

const props = defineProps<{
  ndmDevice: NdmServerResultVO;
  station: Station;
}>();

const settingStore = useSettingStore();
const { activeRequests } = storeToRefs(settingStore);

const queryClient = useQueryClient();

const { ndmDevice, station } = toRefs(props);

const deviceType = computed(() => tryGetDeviceType(ndmDevice.value.deviceType));

const isVideoServer = computed(() => deviceType.value === DEVICE_TYPE_LITERALS.ndmVideoServer);

const SERVER_HIGH_AVAILABLE_QUERY_KEY = 'server-high-available-query';

const deviceUniqueKey = computed(() => [station.value.code, ndmDevice.value.id]);

const { data: highAvailable } = useQuery({
  queryKey: computed(() => [SERVER_HIGH_AVAILABLE_QUERY_KEY, deviceUniqueKey.value, ndmDevice.value.lastDiagTime]),
  enabled: computed(() => activeRequests.value && isVideoServer.value),
  refetchInterval: 30 * 1000,
  gcTime: 0,
  queryFn: async ({ signal }) => {
    const highAvailable = await getHighAvailableApi({ stationCode: station.value.code, signal });
    return highAvailable;
  },
});
watch(activeRequests, (active) => {
  if (!active) {
    queryClient.cancelQueries({ queryKey: [SERVER_HIGH_AVAILABLE_QUERY_KEY] });
  }
});

const showCard = computed(() => {
  const { pyip: physicalIp } = highAvailable.value ?? {};
  const ipAddressMatched = physicalIp === ndmDevice.value.ipAddress;
  return isVideoServer.value && ipAddressMatched;
});
</script>

<template>
  <NAlert v-if="showCard && !!highAvailable" :bordered="false" type="success">
    <template #header>
      <NFlex :align="'center'">
        <div>正在提供服务</div>
        <NFlex :align="'center'" style="font-size: smaller">
          <div>虚拟IP: {{ highAvailable.vip }}</div>
          <div>启用时间: {{ highAvailable.changeDate }}</div>
        </NFlex>
      </NFlex>
    </template>
  </NAlert>
</template>

<style scoped></style>
