<script lang="ts" setup>
// 科室新增/编辑弹窗
// 父级科室选项在打开弹窗时从接口拉取（仅一级科室可选），编辑时排除自己防止自挂
import { ref } from 'vue';

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

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

import { createDepartment, getDepartmentOption, updateDepartment } from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

/**
 * 拉取父级科室选项并注入 pid 下拉
 * 只允许一级科室作为父级（后端强制两级封顶），编辑时排除自身
 */
const loadParentOptions = async (excludeId?: number) => {
  const list = await getDepartmentOption();
  const options = [
    { label: '作为一级科室（无父级）', value: 0 },
    ...(list || [])
      .filter((item: any) => item.level === 1 && item.id !== excludeId)
      .map((item: any) => ({ label: item.name, value: item.id })),
  ];
  formApi.updateSchema([
    {
      fieldName: 'pid',
      componentProps: {
        options,
      },
    },
  ]);
};

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.lock();
        const submitApi = isUpdate.value ? updateDepartment : createDepartment;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.query();
            modalApi.close();
          })
          .finally(() => {
            modalApi.unlock();
          });
      }
    });
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      isUpdate.value = !!update;
      // 先重置再回填，避免上一次打开的残留值
      formApi.resetForm();
      loadParentOptions(update ? values?.id : undefined);
      if (values) {
        formApi.setValues(values);
      }
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate === true ? '编辑' : '新增'}科室`" class="w-[520px]">
    <Form />
  </Modal>
</template>
