<template>
  <div class="data-report-modal">
    <div>
      <el-form :inline="true" :model="formInline">
        <el-form-item label="查询步长">
          <el-select
            style="width: 100%;"
            v-model="formInline.step"
            placeholder="查询步长"
            popper-class="jg-select"
            :popper-append-to-body="false"
            @change="onStepChange"
          >
            <el-option :label="item.name" :value="item.value" v-for="(item, index) in stepList" :key="index"/>
          </el-select>
        </el-form-item>
        <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-button style="margin-left: 20px" @click="handleDownload">导出Excel表格</el-button>
        </el-form-item>
      </el-form>

    </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="{
        background: '#f6f5f5',
        color: '#333333',
        borderColor: '#eaeaea',
        fontSize: '18px',
      }"
      row-key="dateTime"
      border
      stripe
      style="width: 100%">
      <el-table-column
        type="index"
        width="100"
        label="序号"
        align="center"
      />
      <el-table-column
        prop="dateTime"
        label="时间"
        align="center"
        width="200"
      />

      <el-table-column
        v-for="(item, index) in tableColumns"
        :key="index"
        :column-key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :class-name="item.className"
        :align="item.align ? item.align : 'center'"
      ></el-table-column>
    </el-table>

    <div style="display: flex;justify-content: flex-end;margin-top: 8px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationOption.currentPage"
        :page-sizes="[10, 30, 50, 100,500,1000]"
        :page-size="paginationOption.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationOption.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { findSaveData } from '@/api/HistoryData'
import { findTableColumnsNotStatus } from '@/api/TableConfig'
import moment from 'moment'
import {saveJsonToExcel} from "@/utils/utilsExcel";

export default {
  name: 'DataReportModal',
  props: {
    collectEntity: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      tableLoading: true,
      stepList: [
        { name: '2s', value: 2 },
        { name: '1min', value: 60 },
        { name: '30min', value: 1800 },
        { name: '1h', value: 3600 },
      ],
      formInline: {
        dateRange: [
          moment().subtract(1, 'days').valueOf(),
          moment().valueOf()
        ],
        step: 60
      },
      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()])
          }
        }]
      },
      tableData: [],
      tableList: [],
      paginationOption: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      tableColumns: [],
    }
  },
  methods: {
    async fetchData() {
      // this.tableList.length = 0
      this.tableLoading = true

      await findTableColumnsNotStatus().then(res => {
        if (res && res.code === '200') {
          const columns = res.data.filter(e => e.prop !== 'second')
          const tableColumns = []
          for (const item of columns) {
            tableColumns.push({
              label: item.label,
              prop: item.prop && item.prop.toLowerCase(),
              width: item.width,
              className: item.className,
              align: item.align,
            })
          }

          // this.tableColumns = tableColumns
          this.tableColumns = tableColumns.filter(column => column.label !== '操作间');
          console.log('aaaaaaaaaaaa', tableColumns)
        }
      })

      const collectEntityId = this.collectEntity.id
      const params = {
        collectEntityId,
        start: this.formInline.dateRange[0].valueOf(),
        end: this.formInline.dateRange[1].valueOf(),
        // 单位s
        step: this.formInline.step,
        current: this.paginationOption.currentPage,
        pageSize: this.paginationOption.pageSize
      }
      // console.log('==>', this.collectEntity)
      await findSaveData(params).then(res => {
        if (res && res.code === '200') {
          this.tableData = res.data.records
          this.paginationOption.total = res.data.total
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    handleDownload() {
      // 要保留的字段
      const includeFields = ['dateTime', 'electric', 'vibration', 'noise'];
      // 过滤掉不需要的字段，保留需要的字段
      const filteredData = this.tableData.map(item => {
        // 只保留includeFields中的字段
        let filteredItem = {};
        includeFields.forEach(key => {
          if (item.hasOwnProperty(key)) {
            filteredItem[key] = item[key]; // 保留指定字段
          }
        });
        return filteredItem;
      });

      // 自定义字段顺序
      const customOrder = ['dateTime', 'electric', 'vibration', 'noise'];

      // 对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并传入自定义表头
      saveJsonToExcel(sortedData, filename, customHeaders);
    },

    handleSizeChange(val) {
      this.paginationOption.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.paginationOption.currentPage = val
      this.fetchData()
    },
    updateTimeRange() {
      this.formInline.dateRange = [
        moment().subtract(1, 'days').valueOf(),
        moment().valueOf()
      ]
      this.fetchData()
    },
    onStepChange(e) {
      this.paginationOption.pageSize = 10
      this.paginationOption.currentPage = 1
      this.fetchData()
    },
  },
}
</script>

<style lang="less" scoped>
  .data-report-modal {
    height: 100%;
    display: flex;
    flex-direction: column;

    /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;
    }

    .el-table, .el-table__expanded-cell {
      background-color: transparent;
    }

    .el-button {
      color: #333333;
      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: #ffffff !important;
      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: inherit;
      border-color: transparent;
    }

    /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;
    }

    /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;
          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;
        }
      }
    }

    /deep/ .jg-select {
      padding: 10px;
      background-color: #ebebeb;
      box-shadow: 0.1rem 0.1rem 0.1rem #AAA7A7, -0.1rem -0.1rem 0.1rem #FFFFFF;

      .el-select-dropdown__item {
        box-shadow: 0.1rem 0.1rem 0.1rem #AAA7A7, -0.1rem -0.1rem 0.1rem #FFFFFF;
        margin: 8px 3px;
        border-radius: 5px;
      }
    }

    /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/ .popper__arrow {
      display: none;
    }
  }
</style>
