<script setup lang="ts">

import {ref} from "vue";
import type {IEquipmentErrorSearch} from "@/interface/page/recordEquipmentSearch/IEquipmentErrorSearch.ts";
import ErrorBaseEquipmentTypeFormatter from "@/plugin/formatter/ErrorBaseEquipmentTypeFormatter.ts";
import ErrorLevelFormatter from "@/plugin/formatter/ErrorLevelFormatter.ts";
import ErrorTypeFormatter from "@/plugin/formatter/ErrorTypeFormatter.ts";
import type {IEquipmentErrorVo} from "@/model/table/IEquipmentErrorVo.ts";
import MessageUtils from "@/utils/MessageUtils.ts";
import RecordErrorApi from "@/api/recordError.ts";
import type {PageDataResponse} from "@/interface/api/PageDataResponse.ts";
import type {AppServeDataResponse} from "@/interface/api/AppServeDataResponse.ts";
import {AppServeResponseCodeEnum} from "@/constant/enums/AppServeResponseCodeEnum.ts";
import {FormatterUtils} from "@/utils/FormatterUtils.ts";
import EquipmentErrorDetail from "@/components/page/recordEquipmentError/EquipmentErrorDetail.vue";
import type {IAppBaseErrorInfo} from "@/model/table/IAppBaseErrorInfo.ts";

const queryParams = ref<IEquipmentErrorSearch>({});
const errorBaseEquipmentTypeFormatter = new ErrorBaseEquipmentTypeFormatter(); // 设备报警基础资料设备型号格式化
const errorLevelFormatter = new ErrorLevelFormatter(); // 设备报警基础资料报警级别格式化
const errorTypeFormatter = new ErrorTypeFormatter(); // 设备报警基础资料报警类型格式化
const pageSize = ref<number>(100); // 分页单页数据
const pageIndex = ref<number>(1); // 分页页码
const totalPages = ref<number | undefined>(0); // 总数据数
const tableData = ref<IEquipmentErrorVo[]>([]);
const showDetail = ref<boolean>(false); // 是否展示详情框
const detailData = ref<IAppBaseErrorInfo>();

// 查询
const query = () => {
  const loadingInstance = MessageUtils.loading();
  RecordErrorApi.queryEquipmentError(queryParams.value, pageSize.value, pageIndex.value).then(res => {
    const responseStr = JSON.parse(JSON.stringify(res.data));
    const response = responseStr as AppServeDataResponse<PageDataResponse<IEquipmentErrorVo>>;
    if (response.code == AppServeResponseCodeEnum.SUCCESS && response.data != undefined) {
      tableData.value = response.data.data ?? [];
      totalPages.value = response.data.totalCount;
      MessageUtils.successMessage("查询成功");
      return;
    }
    MessageUtils.errMessage(response.msg);
  }).catch(() => {}).finally(() => {
    loadingInstance.close();
  });
};
// 重置查询参数
const resetInput = () => {
  queryParams.value = {};
};
// 分页
const paginationChange = () => {
  query();
};
// 编辑
const handleEdit = (index: number, row: any) => {
  detailData.value = {
    equipmentType: row.equipmentType,
    errCode: row.errCode,
  };
  showDetail.value = true;
};
// 导出数据
const exportData = () => {
  const loadingInstance = MessageUtils.loading("请稍后");
  RecordErrorApi.exportEquipmentError(queryParams.value).then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '设备故障数据下载.xlsx');
    document.body.appendChild(link);
    MessageUtils.successMessage('您的下载将尽快开始，请稍后');
    link.click();
    document.body.removeChild(link);
  }).catch(err => {
    MessageUtils.errMessageBox('请求服务器失败：' + err, '错误');
  }).finally(() => {
    loadingInstance.close();
  });
}
</script>

<template>
  <div style="margin-left: 10px;margin-top: 10px; width: calc(100vw - 280px);">
    <h3>设备报警历史记录</h3>
    <el-row class="searchCard">
      <el-row style="width: 100%;">
        <el-form class="searchForm" v-model="queryParams" label-position="top" label-width="150px" inline>
          <el-form-item label="设备型号：" style="width: 250px;">
            <el-select v-model="queryParams.equipmentType"  placeholder="请选择设备型号" clearable>
              <el-option v-for="item in errorBaseEquipmentTypeFormatter.equipmentType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备号：" style="width: 250px;">
            <el-input v-model="queryParams.equipmentId"  placeholder="请输入报警编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="报警编号：" style="width: 250px;">
            <el-input v-model="queryParams.errorCode"  placeholder="请输入报警编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="报警时间：" style="width: 250px;">
            <el-date-picker
                v-model="queryParams.createTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
            />
          </el-form-item>
        </el-form>
      </el-row>
      <el-row style="width: 100%">
        <el-button-group style="width: 100%;margin-left: 10px; margin-bottom: 10px">
          <el-button type="primary" @click="query">查询/刷新</el-button>
          <el-button type="warning" @click="resetInput">重置查询参数</el-button>
          <el-button type="info" @click="exportData">导出数据</el-button>
        </el-button-group>
      </el-row>
    </el-row>
    <el-row class="dataTable">
      <el-table :data="tableData" stripe border style="width: 100%" max-height="calc(100vh - 320px)">
        <el-table-column type="index" width="80" label="序号" align="center" show-overflow-tooltip fixed="left"/>
        <el-table-column prop="id" label="ID号" width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="equipmentType" label="设备类型" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="errorBaseEquipmentTypeFormatter.errorBaseEquipmentTypeFormatter(scope.row.equipmentType).type">
              {{errorBaseEquipmentTypeFormatter.errorBaseEquipmentTypeFormatter(scope.row.equipmentType).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" width="150" align="center" show-overflow-tooltip/>
        <el-table-column prop="equipmentId" label="设备ID" width="100" align="center" show-overflow-tooltip/>
        <el-table-column prop="errCode" label="报警代码" width="100" align="center" show-overflow-tooltip/>
        <el-table-column prop="errLevel" label="报警级别" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="errorLevelFormatter.errorLevelTagStyleFormatter(scope.row.errLevel).type" effect="dark">
              {{errorLevelFormatter.errorLevelTagStyleFormatter(scope.row.errLevel).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="errType" label="报警类型" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="errorTypeFormatter.errorTypeTagStyleFormatter(scope.row.errType).type">
              {{errorTypeFormatter.errorTypeTagStyleFormatter(scope.row.errType).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="errMsg" label="报警信息" min-width="150" align="center" show-overflow-tooltip/>
        <el-table-column prop="createTime" label="报警时间" width="180" align="center" :formatter="FormatterUtils.formatCellValueTime" show-overflow-tooltip/>
        <el-table-column prop="recoverTime" label="恢复时间" width="180" align="center" :formatter="FormatterUtils.formatCellValueTime" show-overflow-tooltip/>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin: 10px"
                     background
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 100, 200, 300]"
                     size="small"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalPages"
                     @size-change="paginationChange"
                     @current-change="paginationChange"
      />
    </el-row>
  </div>
<!--  报警资料详情-->
  <EquipmentErrorDetail v-model="showDetail" :form-data="detailData"/>
</template>

<style scoped>

</style>