<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div class="app-container">
    <el-card class="box-carde">
      <div slot="header" class="clearfix">
        <span>风机信息</span>
        <el-button style="float: right;padding:3px 10px 3px 3px;" type="text" @click="exportDataEvent">导出数据
        </el-button>
      </div>
      <el-button
        type="primary"
        size="small"
        style="round-clip: 10px"
        :loading="btnLonding"
        @click="insertEvent"
      >新增
      </el-button>
      <el-button
        size="small"
        :loading="btnLonding"
        type="primary"
        style="round-clip: 10px"
        @click="piInsertEvent"
      >
        批量添加
      </el-button>
      <el-button
        size="small"
        :loading="btnLonding"
        type="danger"
        style="round-clip: 10px"
        @click="getSelectionEvent"
      >
        批量删除
      </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>-->
      <!--<vxe-button icon="fa fa-plus">新增</vxe-button>-->
      <div style="padding-top: 10px">
        <vxe-table
          ref="xTable"
          v-loading="false"
          v-show="showTable"
          :keep-source="true"
          align="center"
          :loading="loading"
          auto-resize
          highlight-current-row
          border
          resizable
          show-overflow
          :edit-rules="rules"
          :data="tableData"
          :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
        >
          <vxe-table-column title="风机信息">
            <vxe-table-column type="checkbox" width="3%"/>
            <vxe-table-column
              field="name"
              width="10%"
              title="风机名称"
              :edit-render="{name:'$input',attrs:{type:'text'}}"
            />
            <vxe-table-column
              field="modelNumber"
              width="10%"
              title="风机型号"
              :edit-render="{name:'$input',attrs:{type:'text'}}"
            />

            <vxe-table-column
              field="manufacturer"
              width="10%"
              title="生产商"
              :edit-render="{name: '$input', attrs: {type: 'text'}}"
            />
            <vxe-table-column
              width="10%"
              field="installationTime"
              title="安装时间"
              :edit-render="{props: {type: 'default'}}"
            >
              <template v-slot:edit="{ row }">
                <el-date-picker
                  v-model="row.installationTime"
                  size="mini"
                  style="width: 100%"
                  type="date"
                  placeholder="选择日期："
                />
              </template>
              <template v-slot="{ row }">{{ timestampToTime(row.installationTime) }}</template>
            </vxe-table-column>
            <vxe-table-column
              field="sample"
              width="10%"
              title="是否样板机"
              :edit-render="{name: '$select', options: options}"
            />
            <vxe-table-column
              field="backupA"
              width="10%"
              title="样板机编号"
              :edit-render="{name: '$input',attrs:{type:'text'}}"
            />
            <vxe-table-column
              field="report"
              width="10%"
              title="是否上报"
              :edit-render="{name: '$select', options: options}"
            />
            <vxe-table-column
              field="grade"
              width="10%"
              title="风机等级"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="airDensity"
              width="10%"
              title="设计空气密度"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="cutInSpeed"
              width="10%"
              title="切入速度"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="ratedWindSpeed"
              width="10%"
              title="额定风速(m/s)"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="cutOutSpeed"
              width="10%"
              title="切出速度"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="liveWindSpeed"
              width="10%"
              title="生存风速(m/s)"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="windWheelDiameter"
              width="10%"
              title="风轮直径(m)"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="windWheelMaxSpeed"
              width="10%"
              title="最大转速"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="windWheelMinSpeed"
              width="10%"
              title="最小转速"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="windWheelRatedSpeed"
              width="10%"
              title="额定转速"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="hubHeight"
              width="10%"
              title="轮毂高度(m)"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="collectorCircuit"
              title="集电线路"
              width="8%"
              align="center"
              :edit-render="{name: '$input', props: {type: 'text'}}"></vxe-table-column>
            <vxe-table-column
              field="parallelInDate"
              width="10%"
              title="并网日期"
              :edit-render="{props: {type: 'default'}}"
            >
              <template v-slot:edit="{ row }">
                <el-date-picker
                  v-model="row.parallelInDate"
                  size="mini"
                  style="width: 100%"
                  value-format="timestamp"
                  type="date"
                  placeholder="选择日期"
                />
              </template>
              <template v-slot="{ row }">{{ timestampToTime(row.parallelInDate) }}</template>
            </vxe-table-column>
            <vxe-table-column
              field="lifeLength"
              width="10%"
              title="使用寿命(年)"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="maxPower"
              width="10%"
              title="最大功率(KW)"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="longitude"
              width="10%"
              title="经度"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="latitude"
              width="10%"
              title="纬度"
              :edit-render="{name:'$input',attrs:{type:'number'}}"
            />
            <vxe-table-column
              field="divideIntoDifferentPeriod"
              width="10%"
              title="分期"
              :edit-render="{name:'$input',attrs:{type:'text'}}"
            />
            <vxe-table-column
              field="backupB"
              width="10%"
              title="额定功率"
              :edit-render="{name:'$input',attrs:{type:'text'}}"
            />
