<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="typeForm" label-well-code="right" label-width="200px">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="灯箱类型" prop="typeName">
            <el-input v-model.trim="typeForm.typeName" :maxlength="30" type="text" placeholder="必填" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-show="false" :gutter="20">
        <el-col :span="20">
          <el-form-item label="是否启用离线报警" prop="offlineAlarm">
            <el-radio v-model="typeForm.offlineAlarm" label="1">是</el-radio>
            <el-radio v-model="typeForm.offlineAlarm" label="0">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="false" :gutter="20">
        <el-col :span="20">
          <el-form-item label="离线报警阈值（分钟）" prop="offlineTime">
            <el-input-number v-model="typeForm.offlineTime" :min="1" controls-position="right" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="是否启用电流报警" prop="electricAlarm">
            <el-radio v-model="typeForm.electricAlarm" label="1">是</el-radio>
            <el-radio v-model="typeForm.electricAlarm" label="0">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="showElectricAlarm" :gutter="20">
        <el-col :span="12">
          <el-form-item label="A相电流报警阈值下限（A）" prop="electricMinA">
            <el-input ref="electricMinA" v-model.trim="typeForm.electricMinA" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="A相电流报警阈值上限（A）" prop="electricMaxA">
            <el-input ref="electricMaxA" v-model.trim="typeForm.electricMaxA" :maxlength="10" style="width: 100px" type="text" placeholder="上限" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="showElectricAlarm" :gutter="20">
        <el-col :span="12">
          <el-form-item label="B相电流报警阈值下限（A）" prop="electricMinB">
            <el-input ref="electricMinB" v-model.trim="typeForm.electricMinB" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="B相电流报警阈值上限（A）" prop="electricMaxB">
            <el-input ref="electricMaxB" v-model.trim="typeForm.electricMaxB" :maxlength="10" style="width: 100px" type="text" placeholder="上限" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="showElectricAlarm" :gutter="20">
        <el-col :span="12">
          <el-form-item label="C相电流报警阈值下限（A）" prop="electricMinC">
            <el-input ref="electricMinC" v-model.trim="typeForm.electricMinC" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="C相电流报警阈值上限（A）" prop="electricMaxC">
            <el-input ref="electricMaxC" v-model.trim="typeForm.electricMaxC" :maxlength="10" style="width: 100px" type="text" placeholder="上限" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="是否启用电压报警" prop="voltageAlarm">
            <el-radio v-model="typeForm.voltageAlarm" label="1">是</el-radio>
            <el-radio v-model="typeForm.voltageAlarm" label="0">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="showVoltageAlarm" :gutter="20">
        <el-col :span="12">
          <el-form-item label="A相电压报警阈值下限（V）" prop="voltageMinA">
            <el-input ref="voltageMinA" v-model.trim="typeForm.voltageMinA" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="A相电压报警阈值上限（V）" prop="voltageMaxA">
            <el-input ref="voltageMaxA" v-model.trim="typeForm.voltageMaxA" :maxlength="10" style="width: 100px" type="text" placeholder="上限" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="showVoltageAlarm" :gutter="20">
        <el-col :span="12">
          <el-form-item label="B相电压报警阈值下限（V）" prop="voltageMinB">
            <el-input ref="voltageMinB" v-model.trim="typeForm.voltageMinB" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="B相电压报警阈值上限（V）" prop="voltageMaxB">
            <el-input ref="voltageMaxB" v-model.trim="typeForm.voltageMaxB" :maxlength="10" style="width: 100px" type="text" placeholder="上限" />
          </el-form-item>
        </el-col>
      </el-row> <el-row v-show="showVoltageAlarm" :gutter="20">
        <el-col :span="12">
          <el-form-item label="C相电压报警阈值下限（V）" prop="voltageMinC">
            <el-input ref="voltageMinC" v-model.trim="typeForm.voltageMinC" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="C相电压报警阈值上限（V）" prop="voltageMaxC">
            <el-input ref="voltageMaxC" v-model.trim="typeForm.voltageMaxC" :maxlength="10" style="width: 100px" type="text" placeholder="上限" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addLampboxType, updateLampboxType } from '@/api/system/base'

export function intValidator(rule, value, callback) {
  if (!value) {
    return callback(new Error())
  }
  if (!Number(value)) {
    callback(new Error())
  } else {
    const re = /^[0-9]*[1-9][0-9]*$/
    const rsCheck = re.test(value)
    if (rsCheck === false) {
      callback(new Error())
    } else {
      callback()
    }
  }
}

