<script lang="ts">
type NvrDiskHealthRowData = {
  createdTime: string;
  diskHealthRatio: string;
  diskHealth: number[];
};
</script>

<script setup lang="ts">
import { pageSnmpLogApi, type NdmNvrDiagInfo, type NdmNvrResultVO, type PageParams, type Station } from '@/apis';
import { parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { isCancel } from 'axios';
import dayjs from 'dayjs';
import destr from 'destr';
import { NCard, NDataTable, type DataTableColumns, type DataTableRowData, type PaginationProps } from 'naive-ui';
import { h, onBeforeUnmount, reactive, ref, toRefs, watch } from 'vue';

const props = defineProps<{
  ndmDevice: NdmNvrResultVO;
  station: Station;
}>();

const range = defineModel<[number, number]>('range');
const loading = defineModel<boolean>('loading', { default: false });

const emit = defineEmits<{
  exposeQueryFn: [queryFn: () => void];
}>();

const { ndmDevice, station } = toRefs(props);

const tableColumns: DataTableColumns<NvrDiskHealthRowData> = [
  { title: '诊断时间', key: 'createdTime' },
  { title: '磁盘健康度', key: 'diskHealthRatio' },
  {
    title: '描述',
    key: 'desc',
    render(rowData) {
      const { diskHealth } = rowData;
      const unhealthyDiskIndexes = diskHealth
        .map((health, index) => ({ index, health }))
        .filter(({ health }) => health !== 0)
        .map(({ index }) => index);
      if (unhealthyDiskIndexes.length === 0) return '正常';
      return `磁盘${unhealthyDiskIndexes.join(', ')}异常`;
    },
  },
];

const tableData = ref<DataTableRowData[]>([]);
const DEFAULT_PAGE_SIZE = 10;
const pagination = reactive<PaginationProps>({
  size: 'small',
  showSizePicker: true,
  page: 1,
  pageSize: DEFAULT_PAGE_SIZE,
  pageSizes: [5, 10, 20, 50, 80, 100],
  itemCount: 0,
  prefix: ({ itemCount }) => {
    return h('div', {}, { default: () => `共${itemCount}条` });
  },
  onUpdatePage: (page: number) => {
    pagination.page = page;
    getTableData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    getTableData();
  },
});

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

const { mutate: getTableData, isPending } = useMutation({
  mutationFn: async () => {
    if (!range.value) throw new Error('请选择时间范围');
    const deviceId = ndmDevice.value.id;
    if (!deviceId) throw new Error('该设备没有ID');
    abortController.value?.abort();
    abortController.value = new AbortController();
    const createdTime_precisest = dayjs(range.value[0]).format('YYYY-MM-DD HH:mm:ss');
    const createdTime_preciseed = dayjs(range.value[1]).format('YYYY-MM-DD HH:mm:ss');
    const restParams: Omit<PageParams<{ id: string }>, 'model' | 'extra'> = {
      current: pagination.page ?? 1,
      size: pagination.pageSize ?? DEFAULT_PAGE_SIZE,
      sort: 'id',
      order: 'descending',
    };
    const pageResult = await pageSnmpLogApi(
      {
        model: { deviceId },
        extra: { createdTime_precisest, createdTime_preciseed },
        ...restParams,
      },
      {
        stationCode: station.value.code,
        signal: abortController.value.signal,
      },
    );
    return pageResult;
  },
  onSuccess: ({ records, size, total }) => {
    pagination.pageSize = parseInt(size);
    pagination.itemCount = parseInt(total);
    tableData.value = records.map((record) => {
      const diagInfoJsonString = record.diagInfo;
      const diagInfo = destr<NdmNvrDiagInfo>(diagInfoJsonString);
      if (!diagInfo) return {};
      if (typeof diagInfo !== 'object') return {};
      const healthDiskCount = diagInfo.info?.diskHealth?.filter((health) => health === 0).length ?? 0;
      const totalDiskCount = diagInfo.info?.diskHealth?.length ?? 0;
      return {
        createdTime: record.createdTime,
        diskHealthRatio: `${healthDiskCount}/${totalDiskCount}`,
        diskHealth: diagInfo.info?.diskHealth ?? [],
      };
    });
  },
  onError: (error) => {
    if (isCancel(error)) return;
    console.error(error);
    const errorFeedback = parseErrorFeedback(error);
    window.$message.error(errorFeedback);
  },
});

emit('exposeQueryFn', () => {
  pagination.page = 1;
  pagination.pageSize = DEFAULT_PAGE_SIZE;
  getTableData();
});

watch(isPending, (pending) => {
  loading.value = pending;
});

onBeforeUnmount(() => {
  abortController.value.abort();
});
</script>

<template>
  <NCard hoverable size="small">
    <template #header>
      <span>磁盘健康度记录</span>
    </template>
    <template #default>
      <NDataTable size="small" :loading="isPending" :columns="tableColumns" :data="tableData" :pagination="pagination" :single-line="false" remote flex-height style="height: 500px" />
    </template>
  </NCard>
</template>

<style scoped></style>
