<template>
  <div class="warning">
    <!--<el-button @click="() => this.playAudio()">播放报警音乐</el-button>-->
    <navigation-name :msg="msg"/>
    <br/>
    <div>
      <el-button @click="dialogVisible = true">清空报警记录</el-button>

      <el-button style="margin-left: 20px" @click="handleDownload">导出Excel表格</el-button>
    </div>
    <br/>
    <el-table
        v-loading="tableLoading"
        :data="tableData"
        :header-cell-style="{
        background: '#BFBFBF',
        boxShadow: 'inset grey 0px -1px',
        color: '#333333',
        borderColor: '#eaeaea',
        fontSize: '20px',
      }"
        :cell-style="{
        borderColor: '#919191',
        fontSize: '20px',
        backgroundColor: '#ebebeb',
        fontWeight: '500',
        height: '48px',
      }"
        :row-class-name="tableRowClassName"
        row-key="id"
        border
        stripe
        style="width: 100%">
      <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :class-name="index === 0 ? 'warn-column' : 'warn-row'"
          align="center"
      />
    </el-table>
    <br/>
    <br/>
    <!--<div>
      <el-button style="width: 150px;font-weight: bolder;float: right">应答报警</el-button>
    </div>-->

    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="25%"
        :append-to-body="false"
        custom-class="delete-confirm"
        top="40vh"
        :show-close="false"
    >
      <div style="line-height: 25px;display: flex">
        <div>
          <i class="el-icon-info" style="color:#ea050f;font-size: 25px"/>
        </div>
        <div style="margin-left: 8px;font-size: 16px">此操作将永久删除, 是否继续?</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" @click="handleClearAll" style="color: #FFF;background-color: #A20D13">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {v4 as uuidv4} from 'uuid'
import NavigationName from '@/components/NavigationName'
import moment from 'moment'
import {mapState, mapMutations, mapActions} from 'vuex'
import {clearWarnRecord} from '@/api/WarnRecord'
import {saveJsonToExcel} from "@/utils/utilsExcel";

