<template>
  <a-modal 
  :title=title
  :width="640" 
  :visible="visible" 
  :confirmLoading="loading" 
  okText="确定"
  cancelText="取消"
  @ok="() => { $emit('ok') }" 
  @cancel="() => { $emit('cancel') }">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-decorator="['nickname', {rules: [{required: true, message: '必填项不能为空！'}]}]" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input  :max="11" v-decorator="['TelPhone', {rules: [{required: true, message: '必填项不能为空！'}]}]" />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea  v-decorator="['Desc']" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import pick from 'lodash.pick'

  // 表单字段
  const fields = ['nickname', 'id', 'TelPhone', 'Desc']

  export default {
    props: {
      visible: {
        type: Boolean,
        required: true
      },
      loading: {
        type: Boolean,
        default: () => false
      },
      model: {
        type: Object,
        default: () => null
      }
    },
    data() {
      this.formLayout = {
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 7
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 13
          }
        }
      }
      return {
        title: '添加设备',
        form: this.$form.createForm(this)
      }
    },
    created() {
      fields.forEach(v => this.form.getFieldDecorator(v))
      this.$watch('model', () => {
        if(this.model){
          console.log(this.model)
          this.title = '编辑用户'
          this.model && this.form.setFieldsValue(pick(this.model, fields))
        }else{
          this.title = '添加设备'
        }
       
      })
    }
  }
</script>
