<script setup lang="ts">
import type { Station } from '@/apis/domains';
import type { NdmDeviceAlarmLogResultVO } from '@/apis/models';
import { ndmDeviceAlarmLogDefaultExportByTemplate } from '@/apis/requests';
import type { StationAlarms } from '@/composables/query';
import { JAVA_INTEGER_MAX_VALUE } from '@/constants';
import { DeviceType, DeviceTypeName, type DeviceTypeVal } from '@/enums/device-type';
import { useQueryControlStore } from '@/stores/query-control';
import { downloadByData } from '@/utils/download';
import { useMutation } from '@tanstack/vue-query';
import dayjs from 'dayjs';
import { NButton, NCol, NDataTable, NModal, NRow, NSpace, NStatistic, type DataTableColumns, type DataTableRowData, type PaginationProps } from 'naive-ui';
import { computed, h, reactive, toRefs, watch } from 'vue';

interface Props {
  station: Station;
  stationAlarms?: StationAlarms;
}

const props = defineProps<Props>();
const { station, stationAlarms } = toRefs(props);
const show = defineModel<boolean>('show', { required: true });

watch(show, (newValue) => {
  const queryControlStore = useQueryControlStore();
  if (newValue) {
    console.log('对话框打开，停止轮询');
    queryControlStore.disablePolling();
  } else {
    console.log('对话框关闭，开启轮询');
    queryControlStore.enablePolling();
  }
});

const alarmCount = computed(() => {
  return Object.values(DeviceType).reduce((count, deviceType) => {
    return count + (stationAlarms.value?.[deviceType].length ?? 0);
  }, 0);
});

const classifiedCounts = computed(() => {
  return Object.values(DeviceType).map<{ label: string; count: number }>((deviceType) => {
    return {
      label: DeviceTypeName[deviceType],
      count: stationAlarms.value?.[deviceType].length ?? 0,
    };
  });
});

const tableColumns: DataTableColumns<NdmDeviceAlarmLogResultVO> = [
  { title: '告警流水号', key: 'alarmNo' },
  {
    title: '告警时间',
    key: 'alarmDate',
    render: (rowData /* , rowIndex */) => {
      return dayjs(Number(rowData.alarmDate ?? 0)).format('YYYY-MM-DD HH:mm:ss');
    },
  },
  {
    title: '设备类型',
    key: 'deviceType',
    render: (rowData) => {
      return DeviceTypeName[(rowData.deviceType ?? DeviceType.Camera) as DeviceTypeVal];
    },
    filterMultiple: true,
    filterOptions: Object.values(DeviceType).map((deviceType) => ({ label: DeviceTypeName[deviceType], value: deviceType })),
    filter: (filterOptionValue, row) => {
      return row.deviceType === filterOptionValue;
    },
  },
  { title: '设备名称', key: 'deviceName' },
  { title: '告警类型', key: 'alarmType', align: 'center' },
  { title: '故障级别', key: 'faultLevel', align: 'center' },
  { title: '故障编码', key: 'faultCode', align: 'center' },
  { title: '故障位置', key: 'faultLocation' },
  { title: '故障描述', key: 'faultDescription' },
  { title: '修复建议', key: 'alarmRepairSuggestion' },
  {
    title: '是否恢复',
    key: 'alarmCategory',
    align: 'center',
    render: (rowData) => {
      return rowData.alarmCategory === '2' ? '是' : '否';
    },
    filterMultiple: false,
    filterOptions: [
      { label: '是', value: '2' },
      { label: '否', value: '1' },
    ],
    filter: (filterOptionValue, row) => {
      return row.alarmCategory === filterOptionValue;
    },
  },
  { title: '恢复时间', key: 'updatedTime' },
  {
    title: '告警确认',
    key: 'alarmConfirm',
    align: 'center',
    render: (rowData) => {
      return rowData.alarmConfirm === '1' ? '已确认' : '未确认';
    },
    filterMultiple: false,
    filterOptions: [
      { label: '已确认', value: '1' },
      { label: '未确认', value: '2' },
    ],
    filter: (filterOptionValue, row) => {
      return row.alarmConfirm === filterOptionValue;
    },
  },
  // { title: '设备ID', key: 'deviceId' },
];

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

const tableData = computed<DataTableRowData[]>(() => stationAlarms.value?.unclassified ?? []);

const { mutate: downloadTableData, isPending: isDownloading } = useMutation({
  mutationFn: async () => {
    const data = await ndmDeviceAlarmLogDefaultExportByTemplate(station.value.code, {
      model: {},
      extra: {
        createdTime_precisest: dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss'),
        createdTime_preciseed: dayjs().endOf('date').format('YYYY-MM-DD HH:mm:ss'),
      },
      current: 1,
      size: JAVA_INTEGER_MAX_VALUE,
      order: 'descending',
      sort: 'id',
    });
    return data;
  },
  onSuccess: (data) => {
    downloadByData(data, `${station.value.name}-设备告警记录.xlsx`);
  },
  onError: (error) => {
    window.$message.error(error.message);
  },
});

const exportTableData = () => downloadTableData();

const onModalClose = () => {};
</script>

<template>
  <NModal v-model:show="show" preset="card" style="width: 100vw; height: 100vh" :title="`${station.name} - 设备告警详情`" :close-on-esc="false" :mask-closable="false" @close="onModalClose">
    <div v-if="alarmCount === 0" style="text-align: center; padding: 20px; color: #6c757d">
      <span>当前没有设备告警</span>
    </div>
    <div v-else style="height: 100%; display: flex; flex-direction: column">
      <div style="flex: 0 0 auto; margin-bottom: 16px">
        <NRow>
          <NCol :span="3" v-for="item in classifiedCounts" :key="item.label">
            <NStatistic :label="item.label + '告警'" :value="item.count" />
          </NCol>
        </NRow>
      </div>
      <div style="flex: 0 0 auto; display: flex; align-items: center; padding: 8px 0">
        <div style="font-size: medium">今日设备告警列表</div>
        <NSpace style="margin-left: auto">
          <NButton type="primary" :loading="isDownloading" @click="exportTableData">导出</NButton>
        </NSpace>
      </div>
      <div style="flex: 1 1 auto; min-height: 0">
        <NDataTable :columns="tableColumns" :data="tableData" :pagination="tablePagination" :single-line="false" flex-height style="height: 100%" />
      </div>
    </div>
  </NModal>
</template>

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