<script setup lang="ts">
import { exportIcmpByStationApi, type Station } from '@/apis';
import { DEVICE_TYPE_LITERALS } from '@/enums';
import { useDeviceStore } from '@/stores';
import { downloadByData, parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { isCancel } from 'axios';
import dayjs from 'dayjs';
import { NButton, NFlex, NGrid, NGridItem, NModal, NRadio, NRadioGroup, NStatistic } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, ref, toRefs } from 'vue';

const props = defineProps<{
  stations: Station[];
}>();

const emit = defineEmits<{
  afterLeave: [];
}>();

const show = defineModel<boolean>('show');

const { stations } = toRefs(props);

const deviceStore = useDeviceStore();
const { lineDevices } = storeToRefs(deviceStore);

const status = ref('');

const abortController = ref<AbortController>(new AbortController());

const { mutate: exportIcmp, isPending: loading } = useMutation({
  mutationFn: async (params: { status: string }) => {
    abortController.value.abort();
    abortController.value = new AbortController();
    const data = await exportIcmpByStationApi(
      stations.value.map((station) => station.code),
      params.status,
      {
        signal: abortController.value.signal,
      },
    );
    return data;
  },
  onSuccess: (data, variables) => {
    const { status } = variables;
    let fileName = '全部设备列表';
    if (status === '10') {
      fileName = '在线设备列表';
    } else if (status === '20') {
      fileName = '离线设备列表';
    }
    const time = dayjs().format('YYYY-MM-DD_HH-mm-ss');
    downloadByData(data, `${fileName}_${time}.xlsx`);
  },
  onError: (error) => {
    if (isCancel(error)) return;
    console.error(error);
    const errorFeedback = parseErrorFeedback(error);
    window.$message.error(errorFeedback);
  },
});

const onAfterLeave = () => {
  abortController.value.abort();
  status.value = '';
  emit('afterLeave');
};

const onlineDeviceCount = computed(() => {
  let count = 0;
  for (const station of stations.value) {
    if (station.online) {
      const stationDevices = lineDevices.value[station.code];
      Object.values(DEVICE_TYPE_LITERALS).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 stations.value) {
    if (station.online) {
      const stationDevices = lineDevices.value[station.code];
      Object.values(DEVICE_TYPE_LITERALS).forEach((deviceType) => {
        const onlineDeviceList = stationDevices?.[deviceType]?.filter((device) => device.deviceStatus === '20') ?? [];
        count += onlineDeviceList.length;
      });
    }
  }
  return count;
});
const deviceCount = computed(() => onlineDeviceCount.value + offlineDeviceCount.value);
</script>

<template>
  <NModal v-model:show="show" preset="card" title="导出设备列表" @after-leave="onAfterLeave" style="width: 800px; height: 300px">
    <template #default>
      <NGrid :cols="3" :x-gap="24" :y-gap="8">
        <NGridItem>
          <NStatistic label="全部设备" :value="deviceCount" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="在线设备" :value="onlineDeviceCount" :value-style="{ color: '#18a058' }" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="离线设备" :value="offlineDeviceCount" :value-style="{ color: '#d03050' }" />
        </NGridItem>
      </NGrid>
    </template>
    <template #action>
      <NFlex justify="flex-end" align="center">
        <NRadioGroup v-model:value="status">
          <NRadio value="">全部</NRadio>
          <NRadio value="10">在线</NRadio>
          <NRadio value="20">离线</NRadio>
        </NRadioGroup>
        <NButton secondary :loading="loading" @click="() => exportIcmp({ status })">导出</NButton>
      </NFlex>
    </template>
  </NModal>
</template>

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