<script setup lang="ts">
import type { NdmNvrResultVO } from '@/apis';
import { DeviceAlarmHistoryDiagCard, DeviceStatusHistoryDiagCard, DeviceUsageHistoryDiagCard, isNvrCluster, NvrDiskHealthHistoryDiagCard } from '@/components';
import dayjs from 'dayjs';
import { NButton, NCard, NDatePicker, NFlex, NGi, NGrid, NSelect, type DatePickerProps, type SelectOption } from 'naive-ui';
import { computed, onMounted, reactive, ref, toRefs, useTemplateRef } from 'vue';

const props = defineProps<{
  stationCode: string;
  ndmNvr: NdmNvrResultVO;
}>();

const { stationCode, ndmNvr } = toRefs(props);

const searchFields = reactive({
  dateTimeRange: undefined as DatePickerProps['value'],
});
const onDateChange = (value: [number, number] | null) => {
  if (!value) {
    return;
  }
  const [start, end] = value;
  const diffDays = dayjs(end).diff(dayjs(start), 'day');
  if (diffDays > 7) {
    // 如果超过7天，自动调整结束时间
    const adjustedEnd = dayjs(start).add(7, 'day').valueOf();
    searchFields.dateTimeRange = [start, adjustedEnd];
    window.$message.warning('时间范围不能超过7天，已自动调整');
  } else {
    searchFields.dateTimeRange = value;
  }
};

type DeviceStatusHistoryDiagCardInst = InstanceType<typeof DeviceStatusHistoryDiagCard> | null;
type DeviceAlarmHistoryDiagCardInst = InstanceType<typeof DeviceAlarmHistoryDiagCard> | null;
type DeviceUsageHistoryDiagCardInst = InstanceType<typeof DeviceUsageHistoryDiagCard> | null;
type NvrDiskHealthHistoryCardInst = InstanceType<typeof NvrDiskHealthHistoryDiagCard> | null;
const deviceStatusHistoryDiagCardRef = useTemplateRef<DeviceStatusHistoryDiagCardInst>('deviceStatusHistoryDiagCardRef');
const deviceAlarmHistoryDiagCardRef = useTemplateRef<DeviceAlarmHistoryDiagCardInst>('deviceAlarmHistoryDiagCardRef');
const deviceUsageHistoryDiagCardRef = useTemplateRef<DeviceUsageHistoryDiagCardInst>('deviceUsageHistoryDiagCardRef');
const nvrDiskHealthHistoryCardRef = useTemplateRef<NvrDiskHealthHistoryCardInst>('nvrDiskHealthHistoryCardRef');

function refreshData() {
  deviceStatusHistoryDiagCardRef.value?.refresh();
  deviceAlarmHistoryDiagCardRef.value?.refresh();
  deviceUsageHistoryDiagCardRef.value?.refresh();
  nvrDiskHealthHistoryCardRef.value?.refresh();
}

const loading = computed(() => {
  return (
    deviceStatusHistoryDiagCardRef.value?.isPending || deviceAlarmHistoryDiagCardRef.value?.isPending || deviceUsageHistoryDiagCardRef.value?.isPending || nvrDiskHealthHistoryCardRef.value?.isPending
  );
});

onMounted(() => {
  const now = dayjs();
  const todayEnd = now.endOf('date');
  const weekAgo = now.subtract(1, 'week').startOf('date');
  searchFields.dateTimeRange = [weekAgo.valueOf(), todayEnd.valueOf()];
  refreshData();
});

const diagCards = computed<SelectOption[]>(() => {
  const baseOptions: SelectOption[] = [
    { label: '设备状态', value: 'status' },
    { label: '设备告警', value: 'alarm' },
  ];
  if (!isNvrCluster(ndmNvr.value)) {
    baseOptions.push({ label: '硬件使用率', value: 'usage' }, { label: '硬盘健康', value: 'health' });
  }
  return baseOptions;
});

const selectedCards = ref<string[]>([...diagCards.value.map((option) => `${option.value ?? ''}`)]);
</script>

<template>
  <NCard size="small">
    <NFlex vertical>
      <NCard size="small">
        <NFlex justify="space-between" :wrap="false">
          <NGrid :x-gap="8" :y-gap="8">
            <NGi :span="20">
              <NDatePicker v-model:value="searchFields.dateTimeRange" type="datetimerange" @update:value="onDateChange" />
            </NGi>
            <NGi :span="20">
              <NSelect v-model:value="selectedCards" multiple :options="diagCards" />
            </NGi>
          </NGrid>
          <NButton secondary :loading="loading" @click="refreshData">刷新数据</NButton>
        </NFlex>
      </NCard>

      <DeviceStatusHistoryDiagCard
        v-if="selectedCards.includes('status')"
        :ref="'deviceStatusHistoryDiagCardRef'"
        :station-code="stationCode"
        :ndm-device="ndmNvr"
        :date-time-range="searchFields.dateTimeRange"
      />
      <DeviceAlarmHistoryDiagCard
        v-if="selectedCards.includes('alarm')"
        :ref="'deviceAlarmHistoryDiagCardRef'"
        :station-code="stationCode"
        :ndm-device="ndmNvr"
        :date-time-range="searchFields.dateTimeRange"
      />
      <DeviceUsageHistoryDiagCard
        v-if="selectedCards.includes('usage')"
        :ref="'deviceUsageHistoryDiagCardRef'"
        :station-code="stationCode"
        :ndm-device="ndmNvr"
        :date-time-range="searchFields.dateTimeRange"
        :cpu-usage-field="'stCommonInfo.CPU使用率'"
        :mem-usage-field="'stCommonInfo.内存使用率'"
      />
      <NvrDiskHealthHistoryDiagCard
        v-if="selectedCards.includes('health')"
        :ref="'nvrDiskHealthHistoryCardRef'"
        :station-code="stationCode"
        :ndm-nvr="ndmNvr"
        :date-time-range="searchFields.dateTimeRange"
      />
    </NFlex>
  </NCard>
</template>

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