<script setup lang="ts">
import { isMediaServerAliveApi, isSipServerAliveApi, 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 { NCard, NTag } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, toRefs, watch } from 'vue';

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

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

const queryClient = useQueryClient();

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

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

const MEDIA_SERVER_ALIVE_QUERY_KEY = 'media-server-alive-query';
const VIDEO_SERVER_ALIVE_QUERY_KEY = 'video-server-alive-query';
const { data: isMediaServerAlive } = useQuery({
  queryKey: computed(() => [MEDIA_SERVER_ALIVE_QUERY_KEY, ndmDevice.value.id, ndmDevice.value.lastDiagTime]),
  enabled: computed(() => !offlineDev.value && deviceType.value === DEVICE_TYPE_LITERALS.ndmMediaServer),
  refetchInterval: 30 * 1000,
  gcTime: 0,
  queryFn: async ({ signal }) => {
    const alives = await isMediaServerAliveApi({ stationCode: station.value.code, signal });
    return alives.find((alive) => alive.ip === ndmDevice.value.ipAddress);
  },
});
const { data: isSipServerAlive } = useQuery({
  queryKey: computed(() => [VIDEO_SERVER_ALIVE_QUERY_KEY, ndmDevice.value.id, ndmDevice.value.lastDiagTime]),
  enabled: computed(() => !offlineDev.value && deviceType.value === DEVICE_TYPE_LITERALS.ndmVideoServer),
  refetchInterval: 30 * 1000,
  gcTime: 0,
  queryFn: async ({ signal }) => {
    return await isSipServerAliveApi({ stationCode: station.value.code, signal });
  },
});
watch(offlineDev, (offline) => {
  if (offline) {
    queryClient.cancelQueries({ queryKey: [MEDIA_SERVER_ALIVE_QUERY_KEY] });
    queryClient.cancelQueries({ queryKey: [VIDEO_SERVER_ALIVE_QUERY_KEY] });
  }
});
</script>

<template>
  <NCard hoverable size="small">
    <template #header>
      <span>服务状态</span>
    </template>
    <template #default>
      <div v-if="deviceType === DEVICE_TYPE_LITERALS.ndmMediaServer">
        <span>流媒体服务状态：</span>
        <template v-if="!!isMediaServerAlive">
          <NTag size="small" :type="isMediaServerAlive.online ? 'success' : 'error'">{{ isMediaServerAlive.online ? '在线' : '离线' }}</NTag>
        </template>
        <span v-else>-</span>
      </div>
      <div v-if="deviceType === DEVICE_TYPE_LITERALS.ndmVideoServer">
        <span>信令服务状态：</span>
        <template v-if="isSipServerAlive !== undefined">
          <NTag size="small" :type="isSipServerAlive ? 'success' : 'error'">{{ isSipServerAlive ? '在线' : '离线' }}</NTag>
        </template>
        <span v-else>-</span>
      </div>
    </template>
  </NCard>
</template>

<style scoped lang="scss"></style>