export default {
  name: 'Warning',
  components: {NavigationName},
  data() {
    return {
      msg: '报警显示',
      warnType: {
        1: '上限报警',
        2: '下限报警',
      },
      warnEvent: {
        1: '报警产生',
        2: '报警结束',
        3: '报警应答',
      },
      tableColumns: [
        {
          label: '时间',
          prop: 'warnTime',
          width: '240',
        },
        {
          label: '对象名',
          prop: 'desc',
          width: '400',
        },
        {
          label: '报警类型',
          prop: 'warnTypeText',
          slotScope: true,
        },
        /*{
          label: '报警事件',
          prop: 'warnEventText',
          slotScope: true,
        },*/
        {
          label: '当前值',
          prop: 'currentValue'
        },
        {
          label: '界限值',
          prop: 'limitValue'
        },
      ],
      tableLoading: false,
      dialogVisible: false,
    }
  },
  computed: {
    ...mapState({
      warnRecordData: state => state.queue.warnRecordData,
    }),
    tableData() {
      const tableData = []
      if (this.warnRecordData.length > 0) {
        for (const warnRecord of this.warnRecordData) {
          tableData.push({
            ...warnRecord,
            warnTime: moment(Number(warnRecord.warnTime)).format('YYYY-MM-DD HH:mm:ss'),
            warnTypeText: this.warnType[warnRecord.warnType],
            warnEventText: this.warnEvent[warnRecord.warnEvent],
          })
        }
        return this.handleTableData(tableData)
      } else {
        return tableData
      }
    },
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    ...mapMutations(['CLEAR_WARN_DATA']),
    ...mapActions(['initWarnRecordData']),
    handleDownload() {

      // 要保留的字段
      const includeFields = ['warnTime', 'desc', 'warnTypeText', 'currentValue','limitValue'];

      // 过滤掉不需要的字段，保留需要的字段
      const filteredData = this.tableData.map(item => {
        // 只保留includeFields中的字段
        let filteredItem = {};
        includeFields.forEach(key => {
          if (item.hasOwnProperty(key)) {
            filteredItem[key] = item[key]; // 保留指定字段
          }
        });
        return filteredItem;
      });
      // 自定义字段顺序
      const customOrder = ['warnTime', 'desc', 'warnTypeText', 'currentValue','limitValue'];

      // 对filteredData中的字段进行排序
      const sortedData = filteredData.map(item => {
        let sortedItem = {};
        customOrder.forEach(key => {
          if (item.hasOwnProperty(key)) {
            sortedItem[key] = item[key]; // 按顺序添加字段
          }
        });
        return sortedItem;
      });

      const customHeaders = ["时间","对象名","报警类型","当前值","界限值"];
      // 获取当前时间（UTC时间）
      const now = new Date();

      // 将时间调整为北京时间（UTC + 8小时）
      const timestamp = new Date(now.getTime() + 8 * 60 * 60 * 1000)
          .toISOString()
          .replace(/[-T:.]/g, ''); // 格式化为不含特殊符号的时间戳

      // 拼接文件名
      const filename = `报警记录_${timestamp}.xlsx`;
      saveJsonToExcel(sortedData, filename, customHeaders)
    },
    fetchData() {
      this.initWarnRecordData()
    },
    handleClearAll() {
      clearWarnRecord().then(res => {
        if (res && res.code === '200') {
          this.CLEAR_WARN_DATA()
          this.dialogVisible = false
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
      }).catch(reason => {
        this.$message.error(reason.message)
      })
    },
    handleTableData(tableData) {
      let data
      const len = tableData.length
      if (len < 10) {
        data = [...tableData]
        for (let i = 0; i < (10 - len); i++) {
          data.push({
            id: uuidv4(),
          })
        }
      } else if (len > 10) {
        data = tableData.slice(0, 10)
      } else {
        data = tableData
      }
      return data
    },
    tableRowClassName({row, rowIndex}) {
      const warnEvent = this.tableData[rowIndex].warnEvent
      if (warnEvent === 1) {
        return 'warning-produce'
      } else if (warnEvent === 2) {
        return 'warning-end'
      } else {
        return 'warning-answer'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.warning {
  padding: 0 40px;
  font-size: 16px;
  display: flex;
  flex-direction: column;

  /deep/ .delete-confirm {
    background-color: #ebebeb;
    border-radius: 5px;

    .el-dialog__header {
      padding: 8px 8px 10px;

      .el-dialog__title {
        line-height: 18px;
        font-size: 18px;
        font-weight: bolder;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 20px;
    }

    .el-dialog__footer {
      padding: 8px 16px 16px;
    }
  }

  /deep/ .el-table {
    box-shadow: 0.05rem 0.05rem 0.1rem #AAA7A7, 0.05rem 0.05rem 0.1rem #FFFFFF;

    .cell {
      white-space: pre-line;
    }
  }

  /deep/ .el-table--border, .el-table--group {
    border-radius: 10px;
  }

  /deep/ .el-table__row {
    .warn-column {
      background-color: #d9d9d9 !important;
      box-shadow: inset #BFBFBF -1px -1px !important;
    }

    .warn-row {
    }
  }
}

/deep/ .el-table .warning-produce {
  color: #45c4ff;
}

/deep/ .el-table .warning-end {
  color: #d2262e;
}

/deep/ .el-table .warning-answer {
  color: #24d393;
}

.el-button {
  border: none;
  background-color: #EBEBEB;
  box-shadow: 0.05rem 0.1rem 0.1rem #AAA7A7, -0.05rem -0.1rem 0.1rem #FFFFFF;
}

.el-button:active {
  border: none;
  background-color: #A20D13;
  box-shadow: inset 0.1rem 0.1rem 0.2rem #6E090C, inset -0.1rem -0.1rem 0.2rem #c7494d;
}

.el-button:focus, .el-button:hover {
  color: #FFF;
  border-color: transparent;
  background-color: #A20D13;
}
</style>