<!--            <vxe-table-column-->
<!--              field="powerCurveFunction"-->
<!--              width="10%"-->
<!--              title="曲线函数"-->
<!--              :edit-render="{name:'$input',attrs:{type:'text'}}"-->
<!--            />-->
<!--            <vxe-table-column-->
<!--              field="correctState"-->
<!--              width="10%"-->
<!--              title="状态码"-->
<!--              :edit-render="{name:'$input',attrs:{type:'number'}}"-->
<!--            />-->
            <vxe-table-column
              field="interval"
              title="入库间隔（单位s）"
              width="8%"
              align="center"
              :edit-render="{name: '$select', options: intervals}"
            />
            <vxe-table-column width="15%" fixed="right" title="操作">
              <template v-slot="{ row }">
                <template v-if="$refs.xTable.isActiveByRow(row)">
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    :loading="saveLoding"
                    @click="saveRowEvent(row)"
                  >保存
                  </el-button>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="cancelRowEvent(row)"
                  >取消
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    :loading="btnLonding"
                    @click="editRowEvent(row)"
                  >编辑
                  </el-button>
                  <el-button
                    type="danger"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-delete"
                    :loading="btnLonding"
                    @click="removeEvent(row)"
                  >删除
                  </el-button>
                </template>
              </template>
            </vxe-table-column>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          v-show="!btnLonding&&showTable"
          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"
        />
      </div>

    </el-card>
    <!-- 删除提示框 -->
    <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()
    }
    const checkCorrectState = (rule, value, callback) => {

      if (this.powerCurveFunction != null && this.powerCurveFunction != "") {
        var reg = new RegExp(/^[0-9]\d*$/)
        if (value == null || value == "") {
          callback(new Error('此状态码不能为空'))
        }
        if(!reg.test(value)){
          callback(new Error('此状态码只能为正整数'))
        }
      }else {
        if (value != null && value != "") {
          callback(new Error('未填写曲线函数'))
        }
      }

      callback()
    }
    return {
      powerCurveFunction:"",
      delVisible: false,
      piadd: false,
      id: '',
      checkTableDate: [],
      holidayType: '',
      loading: false,
      saveLoding: false,
      showTable: true,
      btnLonding: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      intervals: [{ key: 0, value: 0, label: '不入库' },{key: 60, value: 60, label: '一分钟'}, {key: 900, value: 900, label: '十五分钟'}],
      options: [
        {
          value: true,
          label: '是'
        },
        {
          value: false,
          label: '否'
        }
      ],
      // 表单验证规则
      rules: {
        name: [
          {required: true, validator: checkName}
        ],
        modelNumber: [
          {required: true, message: '请填写型号'},
          {pattern: /^[^ ]+$/, message: '不能输入空格或特殊符号'}
        ],
        sample: [
          {required: true, message: '请选择是否样板机'}
        ],
        grade: [
          {required: true, message: '请输入风机等级'},
          {pattern: /^[1-9]\d*$/, message: '只能输入正数数字'}
        ],
        airDensity: [
          {required: true, message: '请填写设计空气密度'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        cutOutSpeed: [
          {required: true, message: '请填写切出速度'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        cutInSpeed: [
          {required: true, message: '请填写切入速度'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        ratedWindSpeed: [
          {required: true, message: '请填写额定风速'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        liveWindSpeed: [
          {required: true, message: '请填写生存风速'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        windWheelDiameter: [
          {required: true, message: '请填写风轮直径'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        collectorCircuit: [
          {required: true, message: '集电线不能为空', trigger: 'blur'},
        ],
        windWheelRatedSpeed: [
          {required: true, message: '请填写额定转速'},
          {pattern: /^[0-9]\d*$/, message: '只能输入正数数字'}
        ],
        windWheelMinSpeed: [
          {required: true, message: '请填写最小转速'},
          {pattern: /^[0-9]\d*$/, message: '只能输入正数数字'}
        ],
        windWheelMaxSpeed: [
          {required: true, message: '请填写最大转速'},
          {pattern: /^[0-9]\d*$/, message: '只能输入正数数字'}
        ],
        hubHeight: [
          {required: true, message: '请填写轮毂高度'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        parallelInDate: [
          {required: true, message: '请选择并网时间'}
        ],
        lifeLength: [
          {required: true, message: '请填写使用寿命'},
          {pattern: /^\+?[0-9][0-9]*$/, message: '只能输入正整数'}
        ],
        maxPower: [
          {required: true, message: '请填写最大功率'},
          {pattern: /^\d+(\.\d{1,4})?$/, message: '只能输入正数数字或带小数点4位以内的数字'}
        ],
        longitude: [
          {required: true, message: '请填写经度'},
          {pattern: /^\d+(\.\d{1,6})?$/, message: '只能输入正数数字或带小数点6位以内的数字'}
        ],
        latitude: [
          {required: true, message: '请填写纬度'},
          {pattern: /^\d+(\.\d{1,6})?$/, message: '只能输入正数数字或带小数点6位以内的数字'}
        ],
        manufacturer: [
          {required: true, message: '制造商名称不能为空'}
        ],
        installationTime: [
          {required: true, message: '请选择日期'}
        ],
        report: [
          {required: true, message: '是否上报不能为空', trigger: 'change'}
        ],
        correctState: [
          {required: true, validator: checkCorrectState}
        ]
      },
      // 当前日期之前日期不可选
      pickerOptions1: {
        disabledDate(time) {
          // return time.getTime() < Date.now() - 8.64e7;
          return time.getTime() <= Date.now()
        }
      }
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    getAll() {
      this.loading = true
      this.saveLoding = false
      this.$axios.get('/windTurbineInfo/' + this.currentPage + '/' + this.pageSize).then(response => {
        if (response.data.content == '') {
          this.showTable = false
        } else {
          this.showTable = true
        }
        this.loading = false
        // window.console.log(response.data.content)
        this.tableData = response.data.content

        this.total = response.data.totalElements
        this.btnLonding = false
      })
    },
    // 编辑框改变
    editRowEvent(row) {
      this.id = row.id
      this.btnLonding = true
      this.$refs.xTable.setActiveRow(row)
    },
    // 保存数据操作
    saveRowEvent(row) {
      this.powerCurveFunction = row.powerCurveFunction
      this.saveLoding = true
      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('/windTurbineInfo/saveAll/' + startValue + '/' + endValue, row).then(res => {
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  this.btnLonding = false
                  this.getAll()
                  this.saveLoding = false
                  this.piadd = false
                }).catch((error) => {
                  this.$refs.xTable.setActiveRow(row)
                  this.$message.error('保存风机出错' + error)
                })
              } else {
                alert('数量必须是正整数')
              }
            })
          } else {
            alert('开始值必须是正整数并且不能为空')
          }
        })
      } else {
        this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(), valid => {
          if (valid) {
            if (row.id == undefined) {
              this.$axios.post('/windTurbineInfo/', row).then(response => {
                this.getAll()
                this.btnLonding = false
                this.$XModal.message({status: 'warning', message: response.message})
                this.saveLoding = false
              })
            } else {
              row.equipmentType = row.equipmentType.code
              this.$axios.put('/windTurbineInfo/', row).then(response => {
                this.getAll()
                this.$XModal.message({status: 'warning', message: response.message})
                this.saveLoding = false
              })
            }
          } else {
            this.$XModal.message({status: 'error', message: '校验不通过！'})
            this.saveLoding = false
          }
        })
      }
    },
    // 取消编辑或添加操作
    cancelRowEvent(row) {
      this.saveLoding = false
      this.btnLonding = false
      const xTable = this.$refs.xTable
      if (row.id == undefined) {
        xTable.clearActived().then(() => {
          xTable.remove(row)
        })
      } else {
        xTable.clearActived().then(() => {
          // 还原行数据
          xTable.revertData(row)
        })
      }
    },
    // 删除数据
    removeEvent(row) {
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        if (type === 'confirm') {
          this.$axios.delete('/windTurbineInfo/' + row.id).then(response => {
            this.$XModal.message({status: 'warning', message: response.message})
            this.getAll()
          })
        }
      })
    },
    // 时间戳日期转换器
    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
    },
    // 新增编辑框
    insertEvent() {
      this.piadd = false
      this.id = ''
      this.showTable = true
      this.btnLonding = true
      this.checkSign = false
      this.$refs.xTable.insert({interval: 60})
        .then(({row}) => this.$refs.xTable.setActiveRow(row))
    },
    // 分页出发事件
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getAll()
    },
    piInsertEvent(row) {
      this.piadd = true
      this.showTable = true
      this.btnLonding = true
      this.checkSign = false
      this.$refs.xTable.insert({interval: 60}).then(({row}) => this.$refs.xTable.setActiveRow(row))
    },
    getSelectionEvent() {
      const 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
    },
    // 删除场站信息
    deleteRowEvent(row) {
      this.rowId = row.id
      this.delVisible = true
    },
    deleteCancel() {
      this.delVisible = false
    },
    deleteInfo() {
      this.$axios.delete('/windTurbineInfo/deleteIds/' + '' + this.rowId).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.delVisible = false
        this.getAll()
      }).catch((error) => {
        this.$message.error('删除逆变器信息出错' + error)
      })
    },
    /* handleSizeChange(size) {
          this.pageSize = size
          this.getAll()
      },
      handleCurrentChange(currentPage) {
          this.currentPage = currentPage
          this.getAll()
      },*/
    // 导出
    exportDataEvent() {
      this.loading = true
      this.$axios.get('/windTurbineInfo/').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
      })
    },
    // 导入
    importDataEvent() {
      this.$refs.xTable.importData({types: ['csv']})
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  /*left: 0;*/
  /*width: 100%;*/
  /*min-height: 100%;*/
  /*height: auto;*/
  /*background-image: linear-gradient(25deg, #05362d, #145d44, #24875d, #35b477)*/
}

.pagination {
  margin: 20px 0;
  text-align: right;
}
</style>