export default {
  name: 'EditLampboxType',
  data() {
    // 电流阈值下限校验
    const electricMinA = (rule, value, callback) => {
      const min = Number(this.$refs.electricMinA.value)

      if (isNaN(min) === true) {
        callback(new Error('电流阈值为大于0的数字'))
      } else {
        if (min >= 0) {
          const max = Number(this.$refs.electricMaxA.value)
          if (isNaN(max) === false && max > 0 && min >= max) {
            callback(new Error('电流阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('电流阈值为大于0的数字'))
        }
      }
    }
    // 电流阈值上限校验
    const electricMaxA = (rule, value, callback) => {
      const max = Number(this.$refs.electricMaxA.value)
      const isEmpty = this.$refs.electricMaxA.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电流阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.electricMinA.value)
          if (isNaN(min) === false && isEmpty === false && min >= max) {
            callback(new Error('电流阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    // 电压阈值下限校验
    const voltageMinA = (rule, value, callback) => {
      const min = Number(this.$refs.voltageMinA.value)

      if (isNaN(min) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (min >= 0) {
          const max = Number(this.$refs.voltageMaxA.value)
          if (isNaN(max) === false && max > 0 && min >= max) {
            callback(new Error('电压阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('电压阈值为大于0的数字'))
        }
      }
    }
    // 电压阈值上限校验
    const voltageMaxA = (rule, value, callback) => {
      const max = Number(this.$refs.voltageMaxA.value)
      const isEmpty = this.$refs.voltageMaxA.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.voltageMinA.value)
          if (isNaN(min) === false && isEmpty === false && min >= max) {
            callback(new Error('电压阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }

    // 电流阈值下限校验
    const electricMinB = (rule, value, callback) => {
      const min = Number(this.$refs.electricMinB.value)

      if (isNaN(min) === true) {
        callback(new Error('电流阈值为大于0的数字'))
      } else {
        if (min >= 0) {
          const max = Number(this.$refs.electricMaxB.value)
          if (isNaN(max) === false && max > 0 && min >= max) {
            callback(new Error('电流阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('电流阈值为大于0的数字'))
        }
      }
    }
    // 电流阈值上限校验
    const electricMaxB = (rule, value, callback) => {
      const max = Number(this.$refs.electricMaxB.value)
      const isEmpty = this.$refs.electricMaxB.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电流阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.electricMinB.value)
          if (isNaN(min) === false && isEmpty === false && min >= max) {
            callback(new Error('电流阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    // 电压阈值下限校验
    const voltageMinB = (rule, value, callback) => {
      const min = Number(this.$refs.voltageMinB.value)

      if (isNaN(min) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (min >= 0) {
          const max = Number(this.$refs.voltageMaxB.value)
          if (isNaN(max) === false && max > 0 && min >= max) {
            callback(new Error('电压阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('电压阈值为大于0的数字'))
        }
      }
    }
    // 电压阈值上限校验
    const voltageMaxB = (rule, value, callback) => {
      const max = Number(this.$refs.voltageMaxB.value)
      const isEmpty = this.$refs.voltageMaxB.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.voltageMinB.value)
          if (isNaN(min) === false && isEmpty === false && min >= max) {
            callback(new Error('电压阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }

    // 电流阈值下限校验
    const electricMinC = (rule, value, callback) => {
      const min = Number(this.$refs.electricMinC.value)

      if (isNaN(min) === true) {
        callback(new Error('电流阈值为大于0的数字'))
      } else {
        if (min >= 0) {
          const max = Number(this.$refs.electricMaxC.value)
          if (isNaN(max) === false && max > 0 && min >= max) {
            callback(new Error('电流阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('电流阈值为大于0的数字'))
        }
      }
    }
    // 电流阈值上限校验
    const electricMaxC = (rule, value, callback) => {
      const max = Number(this.$refs.electricMaxC.value)
      const isEmpty = this.$refs.electricMaxC.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电流阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.electricMinC.value)
          if (isNaN(min) === false && isEmpty === false && min >= max) {
            callback(new Error('电流阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    // 电压阈值下限校验
    const voltageMinC = (rule, value, callback) => {
      const min = Number(this.$refs.voltageMinC.value)

      if (isNaN(min) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (min >= 0) {
          const max = Number(this.$refs.voltageMaxC.value)
          if (isNaN(max) === false && max > 0 && min >= max) {
            callback(new Error('电压阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback(new Error('电压阈值为大于0的数字'))
        }
      }
    }
    // 电压阈值上限校验
    const voltageMaxC = (rule, value, callback) => {
      const max = Number(this.$refs.voltageMaxC.value)
      const isEmpty = this.$refs.voltageMaxC.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.voltageMinC.value)
          if (isNaN(min) === false && isEmpty === false && min >= max) {
            callback(new Error('电压阈值下限需要小于上限值'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      typeForm: {
        id: '', // id
        typeName: '', // 类型名
        offlineAlarm: '0', // 是否离线报警
        electricAlarm: '0', // 是否电流报警
        voltageAlarm: '0', // 是否电压报警
        offlineTime: '', // 离线报警时长
        electricMaxA: '', // 电流报警上限
        electricMinA: '', // 电流报警下限
        voltageMaxA: '', // 电压报警上限
        voltageMinA: '', // 电压报警下限
        electricMaxB: '', // 电流报警上限
        electricMinB: '', // 电流报警下限
        voltageMaxB: '', // 电压报警上限
        voltageMinB: '', // 电压报警下限
        electricMaxC: '', // 电流报警上限
        electricMinC: '', // 电流报警下限
        voltageMaxC: '', // 电压报警上限
        voltageMinC: '' // 电压报警下限
      }, // 表单
      textMap: {
        update: '编辑灯箱类型',
        create: '新增灯箱类型',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        typeName: [{ required: true, message: '灯箱类型不能为空', trigger: ['blur', 'change'] }],
        offlineTime: [{ message: '请输入大于1的整数', validator: intValidator, trigger: ['blur'] }],
        electricMinA: [{ validator: electricMinA, trigger: ['blur', 'change'] }],
        electricMaxA: [{ validator: electricMaxA, trigger: ['blur', 'change'] }],
        voltageMinA: [{ validator: voltageMinA, trigger: ['blur', 'change'] }],
        voltageMaxA: [{ validator: voltageMaxA, trigger: ['blur', 'change'] }],
        electricMinB: [{ validator: electricMinB, trigger: ['blur', 'change'] }],
        electricMaxB: [{ validator: electricMaxB, trigger: ['blur', 'change'] }],
        voltageMinB: [{ validator: voltageMinB, trigger: ['blur', 'change'] }],
        voltageMaxB: [{ validator: voltageMaxB, trigger: ['blur', 'change'] }],
        electricMinC: [{ validator: electricMinC, trigger: ['blur', 'change'] }],
        electricMaxC: [{ validator: electricMaxC, trigger: ['blur', 'change'] }],
        voltageMinC: [{ validator: voltageMinC, trigger: ['blur', 'change'] }],
        voltageMaxC: [{ validator: voltageMaxC, trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false,
      btnLoading: true // 保存按钮是否不允许点击
    }
  },
  computed: {
    showOfflineAlarm: function() {
      if (this.typeForm.offlineAlarm === '1') {
        return true
      } else {
        this.clearOfflineTime()
        return false
      }
    },
    showElectricAlarm: function() {
      if (this.typeForm.electricAlarm === '1') {
        return true
      } else {
        this.clearElectricMinMax()
        return false
      }
    },
    showVoltageAlarm: function() {
      if (this.typeForm.voltageAlarm === '1') {
        return true
      } else {
        this.clearVoltageMinMax()
        return false
      }
    }
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.btnLoading = false
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.typeForm = {
          id: row.id,
          typeName: row.typeName,
          offlineAlarm: row.offlineAlarm,
          electricAlarm: row.electricAlarm,
          voltageAlarm: row.voltageAlarm,
          offlineTime: row.offlineAlarm,
          electricMinA: row.electricMinA,
          electricMaxA: row.electricMaxA,
          voltageMinA: row.voltageMinA,
          voltageMaxA: row.voltageMaxA,
          electricMinB: row.electricMinB,
          electricMaxB: row.electricMaxB,
          voltageMinB: row.voltageMinB,
          voltageMaxB: row.voltageMaxB,
          electricMinC: row.electricMinC,
          electricMaxC: row.electricMaxC,
          voltageMinC: row.voltageMinC,
          voltageMaxC: row.voltageMaxC
        }
        this.isEditMode = true
      }
    },
    // 清除数据
    resetForm() {
      this.typeForm = {
        typeName: '',
        offlineAlarm: '0',
        offlineTime: 1,
        electricAlarm: '0',
        voltageAlarm: '0',
        electricMinA: 0,
        electricMaxA: '',
        voltageMinA: 0,
        voltageMaxA: '',
        electricMinB: 0,
        electricMaxB: '',
        voltageMinB: 0,
        voltageMaxB: '',
        electricMinC: 0,
        electricMaxC: '',
        voltageMinC: 0,
        voltageMaxC: ''
      }

      this.btnLoading = false
    },
    clearOfflineTime() {
      this.typeForm.offlineTime = 1
    },
    clearElectricMinMax() {
      this.typeForm.electricMaxA = ''
      this.typeForm.electricMinA = 0
      this.typeForm.electricMaxB = ''
      this.typeForm.electricMinB = 0
      this.typeForm.electricMaxC = ''
      this.typeForm.electricMinC = 0
    },
    clearVoltageMinMax() {
      this.typeForm.voltageMaxA = ''
      this.typeForm.voltageMinA = 0
      this.typeForm.voltageMaxB = ''
      this.typeForm.voltageMinB = 0
      this.typeForm.voltageMaxC = ''
      this.typeForm.voltageMinC = 0
    },
    // 保存数据
    saveData: function() {
      this.btnLoading = true

      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      console.log(this.dialogStatus)
      this.$refs['dataForm'].validate((valid) => {
        console.log('validate:' + valid)
        if (valid) {
          addLampboxType(this.typeForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
              })
            } else {
              this.btnLoading = false
            }
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.typeForm)
          updateLampboxType(this.typeForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.cancel()
            } else {
              this.btnLoading = false
            }
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .dialog-footer {
    margin-top: -20px;
    text-align: center;
  }
</style>
