<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>
          <!--  <el-upload
                            :http-request="importDataEvent"
                            style="float: right;padding:3px 3px 3px 16px;"
                            action="/console/importPvModuleModelCsv/"
                            accept=".xls">
                        <el-button :loading="loadButton"   type="text">导入数据</el-button>
                    </el-upload>-->
        </div>

        <div class="filter-container">
          <el-button type="primary" size="small" style="round-clip: 10px" @click="insertEvent" :loading="loadButton">添加</el-button>
        </div>
        <div style="padding-top: 10px">
          <vxe-table
            ref="xTable"
            border
            export-config
            keep-source
            auto-resize
            resizable
            :edit-rules="rules"
            :loading="loading"
            :data="tableData"
            v-show="showTable"
            show-overflow
            highlight-current-row
            :edit-config="{trigger: 'manual', mode: 'row',autoClear:false,showStatus: true,icon:'none'}"
          >
            <vxe-table-column title="光伏组件信息" align="center">
              <vxe-table-column
                field="model"
                title="组件型号"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="singleCap"
                title="组件容量"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="maximumExcitationVoltage"
                title="最大工作电压(V)"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="maximumPowerCurrent"
                title="最大工作电流(A)"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="openCircuitVoltage"
                title="开路电压(V)"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="shortCircuitCurrent"
                title="短路电流(A)"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="efficiencyOfWork"
                title="工作效率"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="rotationMode"
                title="旋转方式"
                width="8%"
                align="center"
                :edit-render="{name: '$select', options: pvRotationMode}"
              />
              <vxe-table-column
                field="gradient"
                title="安装倾斜度"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="singleArea"
                title="组件面积(㎡)"
                width="7%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                      field="backupC"
                      title="电池板个数"
                      width="7%"
                      align="center"
                      :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />

              <vxe-table-column title="操作" width="15%" 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="mini"
                      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="mini"
                      @click="cancelRowEvent(row)"
                    >取消
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button
                      :loading="loadButton"
                      type="primary"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="mini "
                      icon="el-icon-edit"
                      @click="editRowEvent(row)"
                    >编辑
                    </el-button>
                    <el-button
                      :loading="loadButton"
                      type="danger"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="mini "
                      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"
          />
        </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>

  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].model)) {
              callback(new Error('型号不能重复'))
            }
          } else {
            // 修改
            if (this.id != s6[i].id) {
              if ((value == s6[i].model)) {
                callback(new Error('型号不能重复'))
              }
            }
          }
        }
        callback()
      }
      return {
        id:'',
        total:0,
        pageSize: 10,
        currentPage: 1,
        loadButton: false,
        rowId: '',
        showTable: true,
        tableData: [],
        delVisible: false,
        loading: false,
        // 是否为编辑
        isEdit: false,
        pvRotationMode: [],
        // 表单验证规则
        rules: {
          model: [
            { required: true, validator:checkName},
            { message: '输入过长', max: 15 }
          ],
          singleCap: [
            { required: true, message: '请填写组件容量' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          maximumExcitationVoltage: [
            { required: true, message: '请填写最大工作电压' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          maximumPowerCurrent: [
            { required: true, message: '请填写最大工作电流' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          openCircuitVoltage: [
            { required: true, message: '请填写开路电压' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          shortCircuitCurrent: [
            { required: true, message: '请填写短路电流' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          efficiencyOfWork: [
            { required: true, message: '请填写工作效率' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          gradient: [
            { required: true, message: '请填写倾斜角度' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 10 }
          ],
          rotationMode: [
            { required: true, message: '请填写旋转模式' }
          ],
          singleArea: [
            { required: true, message: '请填写单片面积' },
            {pattern: /^\d+(\.\d+)?$/, message: '只能输入正数数字或带小数点的数字'},
            { message: '输入过长', max: 15 }
          ]


        }
      }
    },
    created() {
      this.getData(this.currentPage, this.pageSize)
    },

    methods: {
      getData(currentPage, pageSize) {
        this.loading = true
        this.$axios.get('/pvModuleModel/' + currentPage + '/' + pageSize,).then((res) => {
          this.tableData = res.data.content
          if(res.data.content==''){
            this.showTable = false
          }else{
            this.showTable = true
          }
          this.total = res.data.count
          // console.log('获取光伏组件信息成功')
          this.getPvRotationMode()
          this.loading = false
        }).catch((error) => {
          this.$message.error('获取光伏组件信息出错' + error)
        })
      },
      getPvRotationMode() {
        this.$axios.get('/getPvRotationMode/').then((res) => {
          this.pvRotationMode = res.data
          // console.log('获取光伏组件旋转枚举信息成功')
        }).catch((error) => {
          this.$message.error('获取光伏组件旋转枚举信息出错' + error)
        })
      },
      handlePageChange({ currentPage, pageSize }) {
        this.currentPage = currentPage
        this.pageSize = pageSize
        this.getData(this.currentPage, this.pageSize)
      },
      insertEvent(row) {
        this.id = ''
        this.showTable = true
        this.isEdit = false
        this.loadButton = true
        this.$refs.xTable.insert()
          .then(({ row }) => this.$refs.xTable.setActiveRow(row))
      },
      editRowEvent(row) {
        this.id = row.id
        this.isEdit = true
        this.loadButton = true
        this.$refs.xTable.setActiveRow(row)
      },
      editSave(row) {
        this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(),valid => {
          if (valid) {
            this.$refs.xTable.clearActived().then(() => {
              if (this.isEdit) {
                // 编辑保存
                this.$axios.put('/pvModuleModel/',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('/pvModuleModel/',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('/pvModuleModel/'+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('/pvModuleModel/').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('/pvModuleModel/').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>
