<template>
  <div style="padding-left: 30px">
    <div style="margin-top: 0.5%;margin-bottom: 0.2%">
      <span style="font-weight: bold">设备类型：</span>
      <vxe-select v-model="equipmentType" placeholder="请选择设备类型" style="width: 10%" clearable>
        <vxe-option v-for="item in equipmentTypeEnum" :key="item.value" :value="item.value" :label="item.label" />
      </vxe-select>
      <div style="display: inline-block">
        <vxe-toolbar>
          <template v-slot:buttons>
            <vxe-button status="primary" @click="search()">查询</vxe-button>
            <vxe-button status="primary" icon="fa fa-plus" @click="insertEvent()">新增</vxe-button>
          </template>
        </vxe-toolbar>
      </div>
    </div>
    <vxe-table
      ref="xTable"
      border
      stripe
      resizable
      show-overflow
      keep-source
      max-height="800"
      align="center"
      :edit-rules="rules"
      :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'manual', mode: 'row',autoClear: false}"
    >
      <vxe-table-column type="checkbox" width="60px" />
      <vxe-table-column field="id" title="Id" sortable />
      <vxe-table-column
        field="explanation"
        title="设备属性名称"
        width="20%"
        :edit-render="{name: '$input', props: {type: 'text',disabled: explanationDisabled}}"
      />
      <vxe-table-column
        field="fieldName"
        title="字段名称"
        width="20%"
        :edit-render="{name: '$input', props: {type: 'text',disabled: fieldNameDisabled}}"
      />
      <vxe-table-column
        field="measurementUnits"
        title="单位"
        :edit-render="{name: '$input', props: {type: 'text',disabled: unitsDisabled}}"
      />
      <vxe-table-column
        field="equipmentType"
        title="设备类型"
        :edit-render="{name: '$select', options: equipmentTypeEnum, props: {disabled: equipmentDisabled}}"
        :filters="this.equipmentTypeEnum"
        :filter-multiple="false"
      />
      <vxe-table-column
        field="equipmentAttributeTypeEnum"
        title="字段类型"
        :formatter="formateEquipmentTypeEnum"
        :edit-render="{name: '$select', options: equipmentAttributeTypeEnum, props: {disabled: equipmentAttributeDisabled}}"
        :filters="this.equipmentAttributeTypeEnum"
        :filter-multiple="false"
        :filter-method="filterMethod"
      />
      <vxe-table-column title="操作" width="150">
        <template v-slot="{ row }">
          <template v-if="$refs.xTable.isActiveByRow(row)">
            <vxe-button
              status="success"
              style="padding: 3px 4px 3px 4px;margin: 2px;"
              size="mini"
              icon="el-icon-edit"
              @click="findByEquipmentType(row)"
            >保存
            </vxe-button>
            <vxe-button
              class="cancel-btn"
              icon="el-icon-refresh"
              status="warning"
              style="padding: 3px 4px 3px 4px;margin: 2px;"
              size="mini"
              @click="cancelRowEvent(row)"
            >取消
            </vxe-button>
          </template>
          <template v-else>
            <div style="display: flex;justify-content: space-around">
              <vxe-button status="primary" size="mini" @click="editRowEvent(row)">编辑</vxe-button>
              <div v-if="row.equipmentAttributeTypeEnum == 'INVARIANT' || row.equipmentAttributeTypeEnum == 'SPARE' || row.equipmentAttributeTypeEnum == null">
                <vxe-button status="info" size="mini" disabled>删除</vxe-button>
              </div>
              <div v-else>
                <vxe-button status="danger" size="mini" @click="removeEvent(row)">删除</vxe-button>
              </div>
            </div>
          </template>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      perfect
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :total="totalResult"
      :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChangeNo"
    />
  </div>
</template>

