<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { ProModal } from 'antdv-pro-modal';
import { message, Modal } from 'ant-design-vue/es';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { MenuInfo } from 'ant-design-vue/es/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/es/table';
import { listAct, exportAll } from '@/api/faultManage/eventAlarm';
import useI18n from '@/hooks/useI18n';
import useNeStore from '@/store/modules/ne';
import saveAs from 'file-saver';
import TableColumnsDnd from '@/components/TableColumnsDnd/index.vue';
import { writeSheet } from '@/utils/execl-utils';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { parseDateToStr } from '@/utils/date-utils';
import dayjs, { type Dayjs } from 'dayjs';
const neListStore = useNeStore();
const { t } = useI18n();

/**表格字段列排序 */
let tableColumnsDnd = ref<ColumnsType>([]);

/**开始结束时间 */
let queryRangePicker = ref<[Dayjs, Dayjs] | undefined>(undefined);
/**时间范围 */
let rangePickerPresets = ref([
  {
    label: 'Now hour',
    value: [dayjs().startOf('hour'), dayjs().endOf('hour')],
  },
  { label: 'Today', value: [dayjs().startOf('day'), dayjs().endOf('day')] },
  {
    label: 'Yesterday',
    value: [
      dayjs().subtract(1, 'day').startOf('day'),
      dayjs().subtract(1, 'day').endOf('day'),
    ],
  },
]);

/**查询参数 */
let queryParams = reactive({
  sortField: 'event_time',
  sortOrder: 'desc',
  /**告警设备类型 */
  neType: '',
  /**告警网元名称 */
  neName: '',
  /**告警网元标识 */
  neId: '',
  /**告警编号 */
  alarmCode: '',
  /**告警级别 */
  origSeverity: undefined,
  /**告警产生时间开始时间 */
  beginTime: undefined as undefined | number,
  /**告警产生时间结束时间 */
  endTime: undefined as undefined | number,
  /**虚拟化标识 */
  pvFlag: undefined,
  /**告警类型 */
  alarmType: undefined,
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    /**告警设备类型 */
    neType: '',
    /**告警网元名称 */
    neName: '',
    /**告警网元标识 */
    neId: '',
    /**告警编号 */
    alarmCode: '',
    /**告警级别 */
    origSeverity: undefined,
    /**告警产生时间 */
    beginTime: undefined,
    endTime: undefined,
    /**虚拟化标识 */
    pvFlag: undefined,
    /**告警类型 */
    alarmType: undefined,
    /**当前页数 */
  });
  queryRangePicker.value = undefined;
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  fnGetList();
}

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**搜索栏 */
  seached: boolean;
  /**记录数据 */
  data: object[];
  /**勾选记录 */
  selectedRowKeys: (string | number)[];
};

/**表格状态 */
let tableState: TabeStateType = reactive({
  loading: false,
  size: 'middle',
  seached: false,
  data: [],
  selectedRowKeys: [],
});

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('views.faultManage.activeAlarm.alarmTitle'),
    dataIndex: 'alarmTitle',
    align: 'left',
    width: 200,
    ellipsis: true,
  },

  {
    title: t('views.faultManage.activeAlarm.eventTime'),
    dataIndex: 'eventTime',
    align: 'left',
    width: 200,
    customRender(opt) {
      if (typeof opt.value === 'number') {
        return parseDateToStr(+opt.value);
      }
      return opt.value;
    },
  },
  {
    title: t('views.faultManage.activeAlarm.alarmId'),
    dataIndex: 'alarmId',
    align: 'left',
    width: 150,
    ellipsis: true,
  },
  {
    title: t('views.faultManage.activeAlarm.alarmCode'),
    dataIndex: 'alarmCode',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.common.neType'),
    dataIndex: 'neType',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.common.neId'),
    dataIndex: 'neId',
    align: 'left',
    width: 100,
  },
  {
    title: t('common.operate'),
    key: 'id',
    align: 'left',
    fixed: 'right',
    width: 100,
  },
];

/**表格分页器参数 */
let tablePagination = reactive({
  /**当前页数 */
  current: 1,
  /**每页条数 */
  pageSize: 20,
  /**默认的每页条数 */
  defaultPageSize: 20,
  /**指定每页可以显示多少条 */
  pageSizeOptions: ['10', '20', '50', '100'],
  /**只有一页时是否隐藏分页器 */
  hideOnSinglePage: false,
  /**是否可以快速跳转至某页 */
  showQuickJumper: true,
  /**是否可以改变 pageSize */
  showSizeChanger: true,
  /**数据总数 */
  total: 0,
  showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
  onChange: (page: number, pageSize: number) => {
    tablePagination.current = page;
    tablePagination.pageSize = pageSize;
    queryParams.pageNum = page;
    queryParams.pageSize = pageSize;
    fnGetList();
  },
});

