// 添加/修改用户库
<template>
  <el-dialog
    :title="isEdit ? '编辑用户库' : '添加用户库'"
    width="500px"
    :visible.sync="visible"
    :destroy-on-close="false"
    :close-on-click-modal="false"
    :center="true"
  >
    <el-form ref="form" :rules="rules" :model="form" label-position="left" label-width="120px">
      <el-form-item prop="id" style="margin-bottom: 0;">&nbsp;</el-form-item>
      <el-form-item label="用户库ID" prop="groupId" required>
        <el-input v-model="form.groupId" />
      </el-form-item>
      <el-form-item label="用户库名称" prop="userLibName" required>
        <el-input v-model="form.userLibName" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add } from '@/api/userlib'

export default {
  data() {
    return {
      form: {
        id: null,
        groupId: null,
        userLibName: null
      },
      rules: {
        groupId: [
          { required: true, whitespace: true, message: '不能为空!', trigger: ['change', 'blur'] }
        ],
        userLibName: [
          { required: true, whitespace: true, message: '不能为空!', trigger: ['change', 'blur'] }
        ]
      },
      visible: false,
      submitLoading: false,
      isEdit: false
    }
  },
  methods: {
    open(obj) {
      this.visible = true
      this.submitLoading = false
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (obj && Object.keys(obj).length > 0) {
          this.form = obj
          this.isEdit = true
        } else {
          this.isEdit = false
        }
      })
    },
    submit(e) {
      e.preventDefault()
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return false
        }
        if (this.submitLoading) {
          return
        }
        this.submitLoading = true
        try {
          await add(this.form)
          this.visible = false
          this.$emit('success', this.isEdit)
        } catch (e) {
          console.info('add', e)
        } finally {
          this.submitLoading = false
        }
      })
    }
  }
}
</script>
