<script setup lang="ts">
import { batchExportRecordCheckApi, pageDefParameterApi, type Station } from '@/apis';
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, NScrollbar, NSpin } from 'naive-ui';
import { ref, toRefs } from 'vue';

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

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

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

const { stations } = toRefs(props);

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

const { mutate: batchExportRecordCheck, isPending: batchExporting } = useMutation({
  mutationFn: async (params: { stations: Station[] }) => {
    const timer = setTimeout(() => {
      if (!batchExporting.value) return;
      window.$message.info('导出耗时较长，请耐心等待...', { duration: 0 });
    }, 3000);

    try {
      abortController.value.abort();
      abortController.value = new AbortController();
      const { records = [] } = await pageDefParameterApi(
        {
          model: {
            key: 'NVR_GAP_SECONDS',
          },
          extra: {},
          current: 1,
          size: 1,
          sort: 'id',
          order: 'descending',
        },
        {
          signal: abortController.value.signal,
        },
      );
      const gapSeconds = parseInt(records.at(0)?.value ?? '5');

      abortController.value.abort();
      abortController.value = new AbortController();
      const data = await batchExportRecordCheckApi(
        {
          checkDuration: 90,
          gapSeconds,
          stationCode: params.stations.map((station) => station.code),
        },
        {
          signal: abortController.value.signal,
        },
      );

      return data;
    } finally {
      window.$message.destroyAll();
      clearTimeout(timer);
    }
  },
  onSuccess: (data, { stations }) => {
    const time = dayjs().format('YYYY-MM-DD_HH-mm-ss');
    let stationName = '';
    if (stations.length === 1) {
      const name = stations.at(0)?.name;
      if (!!name) {
        stationName = `${name}_`;
      }
    }
    downloadByData(data, `${stationName}录像缺失记录_${time}.xlsx`);
  },
  onError: (error) => {
    if (isCancel(error)) return;
    console.error(error);
    const errorFeedback = parseErrorFeedback(error);
    window.$message.error(errorFeedback);
  },
});

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

<template>
  <NModal v-model:show="show" preset="card" title="导出录像诊断" @after-leave="onAfterLeave" style="width: 800px">
    <template #default>
      <NScrollbar style="height: 300px">
        <NSpin size="small" :show="batchExporting">
          <NGrid :cols="6">
            <template v-for="station in stations" :key="station.code">
              <NGridItem>
                <NButton text type="info" style="height: 30px" @click="() => batchExportRecordCheck({ stations: [station] })">{{ station.name }}</NButton>
              </NGridItem>
            </template>
          </NGrid>
        </NSpin>
      </NScrollbar>
    </template>
    <template #action>
      <NFlex justify="flex-end" align="center">
        <NButton secondary :loading="batchExporting" @click="() => batchExportRecordCheck({ stations })">导出全部</NButton>
      </NFlex>
    </template>
  </NModal>
</template>

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