<script setup lang="ts">
import { exportDeviceAlarmLogApi, pageDeviceAlarmLogApi, type NdmDeviceAlarmLog, type NdmDeviceAlarmLogPageQuery, 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 { useDeviceStore, usePermissionStore, useUnreadStore } from '@/stores';
import { downloadByData, parseErrorFeedback } from '@/utils';
import { useMutation } from '@tanstack/vue-query';
import { watchDebounced } from '@vueuse/core';
import { isCancel } from 'axios';
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, onBeforeUnmount, 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];
  alarmCategory: string;
  alarmConfirm: string;
}

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

const permissionStore = usePermissionStore();
const { permissions } = storeToRefs(permissionStore);

const stations = computed(() => permissionStore.stations.VIEW ?? []);

const deviceStore = useDeviceStore();
const { lineDevices } = storeToRefs(deviceStore);

const unreadStore = useUnreadStore();
const { unreadAlarmCount } = storeToRefs(unreadStore);

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,
  }));
});

// 权限变化时，需要刷新表格数据
watch(permissions, (newPermissions, oldPermissions) => {
  const oldPermissionsJson = JSON.stringify(oldPermissions);
  const newPermissionsJson = JSON.stringify(newPermissions);
  if (oldPermissionsJson === newPermissionsJson) return;
  onClickReset();
});

// 未读告警数量被清零时，代表从别的页面跳转过来，需要刷新告警表格数据
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()],
  alarmCategory: '',
  alarmConfirm: '',
});
const resetSearchFields = () => {
  searchFields.value = {
    stationCode_in: [],
    deviceType_in: [],
    deviceName_like: '',
    alarmType_in: [],
    faultLevel_in: [],
    alarmDate: [dayjs().startOf('date').valueOf(), dayjs().endOf('date').valueOf()],
    alarmCategory: '',
    alarmConfirm: '',
  };
};
const getModelFields = (): NdmDeviceAlarmLogPageQuery => {
  return {
    alarmCategory: searchFields.value.alarmCategory || undefined,
    alarmConfirm: searchFields.value.alarmConfirm || undefined,
  };
};
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 deviceNameLike = searchFields.value.deviceName_like;
  const alarmTypeIn = searchFields.value.alarmType_in;
  const faultLevelIn = searchFields.value.faultLevel_in;
  const alarmDateGe = searchFields.value.alarmDate[0];
  const alarmDateLe = searchFields.value.alarmDate[1];
  return {
    stationCode_in: stationCodeIn.length > 0 ? [...stationCodeIn] : stations.value.map((station) => station.code),
    deviceType_in: deviceTypeIn.length > 0 ? [...deviceTypeIn] : undefined,
    deviceName_like: deviceNameLike.length > 0 ? deviceNameLike : undefined,
    alarmType_in: alarmTypeIn.length > 0 ? [...alarmTypeIn] : undefined,
    faultLevel_in: faultLevelIn.length > 0 ? [...faultLevelIn] : 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> = [
  // { 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 && 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 = 20;
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 abortController = ref(new AbortController());

const { mutate: getTableData, isPending: tableLoading } = useMutation({
  mutationFn: async () => {
    abortController.value.abort();
    abortController.value = new AbortController();

    const signal = abortController.value.signal;

    const res = await pageDeviceAlarmLogApi(
      {
        model: getModelFields(),
        extra: getExtraFields(),
        current: pagination.page ?? 1,
        size: pagination.pageSize ?? DEFAULT_PAGE_SIZE,
        sort: 'id',
        order: 'descending',
      },
      {
        signal,
      },
    );

    return res;
  },
  onSuccess: (res) => {
    const { records, size, total } = res;
    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);
  },
});

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 () => {
    abortController.value.abort();
    abortController.value = new AbortController();

    const signal = abortController.value.signal;

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

onBeforeMount(() => {
  getTableData();
});
onBeforeUnmount(() => {
  abortController.value.abort();
});
</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">
          <NSelect
            clearable
            placeholder="请选择恢复状态"
            v-model:value="searchFields.alarmCategory"
            :options="[
              { label: '未恢复', value: '1' },
              { label: '已恢复', value: '2' },
            ]"
          />
        </NFormItemGi>
        <NFormItemGi span="1" label="确认状态" label-placement="left">
          <NSelect
            clearable
            placeholder="请选择确认状态"
            v-model:value="searchFields.alarmConfirm"
            :options="[
              { label: '未确认', value: '2' },
              { label: '已确认', value: '1' },
            ]"
          />
        </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>
