<template>
  <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"
          :loading="btnLonding"
          @click="exportDataEvent"
        >导出数据
        </el-button>
      </div>
      <el-button
        type="primary"
        size="small"
        style="round-clip: 10px"
        :loading="btnLonding"
        @click="insertEvent"
      >新增</el-button>
      <div style="padding-top: 10px">
        <vxe-table
          ref="xTable"
          v-show="showTable"
          :keep-source="true"
          align="center"
          :loading="loading"
          highlight-current-row
          auto-resize
          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
              field="name"
              title="名称"
              width="13%"
              :edit-render="{name: '$input', attrs: {type: 'text'}}"
            />
            <vxe-table-column
              field="manufacturer"
              title="生产商"
              width="13%"
              :edit-render="{name: '$input', attrs: {type: 'text'}}"
            />
            <vxe-table-column
              field="modelNumber"
              title="型号"
              width="13%"
              :edit-render="{name: '$input', attrs: {type: 'text'}}"
            />
            <vxe-table-column
              min-width="60px"
              width="15%"
              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="report"
              title="是否上报"
              width="8%"
              :edit-render="{name: '$select', options: options}"
            />
            <vxe-table-column
              field="interval"
              title="入库间隔（单位s）"
              width="10%"
              align="center"
              :edit-render="{name: '$select', options: intervals}"
            />
            <vxe-table-column min-width="30px" width="15%" 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"
                    @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="deleteRowEvent(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']"
        />
      </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>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Index',
  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.mid == '' || this.mid == undefined) {
          // 新增
          if ((value == s6[i].name)) {
            callback(new Error('名称不能重复'))
          }
        } else {
          // 修改
          if (this.mid != s6[i].id) {
            if ((value == s6[i].name)) {
              callback(new Error('名称不能重复'))
            }
          }
        }
      }
      callback()
    }
    return {
      mid: '',
      rowId: '',
      btnLonding: false,
      loading: false,
      showTable: true,
      delVisible: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      options: [{ label: '是', value: true }, { label: '否', value: false }],
      intervals: [{ key: 0, value: 0, label: '不入库' },{ key: 60, value: 60, label: '一分钟' }, { key: 900, value: 900, label: '十五分钟' }],
      // 是否为编辑
      isEdit: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, validator: checkName }
        ],
        modelNumber: [
          { required: true, message: '升压站型号不能为空', trigger: 'blur' }
        ],
        manufacturer: [
          { required: true, message: '制造商名称不能为空' }
        ],
        installationTime: [
          { required: true, message: '请选择日期' }
        ],
        report: [
          { required: true, message: '是否上报不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    getInfo() {
      this.$axios.get('/boosterStationInfo/').then(res => {
        this.tableData = res.data
      })
    },
    saveRowEvent(row) {
      this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(),valid => {
        if (valid) {
          this.$refs.xTable.clearActived().then(() => {
            if (this.isEdit) {
              console.log(row)
              row.equipmentType = row.equipmentType.code
              // 编辑保存
              this.$axios.put('/boosterStationInfo/', row).then(res => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.btnLonding = false
                this.getInfo()
              }).catch((error) => {
                this.$refs.xTable.setActiveRow(row)
                this.$message.error('修改升压站出错' + error)
              })
            } else {
              // 新增保存
              this.$axios.post('/boosterStationInfo/', row).then(res => {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.btnLonding = false
                this.getInfo()
              }).catch((error) => {
                this.$refs.xTable.setActiveRow(row)
                this.$message.error('保存升压站出错' + error)
              })
            }
          })
        } else {
          this.$XModal.message({status: 'error', message: '校验不通过！'})
        }
      })
    },
    editRowEvent(row) {
      this.mid = row.id
      this.isEdit = true
      this.btnLonding = true
      this.$refs.xTable.setActiveRow(row)
    },
    insertEvent(row) {
      this.mid = ''
      this.showTable = true
      this.piadd = false
      this.isEdit = false
      this.btnLonding = true
      this.$refs.xTable.insert({ interval: 60 }).then(({ row }) => this.$refs.xTable.setActiveRow(row))
    },
    exportDataEvent() {
      this.$axios.get('/boosterStationInfo/').then(res => {
        const data = res.data
        this.$refs.xTable.exportData({
          filename: '升压站信息',
          type: 'csv',
          isHeader: true,
          isFooter: true,
          data
        })
      })
    },
    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('/boosterStationInfo/' + this.rowId).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.delVisible = false
        this.getInfo()
      }).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
    }
  }
}
</script>

<style scoped>

</style>
