<script setup lang="ts">
import type { LineDevices, Station } from '@/apis';
import { DeviceType } from '@/enums';
import { NCard, NGrid, NGi, NStatistic, NSpace, NButton } from 'naive-ui';
import { computed, toRefs } from 'vue';

const props = defineProps<{
  stationList: Station[];
  lineDevices: LineDevices;
  buttonLoading: boolean;
}>();

const emit = defineEmits<{
  'export-online': [];
  'export-offline': [];
  'export-all': [];
}>();

const { stationList, lineDevices, buttonLoading } = toRefs(props);

const onlineDeviceCount = computed(() => {
  let count = 0;
  for (const station of stationList.value) {
    if (station.online) {
      const stationDevices = lineDevices.value[station.code];
      Object.values(DeviceType).forEach((deviceType) => {
        const onlineDeviceList = stationDevices?.[deviceType]?.filter((device) => device.deviceStatus === '10') ?? [];
        count += onlineDeviceList.length;
      });
    }
  }
  return count;
});

const offlineDeviceCount = computed(() => {
  let count = 0;
  for (const station of stationList.value) {
    if (station.online) {
      const stationDevices = lineDevices.value[station.code];
      Object.values(DeviceType).forEach((deviceType) => {
        const offlineDeviceList = stationDevices?.[deviceType]?.filter((device) => device.deviceStatus === '20') ?? [];
        count += offlineDeviceList.length;
      });
    }
  }
  return count;
});

const deviceCount = computed(() => onlineDeviceCount.value + offlineDeviceCount.value);

const onExportOnline = () => emit('export-online');
const onExportOffline = () => emit('export-offline');
const onExportAll = () => emit('export-all');
</script>

<template>
  <NCard bordered hoverable size="small" class="device-statistic-card" title="设备统计">
    <template #header-extra>
      <NSpace align="center">
        <NButton size="small" type="default" tertiary :disabled="buttonLoading" @click="onExportAll">导出全部</NButton>
        <NButton size="small" type="success" tertiary :disabled="buttonLoading" @click="onExportOnline">导出在线</NButton>
        <NButton size="small" type="error" tertiary :disabled="buttonLoading" @click="onExportOffline">导出离线</NButton>
      </NSpace>
    </template>

    <NGrid :cols="3" :x-gap="24" :y-gap="8">
      <NGi>
        <NStatistic label="全部设备" :value="deviceCount" />
      </NGi>
      <NGi>
        <NStatistic label="在线设备" :value="onlineDeviceCount" :value-style="{ color: '#18a058' }" />
      </NGi>
      <NGi>
        <NStatistic label="离线设备" :value="offlineDeviceCount" :value-style="{ color: '#d03050' }" />
      </NGi>
    </NGrid>
  </NCard>
</template>

<style scoped>
.device-statistic-card {
  margin: 8px;
}
</style>