/**表格紧凑型变更操作 */
function fnTableSize({ key }: MenuInfo) {
  tableState.size = key as SizeType;
}

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**详情框是否显示 */
  openByView: boolean;
  /**新增框或修改框是否显示 */
  openByEdit: boolean;
  /**显示过滤设置是否显示 */
  openByShowSet: boolean;
  /**个性化设置置是否显示 */
  openByMyselfSet: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**表单数据 */
  showSetFrom: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByView: false,
  openByEdit: false,
  openByShowSet: false,
  openByMyselfSet: false,
  title: '全部信息',
  from: {
    alarmId: '',
    alarmSeq: '',
    neId: '',
    neName: '',
    neType: '',
    alarmCode: '',
    alarmTitle: '',
    eventTime: '',
    alarmType: '',
    pvFlag: '',
    objectName: '',
    locationInfo: '',
    province: '',
    alarmStatus: '',
    specificProblemId: '',
    specificProblem: '',
    addInfo: '',
    clearType: '',
    clearTime: '',
    ackState: '',
    ackUser: '',
    ackTime: '',
    origSeverity: '',
  },
  showSetFrom: {
    ne_type: '',
    ne_id: '',
    alarm_type: '',
    orig_severity: '',
    alarm_code: '',
    pv_flag: '',
  },
  // myselfSetFrom:{

  // }
  confirmLoading: false,
});

/**
 * 对话框弹出显示为 查看
 * @param row 单行记录信息
 */
function fnModalVisibleByVive(row: Record<string, any>) {
  modalState.from = Object.assign(modalState.from, row);
  modalState.from.clearType = `${modalState.from.clearType}`;
  modalState.from.ackState = `${modalState.from.ackState}`;
  modalState.title = t('views.faultManage.activeAlarm.viewIdInfo', {
    alarmId: row.alarmId,
  });
  modalState.openByView = true;
}

/**表格状态 */
const state = reactive<{
  selectedRowKeys: (string | number)[];
  selectedRow: Record<string, any>;
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  selectedRow: {},
  loading: false,
});

/**监听多选 */
const onSelectChange = (
  keys: (string | number)[],
  record: Record<string, any>
) => {
  state.selectedRowKeys = keys;
  state.selectedRow = record;
};

// key替换中文title
function mapKeysWithReduce(data: any, titleMapping: any) {
  return data.map((item: any) => {
    return Object.keys(item).reduce((newItem: any, key: any) => {
      const title = titleMapping[key] || key;
      newItem[title] = item[key];
      return newItem;
    });
  });
}

/**
 * 导出全部
 */
function fnExportAll() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.faultManage.eventAlarm.exportSure'),
    onOk() {
      const key = 'exportAlarm';
      message.loading({ content: t('common.loading'), key });
      let sortArr: any = [];
      let writeSheetOpt: any = [];
      let mappArr: any = {};
      tableColumnsDnd.value.forEach((item: any) => {
        if (item.dataIndex) {
          sortArr.push(item.dataIndex);
          writeSheetOpt.push(item.title);
          mappArr[item.dataIndex] = item.title;
        }
      });
      // 排序字段
      const sortData = {
        header: writeSheetOpt,
      };

      exportAll(queryParams).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          res.data = res.data.map((objA: any) => {
            let filteredObj: any = {};
            sortArr.forEach((key: any) => {
              if (objA.hasOwnProperty(key)) {
                filteredObj[key] = objA[key];
              }
            });

            return filteredObj;
          });
          res.data = mapKeysWithReduce(res.data, mappArr);

          writeSheet(res.data, 'alarm', sortData).then(fileBlob => {
            saveAs(fileBlob, `evnet_${Date.now()}.xlsx`);

            message.success({
              content: t('common.msgSuccess', { msg: t('common.export') }),
              key,
              duration: 3,
            });
          });
        } else {
          message.error({
            content: `${res.msg}`,
            key,
            duration: 3,
          });
        }
      });
    },
  });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.openByEdit = false;
  modalState.openByView = false;
}

