<script setup lang="ts">
import { exportDeviceAlarmLogApi, pageDeviceAlarmLogApi, type NdmDeviceAlarmLog, type NdmDeviceAlarmLogResultVO, type PageQueryExtra, type Station } from '@/apis';
import { useAlarmActionColumn, useCameraSnapColumn } from '@/composables';
import { ALARM_TYPES, DEVICE_TYPE_CODES, DEVICE_TYPE_LITERALS, DEVICE_TYPE_NAMES, FAULT_LEVELS, tryGetDeviceType, type DeviceType } from '@/enums';
import { renderAlarmDateCell, renderAlarmTypeCell, renderDeviceTypeCell, renderFaultLevelCell } from '@/helpers';
import { useAlarmStore, useDeviceStore, useStationStore } from '@/stores';
import { downloadByData, parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { watchDebounced } from '@vueuse/core';
import dayjs from 'dayjs';
import {
  NButton,
  NDataTable,
  NDatePicker,
  NFlex,
  NForm,
  NFormItemGi,
  NGi,
  NGrid,
  NInput,
  NSelect,
  NSwitch,
  type DataTableColumns,
  type DataTableRowData,
  type PaginationProps,
  type SelectOption,
} from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, h, onBeforeMount, reactive, ref, watch, type CSSProperties } from 'vue';
import { useRoute, useRouter } from 'vue-router';

interface SearchFields extends PageQueryExtra<NdmDeviceAlarmLog> {
  stationCode_in: Station['code'][];
  deviceType_in: string[];
  deviceName_like: string;
  alarmType_in: string[];
  faultLevel_in: string[];
  alarmDate: [number, number];
}

const route = useRoute();
const router = useRouter();

const stationStore = useStationStore();
const { stations } = storeToRefs(stationStore);
const deviceStore = useDeviceStore();
const { lineDevices } = storeToRefs(deviceStore);
const alarmStore = useAlarmStore();
const { unreadAlarmCount } = storeToRefs(alarmStore);

const stationSelectOptions = computed<SelectOption[]>(() => {
  return stations.value.map((station) => ({
    label: station.name,
    value: station.code,
  }));
});
const deviceTypeSelectOptions = computed<SelectOption[]>(() => {
  return Object.values(DEVICE_TYPE_LITERALS).map<SelectOption>((deviceType) => ({
    label: DEVICE_TYPE_NAMES[deviceType],
    value: deviceType,
  }));
});
const alarmTypeSelectOptions = computed<SelectOption[]>(() => {
  return Object.keys(ALARM_TYPES).map<SelectOption>((alarmType) => ({
    label: ALARM_TYPES[alarmType],
    value: alarmType,
  }));
});
const faultLevelSelectOptions = computed<SelectOption[]>(() => {
  return Object.keys(FAULT_LEVELS).map<SelectOption>((faultLevel) => ({
    label: FAULT_LEVELS[faultLevel],
    value: faultLevel,
  }));
});

// 未读告警数量被清零时，代表从别的页面跳转过来，需要刷新告警表格数据
const unreadCountCleared = computed(() => unreadAlarmCount.value === 0);
watch(unreadCountCleared, (newValue, oldValue) => {
  if (!oldValue && newValue) {
    // 不排除是在告警页面内点击了告警徽标按钮，因此要重置查询条件再执行查询
    onClickReset();
  }
});

const realtimeRefresh = ref(false);
watchDebounced(
  [unreadAlarmCount, realtimeRefresh],
  ([count, refresh]) => {
    if (count > 0 && refresh) {
      getTableData();
    }
  },
  {
    debounce: 500,
  },
);

