<script setup lang="ts">
import type { NdmKeyboardResultVO } from '@/apis/models';
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';

import DeviceStatusHistoryDiagCard from './device-status-history-diag-card.vue';

const props = defineProps<{
  stationCode: string;
  ndmKeyboard: NdmKeyboardResultVO;
}>();

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

const searchFields = reactive({
  dateTimeRange: undefined as DatePickerProps['value'],
});

type DeviceStatusHistoryDiagCardInst = InstanceType<typeof DeviceStatusHistoryDiagCard> | null;
const deviceStatusHistoryDiagCardRef = useTemplateRef<DeviceStatusHistoryDiagCardInst>('deviceStatusHistoryDiagCardRef');

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

const loading = computed(() => {
  return deviceStatusHistoryDiagCardRef.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 = ref<SelectOption[]>([{ label: '设备状态', value: 'status' }]);

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" />
            </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="ndmKeyboard"
        :date-time-range="searchFields.dateTimeRange"
      />
    </NFlex>
  </NCard>
</template>

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