<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close">
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="权限码" prop="permission">
        <el-input v-model="form.permission" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="form.desc" autocomplete="off" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit, doAdd } from '@/api/roleManagement'

  export default {
    name: 'RoleManagementEdit',
    data() {
      return {
        id: '',
        form: {
          name: '',
          permission: '',
          desc: '',
        },
        rules: {
          permission: [{ required: true, trigger: 'blur', message: '请输入权限码' }],
          name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.form = {
            name: row.name,
            permission: row.permission,
            desc: row.desc,
          }
          this.id = row.id
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.id) {
              const { msg } = await doEdit(this.id, this.form)
              this.$baseMessage(msg, 'success')
            } else {
              const { msg } = await doAdd(this.form)
              this.$baseMessage(msg, 'success')
            }
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