const searchFields = ref<SearchFields>({
  stationCode_in: [],
  deviceType_in: [],
  deviceName_like: '',
  alarmType_in: [],
  faultLevel_in: [],
  alarmDate: [dayjs().startOf('date').valueOf(), dayjs().endOf('date').valueOf()],
});
const resetSearchFields = () => {
  searchFields.value = {
    stationCode_in: [],
    deviceType_in: [],
    deviceName_like: '',
    alarmType_in: [],
    faultLevel_in: [],
    alarmDate: [dayjs().startOf('date').valueOf(), dayjs().endOf('date').valueOf()],
  };
};
const getExtraFields = (): PageQueryExtra<NdmDeviceAlarmLog> => {
  const stationCodeIn = searchFields.value.stationCode_in;
  const deviceTypeIn = searchFields.value.deviceType_in.flatMap((deviceType) => DEVICE_TYPE_CODES[deviceType as DeviceType]);
  const alarmDateGe = searchFields.value.alarmDate[0];
  const alarmDateLe = searchFields.value.alarmDate[1];
  return {
    stationCode_in: stationCodeIn ? (stationCodeIn.length > 0 ? [...stationCodeIn] : undefined) : undefined,
    deviceType_in: deviceTypeIn ? (deviceTypeIn.length > 0 ? [...deviceTypeIn] : undefined) : undefined,
    deviceName_like: !!searchFields.value.deviceName_like ? searchFields.value.deviceName_like : undefined,
    alarmType_in: searchFields.value.alarmType_in.length > 0 ? [...searchFields.value.alarmType_in] : undefined,
    faultLevel_in: searchFields.value.faultLevel_in.length > 0 ? [...searchFields.value.faultLevel_in] : undefined,
    alarmDate_ge: alarmDateGe,
    alarmDate_le: alarmDateLe,
  };
};

const searchFieldsChanged = ref(false);
watch(searchFields, () => {
  searchFieldsChanged.value = true;
});

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

const { cameraSnapColumn } = useCameraSnapColumn(tableData);
const { alarmActionColumn } = useAlarmActionColumn(tableData);
const tableColumns: DataTableColumns<NdmDeviceAlarmLogResultVO & { snapUrl?: string }> = [
  // { title: '设备ID', key: 'deviceId' },
  // { title: '故障编码', key: 'faultCode', align: 'center' },
  // { title: '故障位置', key: 'faultLocation' },
  { title: '告警流水号', key: 'alarmNo' },
  { title: '告警时间', key: 'alarmDate', render: renderAlarmDateCell },
  { title: '车站', key: 'stationName', render: (rowData) => stations.value.find((station) => station.code === rowData.stationCode)?.name ?? '-' },
  { title: '设备类型', key: 'deviceType', render: renderDeviceTypeCell },
  {
    title: '设备名称',
    key: 'deviceName',
    render: (rowData) => {
      return h(
        'div',
        {
          style: { textDecoration: 'underline', cursor: 'pointer' } as CSSProperties,
          onClick: () => {
            const stationCode = rowData.stationCode;
            if (!stationCode) return;
            const deviceType = tryGetDeviceType(rowData.deviceType);
            if (!deviceType) return;
            const stationDevices = lineDevices.value[stationCode];
            if (!stationDevices) return;
            const classified = stationDevices[deviceType];
            const device = classified.find((device) => device.deviceId === rowData.deviceId);
            if (!device) return;
            const deviceDbId = device.id;
            router.push({
              path: '/device',
              query: {
                stationCode,
                deviceType,
                deviceDbId,
                fromPage: route.path,
              },
            });
          },
        },
        `${rowData.deviceName}`,
      );
    },
  },
  { title: '告警类型', key: 'alarmType', align: 'center', render: renderAlarmTypeCell },
  { title: '故障级别', key: 'faultLevel', align: 'center', render: renderFaultLevelCell },
  { title: '故障描述', key: 'faultDescription' },
  { title: '修复建议', key: 'alarmRepairSuggestion' },
  { title: '是否恢复', key: 'alarmCategory', align: 'center', render: (rowData) => (rowData.alarmCategory === '2' ? '是' : '否') },
  { title: '恢复时间', key: 'updatedTime' },
  cameraSnapColumn,
  alarmActionColumn,
];

