<template>
  <div class="app-container">
    <div class="dark-el-input dark-el-button">
      <el-form ref="queryForm" size="small" :inline="true" popper-class="cpp-popper">
        <el-form-item label="时间">
          <el-date-picker
              :clearable="false"
              v-model="dateTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:45:00']" popper-class="cpp-popper"
              :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="场站名称">
          <el-select v-model="stationCode" placeholder="请选择" popper-class="cpp-popper">
            <el-option
                v-for="item in stationList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逆变器设备">
          <el-select v-model="equipmentId" multiple :multiple-limit="5" filterable collapse-tags
                     popper-class="cpp-popper">
            <el-option
                v-for="item in equipmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: 5px" icon="el-icon-search" @click="beforeQuery">查询
          </el-button>
          <el-button type="primary" style="margin-left: 5px" icon="el-icon-download" @click="exportFile">导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding-top: 10px">
      <vxe-table
          ref="xTable"
          align="center"
          class="mytable-style"
          auto-resize
          border
          resizable
          export-config
          highlight-current-row
          show-overflow
          :data="tableData"
          :radio-config="{trigger: 'row'}">
        <vxe-table-column field="stationCode" title="所属场站" :formatter="stationCodeFormat"></vxe-table-column>
        <vxe-table-column field="equipmentId" title="设备名称" :formatter="nameFormat"></vxe-table-column>
        <vxe-table-column field="time" title="时间" width="150" :formatter="timeFormat"></vxe-table-column>
        <vxe-table-column field="status" title="状态" :formatter="statusFormat"></vxe-table-column>
        <vxe-table-column field="activePower" title="有功(KW)"></vxe-table-column>
        <vxe-table-column field="reactivePower" title="无功(KVar)"></vxe-table-column>
        <vxe-table-column field="voltage" title="电压(V)"></vxe-table-column>
        <vxe-table-column field="electricalCurrent" title="电流(A)"></vxe-table-column>
        <vxe-table-column field="dayElectricQuantity" title="当日发电量(kW·h)"></vxe-table-column>
        <vxe-table-column field="cumulativeGeneratedEnergy" title="累积发电量(MW·h)"></vxe-table-column>
        <vxe-table-column field="dayGridConnectedHours" title="当日并网小时数"></vxe-table-column>
      </vxe-table>
      <vxe-pager
          background
          :loading="loading"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="total"
          @page-change="handlePageChange"
          :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
      </vxe-pager>
    </div>
  </div>
</template>

<script>
export default {
  name: 'inverterinfo',
  data() {
    return {
      equipmentId: [],
      equipmentOptions: [],
      dateTime: [new Date(new Date().toLocaleDateString()).getTime(), new Date(new Date().toLocaleDateString()).getTime() + 60 * 60 * 24 * 1000 - 5 * 1000 * 60],
      total: 0,
      sortOrder: 'asc',
      pageSize: 10,
      currentPage: 1,
      stationList: [],
      stationCode: [],
      searchForm: {},
      tableData: [],
      nameList: [],
      loading: false,
      modId: '',//备用id

      pickerMinDate: null,
      pickerMaxDate: null,
      day30: 30 * 24 * 3600 * 1000,
      // 日期使用
      pickerOptions: {
        onPick: ({maxDate, minDate}) => {
          if (minDate && this.pickerMinDate) {
            this.pickerMinDate = null;
          } else if (minDate) {
            this.pickerMinDate = minDate.getTime();
          }
        },
        disabledDate: (time) => {
          if (this.pickerMinDate) {
            return (time.getTime() < (this.pickerMinDate - this.day30));
          }
          return time.getTime() > new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000  - 1;
        }
      },
    }
  },
  created() {
    // 获取所有逆变器名称(列表转义应用)
    this.$axios.get('/inverterinfo/findAll').then((res) => {
      this.nameList = res.data
      if (res.data.length > 0) {
        // 默认选中前5个逆变器
        let count = 0
        for (let i = 0; i < res.data.length; i++) {
          if (count <= 4) {
            this.equipmentId.push(res.data[i].value)
            count++
          }
        }
      }
    }).catch((error) => {
      this.$message.error('获取逆变器转义名称出错' + error)
    })

  },
  mounted() {
    // 获取场站下拉列表
    this.getStationCode()
  },
  computed: {},
  methods: {
    exportFile() {
      if (this.tableData.length > 0) {
        if (this.equipmentId.length == 0) {
          this.$message.error("请选择逆变器设备查询")
          return
        }
        let startTime = Math.round(this.dateTime[0])
        let endTime = Math.round(this.dateTime[1])
        if (endTime <= startTime) {
          this.$message.error("开始时间不能大于结束时间")
          return
        }

        this.loading = true
        let queryParams = {
          "stationCode": this.stationCode,
          "equipmentId": this.equipmentId.join(','),
          "startTime": startTime,
          "endTime": endTime,
        }
        this.$axios.get('/inverterstatusdata/export', {
          params: queryParams,
          responseType: 'blob',// 用于解决中文乱码
        }).then(response => {
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.$message.error("列表无数据不能导出文件！")
        return
      }
    },
    beforeQuery() {
      this.currentPage = 1
      this.pageSize = 10
      this.dataQuery()
    },
    stationChange() {
      const param = {
        "stationCode": this.stationCode,
      }
      // 获取场站下风机设备
      this.$axios.get('/inverterinfo/findByStationCode', {params: param}).then((res) => {
        this.equipmentOptions = res.data
      }).catch((error) => {
        this.$message.error('获取逆变器设备出错' + error)
      })
    },
    timeFormat({cellValue, row, column}) {
      return this.$moment(cellValue).format('YYYY-MM-DD HH:mm')
    },
    nameFormat({cellValue, row, column}) {
      const item = this.nameList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    stationCodeFormat({cellValue, row, column}) {
      const item = this.stationList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    statusFormat({cellValue, row, column}) {
      if (cellValue == 1) {
        return '运行'
      } else if (cellValue == 2) {
        return '待机'
      } else if (cellValue == 3) {
        return '停用'
      } else if (cellValue == 4) {
        return '故障'
      }
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.dataQuery();
    },
    dataQuery() {
      if (this.equipmentId.length == 0) {
        this.$message.error("请选择逆变器设备查询")
        return
      }
      let startTime = Math.round(this.dateTime[0])
      let endTime = Math.round(this.dateTime[1])
      if (endTime <= startTime) {
        this.$message.error("开始时间不能大于结束时间")
        return
      }

      this.loading = true
      let queryParams = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        "stationCode": this.stationCode,
        "equipmentId": this.equipmentId.join(','),
        "startTime": startTime,
        "endTime": endTime,
      }

      this.$axios.get('/inverterstatusdata/getByStationCodeAndEquipmentIdAndTimeBetween', {params: queryParams}).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    async getStationCode() {
      const param = {
        "type": 'E1',
      }
      await this.$axios.get('/electricfield/findByType', {params: param}).then(response => {
        this.stationList = response.data
        if (this.stationList.length > 0) {
          this.stationCode = this.stationList[0].value
          this.stationChange()
          this.dataQuery()
        }
      })
    },
  }
}
</script>
