<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirm-loading="confirmLoading"
    cancel-text="关闭"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          prop="dictLabel"
          label="名称"
        >
          <a-input v-model="model.dictLabel" placeholder="请输入名称" />
        </a-form-model-item>
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          prop="dictValue"
          label="数据值"
        >
          <a-input v-model="model.dictValue" placeholder="请输入数据值" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction } from '@/api/request'

export default {
  name: 'DictItemModal',
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      dictId: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        dictLabel: [{ required: true, message: '请输入名称!' }],
        dictValue: [{ required: true, message: '请输入数据值!' }]
      },
      url: {
        add: '/system/dict/data',
        edit: '/system/dict/data'
      }
    }
  },
  created() {
  },
  methods: {
    add(dictId, record) {
      this.model = { dictType: record.dictType }
      this.dictId = null
      this.visible = true
    },
    edit(dictId, record) {
      this.model = Object.assign({}, record)
      this.dictId = dictId
      this.visible = true
    },
    // 确定
    handleOk() {
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          this.model.dictLabel = (this.model.dictLabel || '').trim()
          this.model.dictValue = (this.model.dictValue || '').trim()
          let url, type
          if (!this.dictId) {
            url = this.url.add
            type = 'post'
          } else {
            url = this.url.edit
            type = 'put'
          }
          httpAction(url, { ...this.model }, type).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.$emit('ok')
              this.visible = false
            } else {
              console.log(res)
            }
          })
        } else {
          return false
        }
      })
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.$refs.form.resetFields()
    }
  }
}
</script>
