<template>
  <a-modal :visible="visible" :title="modalTitle" @ok="onSubmit" @cancel="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-if="operable" v-model="form.dictionaryName"/>
            <span v-else>{{ form.dictionaryName }}</span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- <a-row>
        <a-col :span="12">
          <a-form-model-item ref="dictionaryCode" label="词典标识" prop="dictionaryCode">
            <a-input v-if="operable" v-model="form.dictionaryCode"/>
            <span v-else>{{ form.dictionaryCode }}</span>
          </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" :disabled="!operable">保存</a-button>
    </div>
  </a-modal>
</template>

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

export default {
  props: {
    id: {
      type: String,
      default: undefined
    }
  },
  data () {
    return {
      modalTitle: '新增',
      visible: false,
      operable: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      form: {
        dictionaryName: ''
      },
      rules: {
        dictionaryName: [
          { required: true, message: '请输入词典名称', trigger: 'blur' },
          { max: 25, message: '长度不能超过25', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    add () {
      this.modalTitle = '新增'
      this.visible = true
      this.operable = true
      this.form.id = undefined
    },
    edit (obj) {
      this.modalTitle = '修改'
      this.visible = true
      this.operable = true
      this.form = obj
    },
    detail (obj) {
      this.modalTitle = '详情'
      this.visible = true
      this.operable = false
      this.form = obj
    },
    onSubmit (e) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.form)
          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.form = {}
      this.visible = false
    }
  }
}
</script>
