<template>
  <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" size="small" style="round-clip: 10px" :loading="loadButton" @click="insertEvent">添加
        </el-button>
        <div style="padding-top: 10px">
          <vxe-table
            v-show="showTable"
            ref="xTable"
            export-config
            :keep-source="true"
            align="center"
            :loading="loading"
            highlight-current-row
            auto-resize
            border
            resizable
            max-height="600px"
            :edit-rules="rules"
            :data="tableData"
            :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
          >
            <vxe-table-column title="附属设备信息" align="center">
              <vxe-table-column
                field="name"
                title="名称"
                width="25%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="equipmentType.code"
                title="设备类型"
                width="20%"
                :edit-render="{name: '$select', options: equipmentTypeEnum}"
                :filters="this.equipmentTypeEnum"
                :filter-multiple="false"
                :formatter="formatterEquipmentType"
              />
              <vxe-table-column
                field="code"
                title="编号"
                width="15%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="backupA"
                title="备注字段"
                width="15%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <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
            v-show="!loadButton&&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-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 {
  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: '',
      loadButton: false,
      loading: false,
      showTable: true,
      delVisible: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      equipmentTypeEnum: [],
      tableData: [],
      intervals: [{ key: 0, value: 0, label: '不入库' }, { key: 60, value: 60, label: '一分钟' }, {
        key: 900,
        value: 900,
        label: '十五分钟'
      }],
      // 是否为编辑
      isEdit: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, validator: checkName }
        ],
        equipmentType: [
          { required: true, message: '附属设备型号不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '编号不能为空' }
        ]
      }
    }
  },
  mounted() {
    this.getSubsidiaryEquipmentTypeEnum()
    this.getInfo()

  },
  methods: {
    getInfo() {
      this.$axios.get('/subsidiaryEquipmentInfo').then(res => {
        this.tableData = res.data
        this.total = res.data.length
        this.loading = false
      }).catch((error) => {
        this.$message.error('获取附属设备信息出错' + error)
      })
    },
    formatterEquipmentType({ cellValue }) {
      const item = this.equipmentTypeEnum.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    editSave(row) {
      this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(), valid => {
        if (valid) {
          this.$refs.xTable.clearActived().then(() => {
            if (this.isEdit) {
              row.equipmentType = row.equipmentType.code
              // 编辑保存
              this.$axios.put('/subsidiaryEquipmentInfo/', row).then(res => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.loadButton = false
                this.getInfo()
              }).catch((error) => {
                this.$refs.xTable.setActiveRow(row)
                this.$message.error('修改附属设备出错' + error)
              })
            } else {
              // 新增保存
              row.equipmentType = row.equipmentType.code
              this.$axios.post('/subsidiaryEquipmentInfo/', row).then(res => {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.loadButton = false
                this.getInfo()
              }).catch((error) => {
                this.$refs.xTable.setActiveRow(row)
                this.$message.error('保存附属设备出错' + error)
              })
            }
          })
        } else {
          this.$XModal.message({ status: 'error', message: '校验不通过！' })
        }
      })
    },
    getSubsidiaryEquipmentTypeEnum() {
      this.$axios.get('dataExchange/getSubsidiaryEquipmentTypeEnum').then(res => {
        this.equipmentTypeEnum = []
        // eslint-disable-next-line no-unused-vars,no-empty
        for (const i in res.data) {
          this.equipmentTypeEnum.push({ 'label': res.data[i].label, 'value': res.data[i].code })
        }
      })
    },
    editRowEvent(row) {
      this.mid = row.id
      this.isEdit = true
      this.loadButton = true
      this.$refs.xTable.setActiveRow(row)
    },
    insertEvent(row) {
      this.mid = ''
      this.showTable = true
      this.piadd = false
      this.isEdit = false
      this.loadButton = true
      this.$refs.xTable.insert({ interval: 0 }).then(({ row }) => this.$refs.xTable.setActiveRow(row))
    },
    exportDataEvent() {
      this.$axios.get('/subsidiaryEquipmentInfo/').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('/subsidiaryEquipmentInfo/' + this.rowId).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.delVisible = false
        this.getInfo()
      }).catch((error) => {
        this.$message.error('删除附属设备信息出错' + error)
      })
    }
  }
}
</script>

<style scoped>

</style>
