<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>
        <el-button type="primary" @click="insertEvent" size="small" style="round-clip: 10px" :loading="loadButton">添加</el-button>
        <el-button
          size="small"
          :loading="loadButton"
          type="primary"
          style="round-clip: 10px"
          @click="piInsertEvent">
          批量添加
        </el-button>
        <el-button
          size="small"
          :loading="loadButton"
          type="danger"
          style="round-clip: 10px"
          @click="getSelectionEvent">
          批量删除
        </el-button>
        <div style="padding-top: 10px">
          <vxe-table
            ref="xTable"
            border
            export-config
            keep-source
            auto-resize
            resizable
            highlight-current-row
            :loading="loading"
            :edit-rules="rules"
            :data="tableData"
            v-show="showTable"
            :edit-config="{trigger: 'manual', mode: 'row',autoClear:false,showStatus: true,icon:'none'}">
            <vxe-table-column title="逆变器信息" align="center">
              <vxe-table-column type="checkbox" width="3%"></vxe-table-column>
              <vxe-table-column field="name" title="名称" width="8%" align="center"
                                :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="modelNumber" title="型号" width="8%" align="center"
                                :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="manufacturer" title="生产商" width="8%" align="center"
                                :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column width="150px" field="installationTime" title="安装时间" align="center"
                                :edit-render="{props: {type: 'default'}}">
                <template v-slot:edit="{ row }">
                  <el-date-picker
                    size="mini"
                    v-model="row.installationTime"
                    style="width: 100%"
                    type="date"
                    placeholder="选择日期："
                  />
                </template>
                <template v-slot="{ row }">{{ timestampToTime(row.installationTime) }}</template>
              </vxe-table-column>
              <vxe-table-column field="report" title="是否上报" width="8%" align="center"
                                :edit-render="{name: '$select', options: trueOrFalse}"></vxe-table-column>
              <vxe-table-column field="capacity" title="额定功率" width="8%" align="center"
                                :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="efficiency" title="效率" width="8%" align="center"
                                :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="box" title="箱式变压器" width="8%" align="center"
                                :edit-render="{name: '$input', props: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="collectorCircuit" title="集电线路" width="8%" align="center"
                                :edit-render="{name: '$input', props: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="batteryModel" title="光组型号" width="8%" align="center"
                                :edit-render="{name: '$select', options: pvInfoMode}"></vxe-table-column>
              <vxe-table-column field="batteryNumber" title="光组个数" width="8%" align="center"
                                :edit-render="{name: '$input', props: {type: 'number'}}"></vxe-table-column>
              <vxe-table-column field="groupSeries" title="是否组串" width="6%" align="center"
                                :edit-render="{name: '$select', options: trueOrFalse}"></vxe-table-column>
              <vxe-table-column field="sample" title="是否样板" width="6%" align="center"
                                :edit-render="{name: '$select', options: trueOrFalse}"></vxe-table-column>
              <vxe-table-column field="backupA" width="10%" title="样板机编号"
                :edit-render="{name: '$input',attrs:{type:'text'}}"/>
              <vxe-table-column field="backupB" title="经度" width="8%" align="center"
                                :edit-render="{name: '$input', props: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="backupC" title="纬度" width="8%" align="center"
                                :edit-render="{name: '$input', props: {type: 'text'}}"></vxe-table-column>
              <vxe-table-column field="interval" title="入库间隔（单位s）" width="8%" align="center"
                                :edit-render="{name: '$select', options: intervals}"></vxe-table-column>
              <vxe-table-column title="操作" fixed="right" width="10%" align="center">
                <template v-slot="{ row }">
                  <template v-if="$refs.xTable.isActiveByRow(row)">
                    <el-button
                      type="success"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium"
                      icon="el-icon-edit"
                      @click="editSave(row)">保存
                    </el-button>
                    <el-button
                      class="cancel-btn"
                      icon="el-icon-refresh"
                      type="warning"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium"
                      @click="cancelRowEvent(row)">取消
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button
                      :loading="loadButton"
                      type="primary"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium "
                      icon="el-icon-edit"
                      @click="editRowEvent(row)">编辑
                    </el-button>
                    <el-button
                      :loading="loadButton"
                      type="danger"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium "
                      icon="el-icon-delete"
                      @click="deleteRowEvent(row)">删除
                    </el-button>
                  </template>
                </template>
              </vxe-table-column>

            </vxe-table-column>
          </vxe-table>
          <vxe-pager
            perfect
            :current-page.sync="currentPage"
            :page-size.sync="pageSize"
            :total="total"
            :page-sizes=[10,50,100]
            :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
            @page-change="handlePageChange"
            v-show="!loadButton&&showTable"
          >
          </vxe-pager>
        </div>
      </el-card>
    </div>
    <!-- 删除提示框 -->
    <el-dialog :visible.sync="delVisible" title="提示" width="300px" center>
      <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>
  import request from '@/utils/request'

  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 {
        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位以内的数字'},
          ],
          backupB: [
            { required: true, message: '请正确填写经度' },
            {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
            // {message: '输入过长', max: 10}
          ],
          backupC: [
            { required: true, message: '请正确填写纬度' },
            {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
            // {message: '输入过长', max: 10}
          ],
          box: [
            {required: true, message: '箱变不能为空', trigger: 'blur'},
          ],
          collectorCircuit: [
            {required: true, message: '集电线不能为空', trigger: 'blur'},
          ],
          batteryModel: [
            {required: true, message: '光组型号不能为空', trigger: 'blur'},
          ],
          batteryNumber: [
            {required: true, message: '光组个数不能为空', trigger: 'blur'}
          ],
          groupSeries: [
            {required: true, message: '是否组串式逆变器不能为空', trigger: 'change'}
          ],
          sample: [
            {required: true, message: '是否样板机不能为空', trigger: 'change'}
          ],
          manufacturer: [
            {required: true, message: '制造商名称不能为空'},
          ],
          installationTime: [
            {required: true, message: '请选择日期'}
          ],
          report: [
            {required: true, message: '是否上报不能为空', trigger: 'change'}
          ]
        }
      }
    },

    created() {
      this.getData(this.currentPage, this.pageSize)
    },
    activated() {
      console.log("2激活activated钩子函数");
    },
    deactivated() {
      console.log("2激活deactivated钩子函数");
    },
    methods: {
      getData(currentPage, pageSize) {
        this.loading = true
        let url = currentPage + '/' + pageSize
        this.$axios.get('/inverterInfo/' + url).then(res => {
          if (res.data.content == "") {
            this.showTable = false

          } else {
            this.showTable = true
          }

          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(this.currentPage, this.pageSize)
      },
      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(this.currentPage, this.pageSize)
                      }).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(this.currentPage, this.pageSize)
                  }).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(this.currentPage, this.pageSize)
                  }).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(this.currentPage, this.pageSize)
        }).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>