const DEFAULT_PAGE_SIZE = 10;
const pagination = reactive<PaginationProps>({
  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 { mutate: getTableData, isPending: tableLoading } = useMutation({
  mutationFn: async () => {
    const res = await pageDeviceAlarmLogApi({
      model: {},
      extra: getExtraFields(),
      current: pagination.page ?? 1,
      size: pagination.pageSize ?? DEFAULT_PAGE_SIZE,
      sort: 'id',
      order: 'descending',
    });
    return res;
  },
  onSuccess: (res) => {
    const { records, size, total } = res;
    pagination.pageSize = parseInt(size);
    pagination.itemCount = parseInt(total);
    tableData.value = records;
  },
  onError: (error) => {
    console.error(error);
    const errorFeedback = parseErrorFeedback(error);
    window.$message.error(errorFeedback);
  },
});

const onClickReset = () => {
  resetSearchFields();
  pagination.page = 1;
  pagination.pageSize = DEFAULT_PAGE_SIZE;
  pagination.itemCount = 0;
  getTableData();
};
const onClickQuery = () => {
  // 点击查询按钮时关闭实时刷新
  realtimeRefresh.value = false;
  if (searchFieldsChanged.value) {
    pagination.page = 1;
    pagination.pageSize = DEFAULT_PAGE_SIZE;
    searchFieldsChanged.value = false;
  }
  getTableData();
};

const { mutate: exportTableData, isPending: exporting } = useMutation({
  mutationFn: async () => {
    const data = await exportDeviceAlarmLogApi({
      model: {},
      extra: getExtraFields(),
      current: pagination.page ?? 1,
      size: pagination.pageSize ?? 10,
      order: 'descending',
      sort: 'id',
    });
    return data;
  },
  onSuccess: (data) => {
    const time = dayjs().format('YYYY-MM-DD_HH-mm-ss');
    downloadByData(data, `设备告警记录_${time}.xlsx`);
  },
  onError: (error) => {
    console.error(error);
    const errorFeedback = parseErrorFeedback(error);
    window.$message.error(errorFeedback);
  },
});

onBeforeMount(() => {
  getTableData();
});
</script>

<template>
  <NFlex vertical :size="0" style="height: 100%">
    <!-- 查询面板 -->
    <NForm style="flex: 0 0 auto; padding: 8px">
      <NGrid cols="3" :x-gap="24">
        <NFormItemGi span="1" label="车站" label-placement="left">
          <NSelect multiple clearable placeholder="请选择车站" v-model:value="searchFields.stationCode_in" :options="stationSelectOptions" />
        </NFormItemGi>
        <NFormItemGi span="1" label="设备类型" label-placement="left">
          <NSelect multiple clearable placeholder="请选择设备类型" v-model:value="searchFields.deviceType_in" :options="deviceTypeSelectOptions" />
        </NFormItemGi>
        <NFormItemGi span="1" label="设备名称" label-placement="left">
          <NInput clearable placeholder="请输入设备名称" v-model:value="searchFields.deviceName_like" />
        </NFormItemGi>
        <NFormItemGi span="1" label="告警类型" label-placement="left">
          <NSelect multiple clearable placeholder="请选择告警类型" v-model:value="searchFields.alarmType_in" :options="alarmTypeSelectOptions" />
        </NFormItemGi>
        <NFormItemGi span="1" label="告警级别" label-placement="left">
          <NSelect multiple clearable placeholder="请选择告警级别" v-model:value="searchFields.faultLevel_in" :options="faultLevelSelectOptions" />
        </NFormItemGi>
        <NFormItemGi span="1" label="告警时间" label-placement="left">
          <NDatePicker v-model:value="searchFields.alarmDate" type="datetimerange" />
        </NFormItemGi>
      </NGrid>
      <!-- 操作按钮 -->
      <NGrid :cols="1">
        <NGi>
          <NFlex>
            <NButton @click="onClickReset">重置</NButton>
            <NButton type="primary" :loading="tableLoading" @click="onClickQuery">查询</NButton>
          </NFlex>
        </NGi>
      </NGrid>
    </NForm>

    <!-- 数据表格工具栏 -->
    <NFlex align="center" style="padding: 8px; flex: 0 0 auto">
      <div style="font-size: medium">视频平台日志</div>
      <NFlex align="center" style="margin-left: auto">
        <div>实时刷新</div>
        <NSwitch size="small" v-model:value="realtimeRefresh" />
        <NButton type="primary" :loading="exporting" @click="() => exportTableData()">导出</NButton>
      </NFlex>
    </NFlex>

    <!-- 数据表格 -->
    <NDataTable
      remote
      :columns="tableColumns"
      :data="tableData"
      :pagination="pagination"
      :loading="realtimeRefresh ? false : tableLoading"
      :single-line="false"
      flex-height
      style="height: 100%; padding: 8px; flex: 1 1 auto"
    />
  </NFlex>
</template>

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