<script setup lang="ts">
import { pageDeviceAlarmLogApi, type NdmDeviceAlarmLogResultVO, type NdmDeviceResultVO, type PageParams, type Station } from '@/apis';
import { renderAlarmDateCell, renderAlarmTypeCell, renderFaultDescriptionCell, renderFaultLevelCell } from '@/helpers';
import { parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { isCancel } from 'axios';
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: NdmDeviceResultVO;
  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<NdmDeviceAlarmLogResultVO> = [
  { title: '告警流水号', key: 'alarmNo' },
  {
    title: '告警时间',
    key: 'alarmDate',
    render: renderAlarmDateCell,
  },
  {
    title: '告警类型',
    key: 'alarmType',
    align: 'center',
    render: renderAlarmTypeCell,
  },
  {
    title: '故障级别',
    key: 'faultLevel',
    align: 'center',
    render: renderFaultLevelCell,
  },
  // { title: '故障编码', key: 'faultCode', align: 'center' },
  {
    title: '故障描述',
    key: 'faultDescription',
    render: (rowData) => renderFaultDescriptionCell(rowData, ndmDevice.value),
  },
  {
    title: '是否恢复',
    key: 'alarmCategory',
    align: 'center',
    render: (rowData) => {
      return rowData.alarmCategory === '2' ? '是' : '否';
    },
  },
  { title: '恢复时间', key: 'updatedTime' },
];

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.deviceId;
    if (!deviceId) throw new Error('该设备未配置设备ID，无法查询告警记录');
    abortController.value?.abort();
    abortController.value = new AbortController();
    const alarmDate_ge = range.value[0];
    const alarmDate_le = range.value[1];
    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 pageDeviceAlarmLogApi(
      {
        model: { deviceId },
        extra: { alarmDate_ge, alarmDate_le },
        ...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;
  },
  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 lang="scss"></style>
