<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="deviceForm" label-well-code="right" label-width="100px">
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="设备编号" prop="devCode">
            <el-input v-model.trim="deviceForm.devCode" :disabled="isEditMode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="业务类型" prop="devType">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in deviceTypeList"
                :key="item.value"
                :label="item.value"
                :value="item.value"
                :checked="false"> {{ item.name }} </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="设备IP" prop="devIp">
            <el-input v-model.trim="deviceForm.devIp" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form-item label="描述" >
            <el-input v-model.trim="deviceForm.description" :maxlength="20" type="textarea" placeholder="非必填" rows = "3" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addDevice, updateDevice, getBusinessType } from '@/api/device'

export default {
  name: 'EditDevice',
  data() {
    var logchecklist = (rule, value, callback) => {
      if (this.checkList.length === 0) {
        callback(new Error('请选择设备类别'))
      } else {
        callback()
      }
    }
    const validateIp = (rule, value, callback) => {
      if (value !== '') {
        if ((/((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))/).test(value) === false) {
          callback(new Error('请填写正确的ip地址'))
        } else {
          callback()
        }
      } else {
        callback(new Error('ip地址不能为空'))
      }
    }
    return {
      checkList: [],
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      deviceForm: {
        devCode: '',
        devType: '',
        devIp: '',
        description: ''
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      deviceTypeList: null, // 设备类型列表
      deviceModelList: null, // 设备型号列表
      showDeviceType: true, // 是否显示设备类型选项
      showModelType: true, // 是否显示型号选项
      rules: {
        devCode: [{ required: true, message: '设备编号不能为空', trigger: ['blur', 'change'] }],
        devType: [{ validator: logchecklist, required: true, message: '请选择业务类型', trigger: ['blur', 'change'] }],
        devIp: [{ validator: validateIp, required: true, trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false
    }
  },
  watch: {
    'deviceForm.deviceType': function(val, oldval) {
      // this.fetchDeviceModel(val)
    }
  },
  mounted() {
    this.fetchBusinessType()
    // this.fetchDeviceModel()
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.checkList = []
      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.deviceForm = {
          devCode: row.devCode,
          devType: row.devType,
          devIp: row.devIp,
          description: row.description,
          id: row.id
        }
        this.checkList = this.deviceForm.devType.split(',')
        // if (row.deviceType !== '') {
        //   this.fetchDeviceModel(row.deviceType)
        // }
        this.isEditMode = true
      }
    },
    // 重置表单
    resetForm() {
      this.deviceForm = {
        devCode: '',
        devType: '',
        devIp: '',
        description: ''
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          that.deviceForm.devType = ''
          that.checkList.forEach(function(value, index) {
            that.deviceForm.devType += value + ','
          })
          that.deviceForm.devType = that.deviceForm.devType.substr(0, that.deviceForm.devType.length - 1)
          addDevice(that.deviceForm).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
              })
            }
          })
        }
      })
    },
    // 修改数据
    updateData: function() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          that.deviceForm.devType = ''
          that.checkList.forEach(function(value, index) {
            that.deviceForm.devType += value + ','
          })
          that.deviceForm.devType = that.deviceForm.devType.substr(0, that.deviceForm.devType.length - 1)
          console.log(that.deviceForm)
          updateDevice(that.deviceForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
          })
        }
      })
    },
    // 获取业务类型
    fetchBusinessType() {
      getBusinessType().then(response => {
        this.deviceTypeList = response.data
        if (this.deviceTypeList.length <= 1) {
          this.showDeviceType = 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%;
  }
</style>
