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

const props = defineProps<{
  stationCode: string;
  ndmSecurityBox: NdmSecurityBoxResultVO;
  dateTimeRange: DatePickerProps['value'];
}>();

const { stationCode, ndmSecurityBox, dateTimeRange } = toRefs(props);

const modalShow = ref(false);

type SecurityBoxCircuitRowData = { number: number } & NdmSecurityBoxCircuit;

const modalTableColumns: DataTableColumns<SecurityBoxCircuitRowData> = [
  { title: '电路序号', key: 'number' },
  {
    title: '状态',
    key: 'status',
    render(rowData) {
      const { status } = rowData;
      if (status === 1) {
        return '开启';
      } else if (status === 0) {
        return '关闭';
      } else {
        return '未知';
      }
    },
  },
  {
    title: '电流(A)',
    key: 'current',
    render(rowData) {
      return `${rowData.current.toFixed(3)}`;
    },
  },
  {
    title: '电压(V)',
    key: 'voltage',
    render(rowData) {
      return `${rowData.voltage.toFixed(3)}`;
    },
  },
];

const modalTableData = ref<DataTableRowData[]>([]);

type SecurityBoxRuntimeRowData = { createdTime: string; diagInfo: NdmSecurityBoxDiagInfo };

const tableColumns: DataTableColumns<SecurityBoxRuntimeRowData> = [
  { title: '诊断时间', key: 'createdTime' },
  {
    title: '温度(℃)',
    key: 'temperature',
    render(rowData) {
      const { info } = rowData.diagInfo;
      const boxInfo = info?.at(0);
      if (!boxInfo) return '';
      return boxInfo.temperature;
    },
  },
  {
    title: '湿度(%)',
    key: 'humidity',
    render(rowData) {
      const { info } = rowData.diagInfo;
      const boxInfo = info?.at(0);
      if (!boxInfo) return '';
      return boxInfo.humidity;
    },
  },
  {
    title: '风扇转速(rpm)',
    key: 'fanSpeeds',
    render(rowData) {
      const { info } = rowData.diagInfo;
      const boxInfo = info?.at(0);
      if (!boxInfo) return '';
      return h('pre', {}, { default: () => boxInfo.fanSpeeds?.join('\n') ?? '' });
    },
  },
  // { title: '开关状态', key: 'switches' },
  {
    title: '电路状态',
    key: 'circuits',
    render(rowData) {
      const { info } = rowData.diagInfo;
      const boxInfo = info?.at(0);
      if (!boxInfo) return '';
      return h(
        NButton,
        {
          text: true,
          type: 'info',
          size: 'small',
          onClick: () => {
            modalTableData.value = boxInfo.circuits?.map((circuit, index) => ({ ...circuit, number: index + 1 })) ?? [];
            modalShow.value = true;
          },
        },
        {
          default: () => '查看',
        },
      );
    },
  },
];

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 = ndmSecurityBox.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<NdmSecurityBoxDiagInfo>(diagInfoJsonString);
      if (!diagInfo) return {};
      if (typeof diagInfo !== 'object') return {};
      return {
        createdTime: record.createdTime,
        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>
  <NModal
    v-model:show="modalShow"
    :preset="'card'"
    :auto-focus="false"
    :transform-origin="'center'"
    :content-style="{
      height: '100%',
    }"
    style="min-width: 1400px; height: 100vh"
  >
    <NDataTable size="small" :columns="modalTableColumns" :data="modalTableData" :single-line="false" :remote="false" flex-height style="height: 100%" />
  </NModal>
</template>

<style scoped></style>
