<script setup lang="ts">
import type { NdmAlarmHostResultVO, Station } from '@/apis';
import { DeviceAlarmHistoryCard, DeviceIcmpHistoryCard, HistoryDiagFilterCard, type DeviceAlarmHistoryCardProps, type DeviceIcmpHistoryCardProps } from '@/components';
import dayjs from 'dayjs';
import { NFlex, type SelectOption } from 'naive-ui';
import { onMounted, ref, toRefs, watch } from 'vue';

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

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

const historyDiagOptions: SelectOption[] = [
  { label: '设备状态', value: 'icmp' },
  { label: '设备告警', value: 'alarm' },
];
const getWeekRange = (): [number, number] => {
  const now = dayjs();
  const todayEnd = now.endOf('date');
  const weekAgo = now.subtract(1, 'week').startOf('date');
  return [weekAgo.valueOf(), todayEnd.valueOf()];
};
const range = ref<[number, number]>(getWeekRange());
const selected = ref<string[]>([...historyDiagOptions.map((option) => `${option.value}`)]);
const loading = ref<boolean>(false);
const icmpLoading = ref<boolean>(false);
const alarmLoading = ref<boolean>(false);
watch([icmpLoading, alarmLoading], (loadings) => {
  loading.value = loadings.some((loading) => loading);
});
const icmpHistoryQueryFn = ref<() => void>();
const onExposeIcmpHistoryQueryFn: DeviceIcmpHistoryCardProps['onExposeQueryFn'] = (queryFn) => {
  icmpHistoryQueryFn.value = queryFn;
};
const alarmHistoryQueryFn = ref<() => void>();
const onExposeAlarmHistoryQueryFn: DeviceAlarmHistoryCardProps['onExposeQueryFn'] = (queryFn) => {
  alarmHistoryQueryFn.value = queryFn;
};
const queryData = () => {
  if (selected.value.includes('icmp')) icmpHistoryQueryFn.value?.();
  if (selected.value.includes('alarm')) alarmHistoryQueryFn.value?.();
};
const onQuery = () => {
  queryData();
};

onMounted(() => {
  queryData();
});
</script>

<template>
  <NFlex vertical>
    <HistoryDiagFilterCard :options="historyDiagOptions" v-model:loading="loading" v-model:range="range" v-model:selected="selected" @query="onQuery" />
    <DeviceIcmpHistoryCard
      v-if="selected.includes('icmp')"
      :ndm-device="ndmDevice"
      :station="station"
      v-model:range="range"
      v-model:loading="icmpLoading"
      @expose-query-fn="onExposeIcmpHistoryQueryFn"
    />
    <DeviceAlarmHistoryCard
      v-if="selected.includes('alarm')"
      :ndm-device="ndmDevice"
      :station="station"
      v-model:range="range"
      v-model:loading="alarmLoading"
      @expose-query-fn="onExposeAlarmHistoryQueryFn"
    />
  </NFlex>
</template>

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