<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 :gutter="20">
        <!--<el-col :span="12">-->
        <!--<el-form-item label="设备名称" prop="deviceName">-->
        <!--<el-input v-model.trim="deviceForm.deviceName" type="text" placeholder="必填"/>-->
        <!--</el-form-item>-->
        <!--</el-col>-->
        <el-col :span="12">
          <el-form-item label="设备编号" prop="devcode">
            <el-input v-model.trim="deviceForm.devcode" :disabled="isEditMode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装日期" prop="installDate">
            <el-date-picker
              v-model.trim="deviceForm.installDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="deviceForm.deviceType" :disabled="isEditMode" placeholder="请选择设备类型">
              <el-option
                v-for="item in deviceTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="modelId">
            <el-select v-model="deviceForm.modelId" placeholder="请选择设备型号">
              <el-option
                v-for="item in deviceModelList"
                :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="12">
          <el-form-item label="闸井编号" prop="wellCode">
            <el-input v-model.trim="deviceForm.wellCode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="集中器编号" prop="concenCode">
            <el-input v-model.trim="deviceForm.concenCode" type="text" placeholder="非必填"/>
          </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, getDeviceType, getDeviceModel } from '@/api/device'

export default {
  name: 'EditDevice',
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      deviceForm: {
        id: '',
        deviceName: '',
        devcode: '',
        deviceType: '',
        wellCode: '',
        modelId: '',
        installDate: '',
        concenCode: ''
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      deviceTypeList: null, // 设备类型列表
      deviceModelList: null, // 设备型号列表
      showDeviceType: true, // 是否显示设备类型选项
      showModelType: true, // 是否显示型号选项
      rules: {
        // deviceName: [{ required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }],
        devcode: [{ required: true, message: '设备编号不能为空', trigger: ['blur', 'change'] }],
        wellCode: [{ required: true, message: '闸井编号不能为空', trigger: ['blur', 'change'] }],
        deviceType: [{ required: true, message: '设备类型必选', trigger: ['blur', 'change'] }],
        modelId: [{ required: true, message: '设备型号必选', trigger: ['blur', 'change'] }],
        installDate: [{ required: true, message: '安装日期必选', trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false
    }
  },
  watch: {
    'deviceForm.deviceType': function(val, oldval) {
      this.fetchDeviceModel(val)
    }
  },
  mounted() {
    this.fetchDeviceType()
    // this.fetchDeviceModel()
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      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 = {
          id: row.id,
          deviceName: row.deviceName,
          devcode: row.devcode,
          deviceType: row.deviceType,
          modelId: row.modelId,
          wellCode: row.wellCode,
          concenCode: row.concenCode,
          installDate: row.installDate
        }
        if (row.deviceType !== '') {
          this.fetchDeviceModel(row.deviceType)
        }
        this.isEditMode = true
      }
    },
    // 重置表单
    resetForm() {
      this.deviceForm = {
        id: '',
        deviceName: '',
        devcode: '',
        deviceType: '',
        wellCode: '',
        modelId: '',
        installDate: '',
        concenCode: ''
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.deviceForm)
        if (valid) {
          addDevice(this.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() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateDevice(this.deviceForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
          })
        }
      })
    },
    // 获取设备型号
    fetchDeviceType() {
      getDeviceType().then(response => {
        this.deviceTypeList = response.data
        if (this.deviceTypeList.length <= 1) {
          this.showDeviceType = false
        }
      })
    },
    // 获取设备型号
    fetchDeviceModel(val) {
      getDeviceModel(val).then(response => {
        this.deviceModelList = response.data
        if (this.deviceModelList.length <= 1) {
          this.showModelType = 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>
