<script lang="ts">
function getValueByFieldPath(record: Record<string, any>, fieldPath?: string) {
  if (!fieldPath) return undefined;
  return fieldPath.split('.').reduce((acc, cur) => acc?.[cur], record);
}
</script>

<script setup lang="ts">
import type { NdmDeviceResultVO, NdmSnmpLogResultVO, PageParams } from '@/apis';
import { pageSnmpLogApi } from '@/apis';
import { useMutation } from '@tanstack/vue-query';
import dayjs from 'dayjs';
import { destr } from 'destr';
import { NCard, NDataTable, type DataTableColumns, type DataTableRowData, type DatePickerProps, type PaginationProps } from 'naive-ui';
import { computed, h, reactive, ref, toRefs } from 'vue';

const props = defineProps<{
  stationCode: string;
  ndmDevice: NdmDeviceResultVO;
  dateTimeRange: DatePickerProps['value'];
  cpuUsageField?: string;
  memUsageField?: string;
  diskUsageField?: string;
}>();

const { stationCode, ndmDevice, dateTimeRange, cpuUsageField, memUsageField, diskUsageField } = toRefs(props);

const tableColumns = computed(() => {
  const columns: DataTableColumns<NdmSnmpLogResultVO> = [{ title: '诊断时间', key: 'createdTime' }];
  if (cpuUsageField.value) {
    columns.push({ title: 'CPU使用率(%)', key: 'cpuUsage' });
  }
  if (memUsageField.value) {
    columns.push({ title: '内存使用率(%)', key: 'memUsage' });
  }
  if (diskUsageField.value) {
    columns.push({ title: '磁盘使用率(%)', key: 'diskUsage' });
  }
  return columns;
});

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) => {
    pagination.page = page;
    getDeviceSnmpLogList();
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    getDeviceSnmpLogList();
  },
});

const { mutate: getDeviceSnmpLogList, isPending } = useMutation({
  mutationFn: async () => {
    if (!dateTimeRange.value) throw new Error('请选择时间范围');
    const range = dateTimeRange.value as [number, number];
    const deviceId = ndmDevice.value.id;
    const createdTime_precisest = dayjs(range[0]).format('YYYY-MM-DD HH:mm:ss');
    const createdTime_preciseed = dayjs(range[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 respData = await pageSnmpLogApi(
      {
        model: { deviceId },
        extra: { createdTime_precisest, createdTime_preciseed },
        ...restParams,
      },
      {
        stationCode: stationCode.value,
      },
    );
    return respData;
  },
  onSuccess: ({ records, size, total }) => {
    pagination.pageSize = parseInt(size);
    pagination.itemCount = parseInt(total);
    tableData.value = records.map((record) => {
      const diagInfoJsonString = record.diagInfo;
      const diagInfo = destr(diagInfoJsonString);
      if (!diagInfo) return {};
      if (typeof diagInfo !== 'object') return {};
      return {
        createdTime: record.createdTime,
        cpuUsage: getValueByFieldPath(diagInfo, cpuUsageField.value),
        memUsage: getValueByFieldPath(diagInfo, memUsageField.value),
        diskUsage: getValueByFieldPath(diagInfo, diskUsageField.value),
        diagInfo,
      };
    });
  },
  onError: (error) => {
    console.error(error);
    window.$message.error(error.message);
  },
});

defineExpose({
  isPending,
  refresh: () => {
    pagination.page = 1;
    pagination.pageSize = DEFAULT_PAGE_SIZE;
    getDeviceSnmpLogList();
  },
});
</script>

<template>
  <NCard size="small" title="设备硬件占用率记录">
    <NDataTable size="small" :loading="isPending" :columns="tableColumns" :data="tableData" :pagination="pagination" :single-line="false" remote flex-height style="height: 500px" />
  </NCard>
</template>

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