<script setup lang="ts">
import type { Department } from '#/api/system/dept/model';

import { defineEmits, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { addDept, deptDetail, updateDept } from '#/api/system/dept/dept';

import { drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();

const [Form, formApi] = useVbenForm({
  // 不显示提交和重置按钮
  showDefaultActions: false,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: drawerFormSchema(),
});
const isUpdateRef = ref<boolean>(false);
const [DeptDrawer, deptDrawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      deptDrawerApi.drawerLoading(true);
      let { deptId, isUpdate, parentId } = deptDrawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const deptData = await deptDetail(deptId);
        await formApi.setValues({ ...deptData, isUpdate });
      } else {
        // 如果父节点是0的话说明是根节点，将本节点id复制给根节点用于侧拉显示根节点。
        if (parentId === 0) {
          parentId = deptId;
        }
        await formApi.setValues({ parentId, isUpdate });
      }
    } catch (error) {
      console.error(error);
    } finally {
      deptDrawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    try {
      this.confirmLoading = true;
      const data = await formApi.getValues<Department>();
      // 动态判断调用新增还是修改
      isUpdateRef.value ? await updateDept(data) : await addDept(data);
      emit('reload');
      deptDrawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <DeptDrawer :title="isUpdateRef ? '编辑' : '新增'">
    <Form />
  </DeptDrawer>
</template>
<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
