<template>
  <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="controllerForm" label-well-code="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="控制器编号" prop="controllerCode">
            <el-input v-model.trim="controllerForm.controllerCode" :readonly="isEditMode" :maxlength="15" clearable type="text" placeholder="必填" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="控制器类型" prop="controllerType">
            <el-select v-model="controllerForm.controllerType" placeholder="请选择控制器型号" clearable>
              <el-option v-for="item in controllerTypeList" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="所属组织">
            <dept-select v-model="controllerForm.deptId" :dept-show="true" :need-top="true" placeholder="所属组织"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="物联网平台">
            <el-input v-model.trim="controllerForm.plantform" :maxlength="30" clearable type="text" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="15">
          <el-form-item label="电信设备编号">
            <el-input v-model.trim="controllerForm.teleId" clearable 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 DeptSelect from '@/components/DeptSelect'
import { addController, editController } from '@/api/system/device'
import { getControllerType } from '@/api/system/allDict'

export default {
  name: 'EditController',
  components: { DeptSelect },
  data() {
    const typeValidator = (rule, value, callback) => {
      if (value === 0 || value === '') {
        return callback(new Error('请选择控制器类型'))
      } else {
        return callback()
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      controllerForm: {
        id: '', // id
        controllerCode: '', // 控制器编号
        controllerType: '', // 控制器类型
        deptId: '',
        teleId: '',
        plantform: ''
      }, // 表单
      textMap: {
        update: '编辑控制器',
        create: '新增控制器',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        controllerCode: [{ required: true, message: '控制器编号不能为空', trigger: ['blur', 'change'] }],
        controllerType: [{ required: true, message: '控制器类型不能为空', trigger: ['blur', 'change'], validator: typeValidator }]
      }, // 前端校验规则
      controllerTypeList: [], // 控制器类型列表
      isEditMode: false,
      btnLoading: true // 保存按钮是否不允许点击
    }
  },
  created() {
    this.fetchControllerType() // 获取控制器类型
  },
  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.controllerForm = {
          id: row.id,
          controllerCode: row.controllerCode,
          controllerType: row.controllerType,
          deptId: row.deptId,
          teleId: row.teleId,
          plantform: row.plantform
        }
        this.isEditMode = true
      }
    },
    fetchControllerType() {
      getControllerType().then(response => {
        if (response.code === 200) {
          this.controllerTypeList = response.data
        }
      })
    },
    // 清除数据
    resetForm() {
      this.controllerForm = {
        controllerCode: '',
        controllerType: '',
        deptId: '',
        teleId: '',
        plantform: ''
      }

      this.btnLoading = false
    },
    // 保存数据
    saveData: function() {
      this.btnLoading = true

      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addController(this.controllerForm).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
            }
          }).catch(() => {
            this.btnLoading = false
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editController(this.controllerForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.cancel()
            } else {
              this.btnLoading = false
            }
          }).catch(() => {
            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>