<script>
export default {
  name: 'Index',
  data() {
    const checkExplanation = (rule, value, callback) => {
      var s6 = this.modData
      for (let i = 0; i < s6.length; i++) {
        if (this.saveFlag === 1) {
          // 新增
          if ((value == s6[i].explanation)) {
            callback(new Error('设备属性名称不能重复'))
          }
        } else {
          if (this.modId != s6[i].id) {
            if ((value == s6[i].explanation)) {
              callback(new Error('设备属性名称不能重复'))
            }
          }
        }
      }
      callback()
    }
    const checkFieldName = (rule, value, callback) => {
      var s6 = this.modData
      for (let i = 0; i < s6.length; i++) {
        if (this.saveFlag === 1) {
          // 新增
          if ((value == s6[i].fieldName)) {
            callback(new Error('字段名称不能重复'))
          }
        } else {
          if (this.modId != s6[i].id) {
            if ((value == s6[i].fieldName)) {
              callback(new Error('字段名称不能重复'))
            }
          }
        }
      }
      callback()
    }
    return {
      loading: false,
      explanationDisabled: false,
      fieldNameDisabled: false,
      unitsDisabled: false,
      equipmentDisabled: false,
      equipmentAttributeDisabled: false,
      saveFlag: 1,
      equipmentType: '',
      tableData: [],
      allData: [],
      modData: [],
      modId: '',
      equipmentTypeEnum: [],
      equipmentAttributeTypeEnum: [{ value: 'INVARIANT', label: '固定字段' }, { value: 'SPARE', label: '备用字段' }, { value: 'CUSTOM', label: '自定义字段' }],
      currentPage: 1,
      pageSize: 10,
      totalResult: 0,
      rules: {
        explanation: [
          { required: true, validator: checkExplanation }
        ],
        fieldName: [
          { required: true, validator: checkFieldName }
        ]
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      Promise.all([this.getEquipmentTypeEnum(), this.getAllData()]).then((res) => {
        this.equipmentTypeEnum = res[0]
        console.log(this.equipmentTypeEnum)
        this.allData = res[1]
        this.$nextTick(() => {
          this.get()
          this.updateEquipmentTypeFilterEvent()
        })
      })
    },
    get() {
      this.loading = true
      this.$axios.get('dataExchange/getAllByPage/' + this.currentPage + '/' + this.pageSize).then((res) => {
        this.currentPage = res.data.number + 1
        this.pageSize = res.data.size
        this.totalResult = res.data.totalElements
        this.tableData = res.data.content
        for (var i = 0; i < this.tableData.length; i++) {
          const item = this.equipmentTypeEnum.find(item => item.label === this.tableData[i].equipmentType.message)
          this.tableData[i].equipmentType = item.value
        }
        this.loading = false
      })
      //   .catch((error) => {
      //   this.loading = false
      //   this.$message.error('查询设备属性错误:' + error)
      // })
    },
    getEquipmentTypeEnum() {
      const axios = this.$axios
      return new Promise(function(resolve, reject) {
        axios.get('dataExchange/getEquipmentTypeEnum').then(res => {
          resolve(res.data)
        })
      })
    },
    getAllData() {
      const axios = this.$axios
      return new Promise(function(resolve, reject) {
        axios.get('dataExchange/getAll').then(res => {
          resolve(res.data)
        })
      })
    },
    findByEquipmentType(row) {
      const item = this.equipmentTypeEnum.find(item => item.value === row.equipmentType)
      var EquipmentTypeCode = item ? item.code : ''
      this.$axios.get('dataExchange/getByEquipmentType/' + EquipmentTypeCode).then((res) => {
        this.modData = res.data
        this.editSave(row)
      })
    },
    search() {
      this.loading = true
      if (this.equipmentType === null || this.equipmentType === '') {
        this.get()
      } else {
        this.$axios.get('dataExchange/' + this.equipmentType + '/' + this.currentPage + '/' + this.pageSize).then((res) => {
          this.currentPage = res.data.number + 1
          this.pageSize = res.data.size
          this.totalResult = res.data.totalElements
          this.tableData = res.data.content
          for (var i = 0; i < this.tableData.length; i++) {
            const item = this.equipmentTypeEnum.find(item => item.label === this.tableData[i].equipmentType.message)
            this.tableData[i].equipmentType = item.value
          }
          this.loading = false
          // console.log(res.data)
        })
      }
    },
    editSave(row) {
      this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(), valid => {
        if (valid) {
          if (this.saveFlag === 1) {
            this.$axios.post('/dataExchange/', row).then((res) => {
              if (res.data === 1) {
                this.$message.success(`保存${row.explanation}属性成功`)
              } else {
                this.$message.error(`保存${row.explanation}属性失败`)
              }
              this.init()
            }).catch((error) => {
              this.$message.error(`保存操作失败：` + error)
            })
          } else {
            this.$axios.put('/dataExchange/', row).then((res) => {
              if (res.data === 1) {
                this.$message.success(`修改${row.explanation}属性成功`)
              } else {
                this.$message.error(`修改${row.explanation}属性失败`)
              }
              this.init()
            }).catch((error) => {
              this.$message.error(`修改操作失败：` + error)
            })
          }
        } else {
          this.$message.error('校验不通过')
        }
      })
    },
    insertEvent() {
      this.saveFlag = 1
      this.explanationDisabled = false
      this.fieldNameDisabled = false
      this.unitsDisabled = false
      this.equipmentDisabled = false
      this.equipmentAttributeDisabled = true
      this.$refs.xTable.insert({ equipmentAttributeTypeEnum: 'CUSTOM' }).then(({ row }) => this.$refs.xTable.setActiveRow(row))
    },
    editRowEvent(row) {
      this.modId = row.id
      this.saveFlag = 2
      this.equipmentAttributeDisabled = true
      if (row.equipmentAttributeTypeEnum === 'INVARIANT' || row.equipmentAttributeTypeEnum === null) {
        this.explanationDisabled = true
        this.fieldNameDisabled = true
        this.unitsDisabled = false
        this.equipmentDisabled = true
      } else if (row.equipmentAttributeTypeEnum === 'SPARE') {
        this.explanationDisabled = false
        this.fieldNameDisabled = true
        this.unitsDisabled = false
        this.equipmentDisabled = true
      } else {
        this.explanationDisabled = false
        this.fieldNameDisabled = false
        this.unitsDisabled = false
        this.equipmentDisabled = false
      }
      this.$refs.xTable.setActiveRow(row)
    },
    removeEvent(row) {
      this.$axios.get('/dataExchange/dataPointById/' + row.id).then((res) => {
        console.log(res.data)
        if (res.data.length > 0) {
          this.$message.warning(`${row.explanation}属性已经配置点表不可删除`)
        } else {
          this.$XModal.confirm('您确定要删除该数据?').then(type => {
            if (type === 'confirm') {
              this.$axios.delete('/dataExchange/' + row.id).then((res) => {
                if (res.data === 1) {
                  this.$message.success(`删除${row.explanation}属性成功`)
                  this.$refs.xTable.remove(row)
                } else {
                  this.$message.error(`删除${row.explanation}属性失败`)
                }
              }).catch((error) => {
                this.$message.error(`删除操作失败：` + error)
              })
            }
          })
        }
      })
    },
    cancelRowEvent(row) {
      const xTable = this.$refs.xTable
      if (row.id == undefined) {
        xTable.clearActived().then(() => {
          xTable.remove(row)
        })
      } else {
        xTable.clearActived().then(() => {
          // 还原行数据
          xTable.revertData(row)
        })
      }
    },
    // 转换文件类型协议
    formateEquipmentTypeEnum({ cellValue }) {
      if (cellValue === null) {
        return '固定字段'
      }
      const item = this.equipmentAttributeTypeEnum.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    // 过滤条件赋值，重新处理
    updateEquipmentTypeFilterEvent() {
      var data = []
      for (var i = 0; i < this.equipmentTypeEnum.length; i++) {
        data.push({ value: this.equipmentTypeEnum[i].value, label: this.equipmentTypeEnum[i].label })
      }
      const xTable = this.$refs.xTable
      const column = xTable.getColumnByField('equipmentType')
      // 修改筛选列表，并默认设置为选中状态
      xTable.setFilter(column, data)
      // 修改条件之后，需要手动调用 updateData 处理表格数据
      xTable.updateData()
    },
    filterMethod({ value, row, column }) {
      if (value === 'INVARIANT' || value === null) {
        return row.equipmentAttributeTypeEnum === 'INVARIANT' || row.equipmentAttributeTypeEnum === null
      } else if (value === 'SPARE') {
        return row.equipmentAttributeTypeEnum === 'SPARE'
      } else {
        return row.equipmentAttributeTypeEnum === 'CUSTOM'
      }
    },
    handlePageChangeNo({ currentPage, pageSize }) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      if (this.equipmentType != '') {
        this.search()
      } else {
        this.get()
      }
    }
  }
}
</script>

<style scoped>

</style>