/**查询列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }

  // 时间范围
  if (
    Array.isArray(queryRangePicker.value) &&
    queryRangePicker.value.length > 0
  ) {
    queryParams.beginTime = queryRangePicker.value[0].valueOf();
    queryParams.endTime = queryRangePicker.value[1].valueOf();
  } else {
    queryParams.beginTime = undefined;
    queryParams.endTime = undefined;
  }

  listAct(toRaw(queryParams)).then((res: any) => {
    if (res.code === RESULT_CODE_SUCCESS) {
      // 取消勾选
      if (state.selectedRowKeys.length > 0) {
        state.selectedRowKeys = [];
      }
      ////
      const { total, rows } = res.data;
      tablePagination.total = total;
      tableState.data = rows;
      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    } else {
      tablePagination.total = 0;
      tableState.data = [];
    }
    tableState.loading = false;
  });
}

onMounted(() => {
  // 获取列表
  fnGetList();
});
</script>

<template>
  <PageContainer>
    <a-card
      v-show="tableState.seached"
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="4" :md="12" :xs="24">
            <a-form-item :label="t('views.ne.common.neType')" name="neType">
              <a-auto-complete
                v-model:value="queryParams.neType"
                :options="neListStore.getNeSelectOtions"
                allow-clear
                :placeholder="t('views.ne.common.neTypePlease')"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.alarmCode')"
              name="alarm_code"
            >
              <a-input
                v-model:value="queryParams.alarmCode"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.eventTime')"
              name="eventTime"
            >
              <a-range-picker
                v-model:value="queryRangePicker"
                :presets="rangePickerPresets"
                :bordered="true"
                :allow-clear="false"
                style="width: 100%"
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
              ></a-range-picker>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnGetList(1)">
                  <template #icon><SearchOutlined /></template>
                  {{ t('common.search') }}
                </a-button>
                <a-button type="default" @click.prevent="fnQueryReset">
                  <template #icon><ClearOutlined /></template>
                  {{ t('common.reset') }}
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-space :size="8" align="center" v-if="false">
          <a-button
            type="primary"
            @click.prevent="fnExportAll()"
            :disabled="tableState.data.length <= 0"
          >
            <template #icon> <export-outlined /> </template>
            {{ t('views.faultManage.activeAlarm.exportAll') }}
          </a-button>
        </a-space>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('common.searchBarText') }}</template>
            <a-switch
              v-model:checked="tableState.seached"
              :checked-children="t('common.switch.show')"
              :un-checked-children="t('common.switch.hide')"
              size="small"
            />
          </a-tooltip>
          <a-tooltip>
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip>
            <template #title>{{ t('common.sizeText') }}</template>
            <a-dropdown trigger="click">
              <a-button type="text">
                <template #icon><ColumnHeightOutlined /></template>
              </a-button>
              <template #overlay>
                <a-menu
                  :selected-keys="[tableState.size as string]"
                  @click="fnTableSize"
                >
                  <a-menu-item key="default">
                    {{ t('common.size.default') }}
                  </a-menu-item>
                  <a-menu-item key="middle">
                    {{ t('common.size.middle') }}
                  </a-menu-item>
                  <a-menu-item key="small">
                    {{ t('common.size.small') }}
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-tooltip>
          <TableColumnsDnd
            cache-id="alarmEvent"
            :columns="tableColumns"
            v-model:columns-dnd="tableColumnsDnd"
          ></TableColumnsDnd>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="id"
        :columns="tableColumnsDnd"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ x: tableColumns.length * 150, y: 'calc(100vh - 480px)' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column?.key === 'id'">
            <a-space :size="8" align="center">
              <a-tooltip>
                <template #title>{{ t('common.viewText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByVive(record)"
                >
                  <template #icon><InfoCircleOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情框 -->
    <ProModal
      :drag="true"
      :width="800"
      :body-style="{ height: '520px', overflowY: 'scroll' }"
      :keyboard="false"
      :mask-closable="false"
      :open="modalState.openByView"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @cancel="fnModalCancel"
    >
      <template v-slot:footer>
        <a-button @click="fnModalCancel">
          {{ t('views.faultManage.activeAlarm.closeModal') }}
        </a-button>
      </template>

      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 8 }"
        :label-wrap="true"
      >
        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.alarmId')"
              name="alarmId"
            >
              {{ modalState.from.alarmId }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.alarmSeq')"
              name="alarmSeq"
            >
              {{ modalState.from.alarmSeq }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.alarmCode')"
              name="alarmCode"
            >
              {{ modalState.from.alarmCode }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item :label="t('views.ne.common.neType')" name="neType">
              {{ modalState.from.neType }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item :label="t('views.ne.common.neId')" name="neId">
              {{ modalState.from.neId }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.alarmTitle')"
              name="alarmTitle"
            >
              {{ modalState.from.alarmTitle }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.eventTime')"
              name="eventTime"
            >
              {{ modalState.from.eventTime }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.faultManage.activeAlarm.locationInfo')"
          name="locationInfo"
          :label-col="{ span: 4 }"
        >
          {{ modalState.from.locationInfo }}
        </a-form-item>

        <a-form-item
          :label="t('views.faultManage.activeAlarm.addInfo')"
          name="addInfo"
          :label-col="{ span: 4 }"
        >
          {{ modalState.from.addInfo }}
        </a-form-item>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.specificProblemId')"
              name="specificProblemId"
            >
              {{ modalState.from.specificProblemId }}
            </a-form-item>
          </a-col>

          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.faultManage.activeAlarm.objectName')"
              name="objectName"
            >
              {{ modalState.from.objectName }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.faultManage.activeAlarm.specificProblem')"
          name="specificProblem"
          :label-col="{ span: 4 }"
        >
          {{ modalState.from.specificProblem }}
        </a-form-item>
      </a-form>
    </ProModal>
  </PageContainer>
</template>

<style lang="less" scoped>
.table :deep(.ant-pagination) {
  padding: 0 24px;
}
</style>
