<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 } from '@/apis/models';
import { useDeviceSnmpLogsQuery } from '@/composables/query';
import { destr } from 'destr';
import { NCard, NDataTable, type DataTableColumns, type DataTableRowData } from 'naive-ui';
import { computed, toRefs } from 'vue';

const props = defineProps<{
  stationCode: string;
  ndmDevice: NdmDeviceResultVO;
  dateTimeRange: [number, number];
  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 { snmpLogRespData, isPending, pagination, refresh } = useDeviceSnmpLogsQuery(stationCode, ndmDevice, dateTimeRange);
const tableData = computed<DataTableRowData[]>(() => {
  const { records = [] } = snmpLogRespData.value ?? {};
  return 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,
    };
  });
});

defineExpose({
  isPending,
  refresh,
});
</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>
