<template>
    <vxe-modal
      resize
      v-model="showModal"
      :title="modalTitle"
      @hide="onHide"
      width="400px"
      show-footer
      esc-closable
    >
      <el-form ref="formRef" inline :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item class="w-full" label="部门名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item class="w-full" label="部门编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入部门编码" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
  
      <template #footer>
        <el-button type="default" @click="showModal = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </vxe-modal>
  </template>
  
  <script setup>
    import { computed } from 'vue';
    import { ref } from 'vue';
    import { saveDepartment } from '@/api/departmentManage';
    import { ElMessage } from 'element-plus';
  
    const emits = defineEmits(['success']);
    const formRef = ref();
    const showModal = ref(false);
    const loading = ref(false);
    const form = ref({
    //   code: '',
      name: '',
      parent: null
    });
    const rules = ref({
    //   code: { required: true, message: '请输入部门编码', trigger: 'blur' },
      name: [
        { required: true, message: '请输入部门名称', trigger: 'blur' }
      ],
    });
  
    const currentdepartment = ref(null);
    const isEdit = computed(() => !!currentdepartment.value);
    const modalTitle = computed(() => (isEdit.value ? '编辑部门' : '新增部门'));
  
    const submitForm = async () => {
      try {
        await formRef.value.validate();
        loading.value = true;
  
        await saveDepartment(form.value);
  
        ElMessage({
          type: 'success',
          message: isEdit.value ? '修改成功！' : '添加成功！',
          plain: true,
        });
        emits('success');
        showModal.value = false;
      } catch {}
      loading.value = false;
    };
  
    const onHide = () => {
      form.value = {
        // code: '',
        name: '',
        parent: {}
      };
      formRef.value.clearValidate();
      currentdepartment.value = null;
      showModal.value = false;
    };
    const openModal = (type, department) => {
      if (type === 'add') {
        department && (form.value.parent = department);
        !department && (form.value.parent = null);
        currentdepartment.value = null;
      } else {
        department && (form.value = department);
        currentdepartment.value = department;
      }
      
      showModal.value = true;
    };
  
    defineExpose({
      openModal,
    });
  </script>
  <style lang="scss" scoped></style>
  