<template>
  <a-modal centered :visible="visible" :title="modalTitle" :width="720" @close="onCancel">
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-model-item ref="dictionaryName" label="词典名称" prop="dictionaryName">
            <a-input v-model="form.dictionaryName"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item ref="dictionaryCode" label="词典标识" prop="dictionaryCode">
            <a-input v-model="form.dictionaryCode"/>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div class="draw-button-container align-center">
      <a-button @click="onCancel">取消</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </div>
    </a-drawer>
  </a-modal></template>

<script>
import { dictionaryAdd, dictionaryUpdate, dictionaryGet } from '@/api/sys/dictionary'

export default {
  props: {
    id: {
      type: String,
      default: undefined
    }
  },
  data () {
    return {
      modalTitle: '新增',
      visible: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      form: {
        dictionaryName: '',
        dictionaryCode: ''
      },
      rules: {
        dictionaryName: [
          { required: true, message: '请输入词典名称', trigger: 'blur' },
          { max: 25, message: '长度不能超过25', trigger: 'blur' }
        ],
        dictionaryCode: [
          { required: true, message: '请输入词典标识', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    add () {
      this.modalTitle = '新增'
      this.visible = true
      this.form.id = undefined
    },
    edit (obj) {
      this.modalTitle = '修改'
      this.visible = true
      dictionaryGet({ id: obj.id }).then(data => {
        const form = data.data
        this.form = form
      })
    },
    onSubmit (e) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.form.id) {
            dictionaryUpdate(this.form).then(data => {
              this.$emit('ok')
              this.onCancel()
            })
          } else {
            dictionaryAdd(this.form).then(data => {
              this.$emit('ok')
              this.onCancel()
            })
          }
        } else {
          return false
        }
      })
    },
    onCancel () {
      this.$refs.ruleForm.resetFields()
      delete this.form.id
      this.visible = false
    },
    onReset () {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>
