<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）" prop="electricMin">
            <el-input ref="electricMin" v-model.trim="typeForm.electricMin" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电流报警阈值上限（A）" prop="electricMax">
            <el-input ref="electricMax" v-model.trim="typeForm.electricMax" :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="电压报警阈值下限（V）" prop="voltageMin">
            <el-input ref="voltageMin" v-model.trim="typeForm.voltageMin" :maxlength="10" style="width: 100px" type="text" placeholder="下限" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电压报警阈值上限（V）" prop="voltageMax">
            <el-input ref="voltageMax" v-model.trim="typeForm.voltageMax" :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 { addLampType, updateLampType } 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: 'EditLampType',
  data() {
    // 电流阈值下限校验
    const electricMin = (rule, value, callback) => {
      const min = Number(this.$refs.electricMin.value)

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

    // 电流阈值上限校验
    const electricMax = (rule, value, callback) => {
      const max = Number(this.$refs.electricMax.value)
      const isEmpty = this.$refs.electricMax.value === ''

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

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

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

    // 电压阈值上限校验
    const voltageMax = (rule, value, callback) => {
      const max = Number(this.$refs.voltageMax.value)
      const isEmpty = this.$refs.voltageMax.value === ''

      if (isNaN(max) === true) {
        callback(new Error('电压阈值为大于0的数字'))
      } else {
        if (max >= 0) {
          const min = Number(this.$refs.voltageMin.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: '', // 离线报警时长
        electricMax: '', // 电流报警上限
        electricMin: '', // 电流报警下限
        voltageMax: '', // 电压报警上限
        voltageMin: '' // 电压报警下限
      }, // 表单
      textMap: {
        update: '编辑路灯类型',
        create: '新增路灯类型',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        typeName: [{ required: true, message: '路灯类型不能为空', trigger: ['blur', 'change'] }],
        offlineTime: [{ message: '请输入大于1的整数', validator: intValidator, trigger: ['blur'] }],
        electricMin: [{ validator: electricMin, trigger: ['blur', 'change'] }],
        electricMax: [{ validator: electricMax, trigger: ['blur', 'change'] }],
        voltageMin: [{ validator: voltageMin, trigger: ['blur', 'change'] }],
        voltageMax: [{ validator: voltageMax, 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,
          electricMin: row.electricMin,
          electricMax: row.electricMax,
          voltageMin: row.voltageMin,
          voltageMax: row.voltageMax
        }
        this.isEditMode = true
      }
    },
    // 清除数据
    resetForm() {
      this.typeForm = {
        typeName: '',
        offlineAlarm: '0',
        offlineTime: 1,
        electricAlarm: '0',
        voltageAlarm: '0',
        electricMin: 0,
        electricMax: '',
        voltageMin: 0,
        voltageMax: ''
      }

      this.btnLoading = false
    },
    clearOfflineTime() {
      this.typeForm.offlineTime = 1
    },
    clearElectricMinMax() {
      this.typeForm.electricMax = ''
      this.typeForm.electricMin = 0
    },
    clearVoltageMinMax() {
      this.typeForm.voltageMax = ''
      this.typeForm.voltageMin = 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) {
          addLampType(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) {
          updateLampType(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>
