<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">


  <div class="app-container">

    <div>
      <el-card>
        <div slot="header" class="clearfix">
          <b><span>逆变器信息</span></b>
          <el-button :loading="loadButton" style="float: right;padding:3px 10px 3px 3px;" type="text"
                     @click="exportDataEvent">导出数据
          </el-button>
        </div>
        <span style="font-weight: bold;font-size: 14px">场站名称：</span>
        <el-select v-model="stationCode" clearable size="small" style="width:250px">
          <el-option
            v-for="item in stationList"
            :key="item.stationCode"
            :label="item.name"
            :value="item.stationCode">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6;font-size: 13px">{{ item.stationCode }}</span>
          </el-option>
        </el-select>
        <el-button icon="el-icon-search" size="small" type="primary" @click="getData">查询</el-button>
        <el-button :loading="loadButton" size="small" style="round-clip: 10px" type="primary" @click="insertEvent">添加
        </el-button>
        <el-button
          :loading="loadButton"
          size="small"
          style="round-clip: 10px"
          type="primary"
          @click="piInsertEvent">
          批量添加
        </el-button>
        <el-button
          :loading="loadButton"
          size="small"
          style="round-clip: 10px"
          type="danger"
          @click="getSelectionEvent">
          批量删除
        </el-button>
        <div style="padding-top: 10px">
          <vxe-table
            v-show="showTable"
            ref="xTable"
            :data="tableData"
            :edit-config="{trigger: 'manual', mode: 'row',autoClear:false,showStatus: true,icon:'none'}"
            :edit-rules="rules"
            :loading="loading"
            auto-resize
            border
            export-config
            highlight-current-row
            keep-source
            resizable>
            <vxe-table-column align="center" title="逆变器信息">
              <vxe-table-column type="checkbox" width="3%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$input', attrs: {type: 'text'}}" field="stationCode" title="场站编号"
                                width="6%"></vxe-table-column>
              <vxe-table-column :edit-render="{name:'$input',attrs:{type:'text'}}" field="equipmentNo" title="设备编号"
                                width="10%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$input', attrs: {type: 'text'}}" align="center" field="name" title="名称"
                                width="8%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$input', attrs: {type: 'text'}}" align="center" field="modelNumber" title="型号"
                                width="8%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$select', options: trueOrFalse}" align="center" field="report" title="是否上报"
                                width="8%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$input', attrs: {type: 'text'}}" align="center" field="capacity" title="额定功率"
                                width="8%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$input', attrs: {type: 'text'}}" align="center" field="efficiency" title="效率"
                                width="8%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$input', props: {type: 'text'}}" align="center" field="collectorCircuit" title="集电线路"
                                width="8%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$select', options: trueOrFalse}" align="center" field="groupSeries" title="是否组串"
                                width="6%"></vxe-table-column>
              <vxe-table-column :edit-render="{name: '$select', options: trueOrFalse}" align="center" field="sample" title="是否样板"
                                width="6%"></vxe-table-column>
              <vxe-table-column align="center" fixed="right" title="操作" width="10%">
                <template v-slot="{ row }">
                  <template v-if="$refs.xTable.isActiveByRow(row)">
                    <el-button
                      icon="el-icon-edit"
                      size="medium"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      type="success"
                      @click="editSave(row)">保存
                    </el-button>
                    <el-button
                      class="cancel-btn"
                      icon="el-icon-refresh"
                      size="medium"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      type="warning"
                      @click="cancelRowEvent(row)">取消
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button
                      :loading="loadButton"
                      icon="el-icon-edit"
                      size="medium "
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      type="primary"
                      @click="editRowEvent(row)">编辑
                    </el-button>
                    <el-button
                      :loading="loadButton"
                      icon="el-icon-delete"
                      size="medium "
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      type="danger"
                      @click="deleteRowEvent(row)">删除
                    </el-button>
                  </template>
                </template>
              </vxe-table-column>

            </vxe-table-column>
          </vxe-table>
          <vxe-pager
            v-show="!loadButton&&showTable"
            :current-page.sync="currentPage"
            :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
            :page-size.sync="pageSize"
            :page-sizes=[10,50,100]
            :total="total"
            perfect
            @page-change="handlePageChange"
          >
          </vxe-pager>
        </div>
      </el-card>
    </div>
    <!-- 删除提示框 -->
    <el-dialog :visible.sync="delVisible" center title="提示" width="300px">
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="deleteCancel()">取 消</el-button>
                <el-button type="primary" @click="deleteInfo()">确 定</el-button>
                </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    const checkName = (rule, value, callback) => {
      var s6 = this.tableData
      if (value == null || value === '') {
        callback(new Error('请填写逆变器名称'))
      }
      for (let i = 0; i < s6.length; i++) {
        if (this.id == '' || this.id == undefined) {
          // 新增
          if ((value == s6[i].name)) {
            callback(new Error('名称不能重复'))
          }
        } else {
          // 修改
          if (this.id != s6[i].id) {
            if ((value == s6[i].name)) {
              callback(new Error('名称不能重复'))
            }
          }
        }
      }
      callback()
    }
    return {
      stationCode: '',
      stationList: [],
      id: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isSample: '',
      piadd: '',
      loadButton: false,
      loading: false,
      rowId: "",
      options: [{value: true, label: '样板机'},
        {value: null, label: '所有'}],
      option: "",
      tableData: [],
      showTable: true,
      batchAddData: [],
      delVisible: false,
      //是否为编辑
      isEdit: false,
      pvInfo: [],
      pvInfoMode: [],
      pvRotationMode: [],
      trueOrFalse: [{label: '是', value: true},
        {label: '否', value: false}],
      intervals: [{key: 0, value: 0, label: '不入库'}, {key: 60, value: 60, label: '一分钟'}, {
        key: 900,
        value: 900,
        label: '十五分钟'
      }],
      // 表单验证规则
      rules: {
        name: [
          {required: true, validator: checkName}
        ],
        modelNumber: [
          {required: true, message: '逆变器型号不能为空', trigger: 'blur'}
        ],
        capacity: [
          {required: true, message: '额定容量不能为空', trigger: 'blur'},
          {pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入正数数字或带小数点2位以内的数字'},
        ],
        efficiency: [
          {required: true, message: '逆变器效率不能为空', trigger: 'blur'},
          {pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入正数数字或带小数点2位以内的数字'},
        ],
        collectorCircuit: [
          {required: true, message: '集电线不能为空', trigger: 'blur'},
        ],
        groupSeries: [
          {required: true, message: '是否组串式逆变器不能为空', trigger: 'change'}
        ],
        sample: [
          {required: true, message: '是否样板机不能为空', trigger: 'change'}
        ],
        report: [
          {required: true, message: '是否上报不能为空', trigger: 'change'}
        ]
      }
    }
  },

  created() {
    this.getStationList()
    this.getData()
  },
  activated() {
    console.log("2激活activated钩子函数");
  },
  deactivated() {
    console.log("2激活deactivated钩子函数");
  },
  methods: {
    getStationList() {
      this.$axios.get('/electricField/getElectricField').then((res) => {
        this.stationList = res.data
      }).catch((error) => {
        this.$message.error('获取场站下拉框出错' + error)
      })
    },
    getData() {
      this.loading = true
      let queryParam = this.stationCode;
      if (queryParam == '') {
        queryParam = "ALL"
      }
      let url = this.currentPage + '/' + this.pageSize + '/' + queryParam
      this.$axios.get('/inverterInfo/' + url).then(res => {
        this.tableData = res.data.content
        this.total = res.data.totalElements
        this.loading = false
        // console.log(res.data)
        this.getPvData()
      }).catch((error) => {
        this.$message.error('获取逆变器信息出错' + error)
      })
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getData()
    },
    getPvData() {
      this.$axios.get('/pvModuleModel/').then(res => {
        this.pvInfo = res.data
        this.pvInfoMode = []
        for (let i = 0; i < this.pvInfo.length; i++) {
          const pInfo = {label: this.pvInfo[i].model, value: this.pvInfo[i].id}
          this.pvInfoMode.push(pInfo)
        }
        console.log("获取所有光伏组件信息成功")
      }).catch((error) => {
        this.$message.error('获取逆变器信息出错' + error)
      })
    },
    timestampToTime(time) {
      const date = new Date(time) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
      return Y + M + D
    },
    getSelectionEvent() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      if (selectRecords == "") {
        this.$message.error('请选择要删除的对象')
        return
      }
      this.rowId = ''
      for (let i = 0; i < selectRecords.length; i++)
        this.rowId += (selectRecords[i].id + ",")
      // console.log(this.rowId)
      this.delVisible = true
    },
    piInsertEvent(row) {
      this.piadd = true;
      this.showTable = true
      this.isEdit = false;
      this.loadButton = true;
      this.$refs.xTable.insert({interval: 60}).then(({row}) => this.$refs.xTable.setActiveRow(row))
    },
    insertEvent(row) {
      this.id = ''
      this.showTable = true
      this.piadd = false;
      this.isEdit = false;
      this.loadButton = true;
      this.$refs.xTable.insert({interval: 60}).then(({row}) => this.$refs.xTable.setActiveRow(row))
    },
    async insertBatchEvent(row) {
      /*const { row: newRow } = await this.$refs.bTable.insert()*/
      // alert(1111)
      // 插入一条数据并触发校验
      let {row: newRow} = await this.$refs.bTable.insertAt(row)
      await this.$refs.bTable.setActiveRow(newRow)
      // alert(2222)
      /*          const errMap = await this.$refs.bTable.validate(newRow).catch(errMap => errMap)
                if (errMap) {

                }*/
    },
    async fullValidEvent() {
      const errMap = await this.$refs.bTable.fullValidate().catch(errMap => errMap)
      if (errMap) {
        let msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            let {rowIndex, column, rules} = params
            rules.forEach(rule => {
              msgList.push(`第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}`)
            })
          })
        })
        this.$XModal.message({
          status: 'error',
          message: () => {
            return [
              < div
                class
                  ="red"
                style="max-height: 400px;overflow: auto;">
                {
                  msgList.map(msg => < div> {msg} < /div>)
                }
              < /div>
            ]
          }
        })
      } else {
        this.$XModal.message({status: 'success', message: '校验成功！'})
      }
    },
    saveBatchEvent() {
      const {insertRecords, removeRecords, updateRecords} = this.$refs.bTable.getRecordset()
      this.$XModal.alert(`insertRecords=${insertRecords.length} removeRecords=${removeRecords.length} updateRecords=${updateRecords.length}`)
    },
    editRowEvent(row) {
      this.id = row.id
      for (let i = 0; i < this.pvInfoMode.length; i++) {
        if (row.batteryModel == this.pvInfoMode[i].value) {
          row.batteryModel = this.pvInfoMode[i].value
        }
      }
      this.isEdit = true
      this.loadButton = true
      this.$refs.xTable.setActiveRow(row)
    },
    //设计有判断是否批量添加，批量添加弹窗表明添加条数，然后批量生成保存
    editSave(row) {
      this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(), valid => {

        if (valid) {
          if (this.piadd) {
            const inviter = row
            this.$prompt('请输入开始编号（例：1-0，其中0为开始值）', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'number',
            }).then(({value}) => {
              const startValue = value
              if (startValue >= 0 && startValue != null) {
                this.$prompt('请输入添加数目', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  inputType: 'number',
                }).then(({value}) => {
                  const endValue = value
                  if (endValue >= 0) {
                    this.$axios.post('/inverterInfo/saveAll/' + startValue + '/' + endValue, row).then(res => {
                      this.$message({
                        message: '保存成功',
                        type: 'success'
                      })
                      this.loadButton = false
                      this.piadd = false
                      this.getData()
                    }).catch((error) => {
                      this.$refs.xTable.setActiveRow(row)
                      this.$message.error('保存逆变器出错' + error)
                    })
                  } else {
                    alert("数量必须是正整数")
                  }
                })
              } else {
                alert("开始值必须是正整数并且不能为空")
              }
            })
          } else {
            this.$refs.xTable.clearActived().then(() => {
              if (this.isEdit) {
                row.equipmentType = row.equipmentType.code
                //编辑保存
                this.$axios.put('/inverterInfo/', row).then(res => {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this.loadButton = false;
                  this.getData()
                }).catch((error) => {
                  this.$refs.xTable.setActiveRow(row)
                  this.$message.error('修改逆变器出错' + error)
                })
              } else {
                //新增保存
                this.$axios.post('/inverterInfo/', row).then(res => {
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  this.loadButton = false;
                  this.getData()
                }).catch((error) => {
                  this.$refs.xTable.setActiveRow(row)
                  this.$message.error('保存逆变器出错' + error)
                })
              }
            })
          }
        } else {
          this.$XModal.message({status: 'error', message: '校验不通过！'})
        }
      })
    },
    cancelRowEvent(row) {
      const xTable = this.$refs.xTable
      xTable.clearActived().then(() => {
        // 还原行数据
        if (this.isEdit) {
          //编辑
          xTable.revertData(row)
        } else {
          //新增
          xTable.remove(row)
        }
        this.loadButton = false;
      })
    },
    // 删除场站信息
    deleteRowEvent(row) {
      this.rowId = row.id
      this.delVisible = true
    },
    deleteCancel() {
      this.delVisible = false
    },
    deleteInfo() {
      this.$axios.delete('/inverterInfo/' + '' + this.rowId).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.delVisible = false
        this.getData()
      }).catch((error) => {
        this.$message.error('删除逆变器信息出错' + error)
      })
    },
    exportDataEvent() {
      // this.loading = true
      this.$axios.get('/inverterInfo/').then(res => {
        const data = res.data.content
        this.$refs.xTable.exportData({
          filename: '逆变器信息',
          type: 'csv',
          isHeader: true,
          isFooter: true,
          data
        })
        // this.loading = false
      }).catch(e => {
        // this.loading = false
      })
    },
    /*dataUpload(item) {

    },*/
    importDataEvent(item) {
      this.loadButton = true
      const formData = new FormData()
      formData.append('file', item.file)
      // console.log('上传文件', item.file)
      this.$axios.post('/console/importPvModuleModelCsv/', formData).then(res => {
        this.$message({
          message: '导入光伏组件信息成功',
          type: 'success'
        })
      }).catch((error) => {
        this.$message({
          message: '导入光伏组件信息成功',
          type: 'success'
        })
      })
      this.loadButton = false
      /*  this.$refs.xTable.importData({ types: ['csv'] })*/
    },


  }
}
</script>

<style scoped>

.my_table_insert .vxe-body--row.is--new {
  background-color: #f1fdf1;
}
</style>
