<template>
  <div class="show-warn-modal">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="选择查询时间">
        <el-date-picker
            v-model="formInline.dateRange"
            type="datetimerange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            popper-class="history-date-picker"
            :append-to-body="false"
            :picker-options="pickerOptions"
            :clearable="false"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="fetchData">查询</el-button>
      </el-form-item>
      <el-button style="margin-left: 20px" @click="handleDownload">导出Excel表格</el-button>
    </el-form>
    <el-table
        :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>
    <div style="float: right;margin-top: 8px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paginationOption.currentPage"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="paginationOption.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paginationOption.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {findCollectEntityWarnRecord} from '@/api/WarnRecord'
import moment from 'moment'
import {saveJsonToExcel} from "@/utils/utilsExcel";

export default {
  name: 'ShowWarnModal',
  props: {
    collectEntity: {
      type: Object,
      default: () => {
      }
    },
  },
  data() {
    return {
      formInline: {
        dateRange: [
          moment().subtract(1, 'days').valueOf(),
          moment().valueOf()
        ]
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一小时',
          onClick(picker) {
            picker.$emit('pick', [moment().subtract(1, 'hours'), moment()])
          }
        }, {
          text: '最近六小时',
          onClick(picker) {
            picker.$emit('pick', [moment().subtract(6, 'hours'), moment()])
          }
        }, {
          text: '最近24小时',
          onClick(picker) {
            picker.$emit('pick', [moment().subtract(24, 'hours'), moment()])
          }
        }]
      },
      warnType: {
        1: '上限报警',
        2: '下限报警',
      },
      warnEvent: {
        1: '报警产生',
        2: '报警结束',
        3: '报警应答',
      },
      tableData: [],
      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'
        },
      ],
      paginationOption: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    }
  },
  methods: {
    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() {
      const tagIds = this.collectEntity.tagList.map(e => e.id)
      const params = {
        tagIds: tagIds,
        start: this.formInline.dateRange[0].valueOf(),
        end: this.formInline.dateRange[1].valueOf(),
        current: this.paginationOption.currentPage,
        pageSize: this.paginationOption.pageSize,
      }
      findCollectEntityWarnRecord(params).then(res => {
        if (res && res.code === '200') {
          const tableData = []
          for (const warnRecord of res.data.records) {
            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],
            })
          }
          this.tableData = tableData
          this.paginationOption.total = Number(res.data.total)
        }
      })
    },
    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'
      }
    },
    handleSizeChange(val) {
      this.paginationOption.pageSize = val
      // console.log(`每页 ${val} 条`, this.paginationOption)
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.paginationOption.currentPage = val
      // console.log(`当前页: ${val}`, this.paginationOption)
      this.fetchData()
    },
    updateTimeRange() {
      this.formInline.dateRange = [
        moment().subtract(1, 'days').valueOf(),
        moment().valueOf()
      ]
      this.fetchData()
    }
  },
}
</script>

<style lang="less" scoped>
.show-warn-modal {
  /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;
  }

  /deep/ .el-input__inner {
    background-color: #ebebeb;
    box-shadow: inset 0.1rem 0.1rem 0.1rem #AAA7A7, inset -0.1rem -0.1rem 0.1rem #FFFFFF;
    border: none;
    font-size: 16px;
    color: #333333;
  }

  /deep/ .el-select-dropdown__item.selected {
    font-weight: normal;
    color: #FFFFFF;
    background-color: #A20D13;
    border-radius: 5px;
    box-shadow: inset 0.2rem 0.2rem 0.5rem #6E090C, inset -0.2rem -0.2rem 0.5rem #C71016;
  }

  /deep/ .history-date-picker {
    left: 10% !important;
    background-color: #EBEBEB;
    box-shadow: 0.05rem 0.05rem 0.1rem #AAA7A7, -0.05rem -0.05rem 0.1rem #FFFFFF;

    .el-picker-panel__sidebar {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 110px;
      border-right: 1px solid #e4e4e4;
      box-sizing: border-box;
      padding-top: 6px;
      background-color: transparent;
      overflow: auto;
    }

    .today {
      div {
        span {
          color: #A20D13;
          font-weight: bolder;
        }
      }
    }

    .start-date, .end-date {
      div {
        span {
          color: #A20D13;
          font-weight: bolder;
          background-color: #EBEBEB;
          box-shadow: 0.05rem 0.05rem 0.1rem #AAA7A7, -0.05rem -0.05rem 0.1rem #FFFFFF;
        }
      }
    }

    .el-picker-panel__footer {
      border-top: 1px solid #e4e4e4;
      padding: 4px;
      text-align: right;
      background-color: #ebebeb;
      position: relative;
      font-size: 0;
    }

    .el-picker-panel__shortcut {
      display: block;
      width: 90%;
      border: 0;
      border-radius: 5px;
      background-color: transparent;
      line-height: 28px;
      font-size: 14px;
      color: #606266;
      padding-left: 12px;
      text-align: left;
      outline: 0;
      cursor: pointer;
      margin: 8px 5px;
      box-shadow: 0.1rem 0.1rem 0.1rem #aaa7a7, -0.1rem -0.1rem 0.1rem #ffffff;
    }

    .el-button--text {
      color: #A20D13;
    }

    .el-button--default {
      color: #FFF;
      background-color: #A20D13;
    }

    .el-button.is-plain:focus, .el-button.is-plain:hover {
      border-color: transparent;
      color: #FFF;
    }
  }

  /deep/ .popper__arrow {
    display: none;
  }

  /deep/ .el-range-editor .el-range-input {
    line-height: 1;
    background-color: transparent;
  }

  /deep/ .el-date-editor .el-range__icon {
    color: inherit;
  }

  .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 {
    color: #FFF;
    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: #606266;
    border-color: transparent;
    /*background-color: #A20D13;*/
  }

  /deep/ .el-pagination {
    .btn-prev {
      background: inherit !important;
      background-color: #EBEBEB;
      box-shadow: 0.05rem 0.1rem 0.1rem #AAA7A7, -0.05rem -0.1rem 0.1rem #FFFFFF;
    }

    .btn-next {
      background-color: #EBEBEB;
      box-shadow: 0.05rem 0.1rem 0.1rem #AAA7A7, -0.05rem -0.1rem 0.1rem #FFFFFF;
    }

    /*
          .btn-prev:active, .btn-next:active {
            color: #FFF;
            border: none;
            background-color: #A20D13 !important;
            box-shadow: inset 0.1rem 0.1rem 0.2rem #6E090C, inset -0.1rem -0.1rem 0.2rem #c7494d;
          }*/

    button:hover {
      color: #c7494d;
    }

    .el-pager {
      li {
        padding: 0 4px;
        background: #FFF;
        font-size: 13px;
        min-width: 35.5px;
        height: 28px;
        line-height: 28px;
        box-sizing: border-box;
        text-align: center;
        background-color: #EBEBEB;
        box-shadow: 0.05rem 0.1rem 0.1rem #AAA7A7, -0.05rem -0.1rem 0.1rem #FFFFFF;
      }

      li.active, li:hover {
        color: #c7494d;
        cursor: default;
      }
    }
  }
}
</style>
