<template>
  <vxe-modal
    resize
    v-model="showModal"
    :title="modalTitle"
    @hide="onHide"
    width="500px"
    show-maximize
    show-footer
    esc-closable
  >
    <el-form ref="formRef" :model="form" :rules="rules" inline label-width="80px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item class="w-full" label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="角色编码" prop="roleCode">
            <el-input v-model="form.roleCode" placeholder="请输入角色编码" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="角色描述" prop="roleDesc">
            <el-input v-model="form.roleDesc" placeholder="请输入角色描述" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
    </template>
  </vxe-modal>
</template>

<script setup name="menuFormModal">
  import { ref, computed } from 'vue';
  import { saveRole } from '@/api/role';
  import { ElMessage } from 'element-plus';

  const emits = defineEmits(['success']);
  const currentRole = ref(null);
  const showModal = ref(false);
  const formRef = ref(null);

  const isEdit = computed(() => !!currentRole.value);
  const modalTitle = computed(() => (isEdit.value ? '编辑角色' : '新增角色'));

  const form = ref({
    roleName: '',
    roleCode: '',
    roleDesc: '',
  });
  const rules = ref({
    roleName: { required: true, message: '请输入角色名称', trigger: 'blur' },
    roleCode: { required: true, message: '请输入角色编码', trigger: 'blur' },
  });

  const loading = ref(false);
  const submitForm = async () => {
    try {
      await formRef.value.validate();
      loading.value = true;

      await saveRole(form.value);
      emits('success');
      ElMessage({
        type: 'success',
        message: isEdit.value ? '修改成功！' : '添加成功!',
        plain: true,
      });
      showModal.value = false;
    } catch {}
    loading.value = false;
  };
  const onHide = () => {
    form.value = {
      roleName: '',
      roleCode: '',
      roleDesc: '',
    };
    formRef.value.clearValidate();
    currentRole.value = null;
  };
  const openModal = (role) => {
    role && (form.value = role);
    currentRole.value = role;
    showModal.value = true;
  };

  defineExpose({
    openModal,
  });
</script>
