<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { EmployeeInfoApi } from '#/api/hr/employeeModel';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { addFullName, getVxePopupContainer } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { treeList } from '#/api/auth/dept';
import { applyTransfer } from '#/api/hr/employeeInfo';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<EmployeeInfoApi.EmployeeTransferApplyBo>();

const formSchema: VbenFormSchema[] = [
  {
    label: '主键',
    fieldName: 'id',
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    component: 'Input',
    fieldName: 'name',
    label: '姓名',
    disabled: true,
  },
  {
    component: 'ApiTreeSelect',
    componentProps: (formModel) => ({
      api: async () => {
        const deptArray = await treeList();
        // const deptTree = genDeptTree(deptArray);
        addFullName(deptArray, 'label', ' / ');
        return deptArray;
      },
      async onSelect(deptId: number | string, node: Record<string, any>) {
        /** 根据部门Node获取部门等级数组 */
        const result = node.fullName
          .split('/')
          .map((item: string) => item.trim())
          .filter(Boolean);
        /** 变化后需要重新设置部门信息 */
        formModel.plate = result[0];
        formModel.firstLevelDepartment = result[1];
        formModel.secondLevelDepartment = result[2];
        formModel.thirdLevelDepartment = result[3];
      },
      getVxePopupContainer,
      class: 'w-full',
      treeLine: { showLeafIcon: false },
      treeIcon: false,
      // 筛选的字段
      treeNodeFilterProp: 'label',
      // 选中后显示在输入框的值
      treeNodeLabelProp: 'fullName',
      // fieldNames: { label: 'label', value: 'id' },
      labelField: 'label',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'id',
      childrenField: 'children',
    }),
    fieldName: 'deptId',
    label: '新的部门',
    rules: 'selectRequired',
  },
  // {
  //   component: 'Select',
  //   componentProps: {
  //     getVxePopupContainer,
  //     placeholder: '请先选择一级部门',
  //   },
  //   fieldName: 'secondLevelDepartment',
  //   label: '二级部门',
  //   rules: 'required',
  // },
  // {
  //   component: 'Input',
  //   fieldName: 'description',
  //   label: '描述',
  //   rules: 'required',
  // },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '调配申请备注',
    formItemClass: 'items-start',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const data = modalApi.getData() as { id?: number; name?: string };
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    modalApi.lock();
    const data =
      await formApi.getValues<EmployeeInfoApi.EmployeeTransferApplyBo>();
    try {
      await applyTransfer(data);
      resetInitialized();
      emit('success');
      modalApi.close();
    } finally {
      modalApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

// const getModalTitle = computed(() =>
//   formData.value?.id ? '修改字典类型' : '新增字典类型',
// );
</script>
<template>
  <BasicModal title="调配申请">
    <BasicForm class="mx-4" />
  </BasicModal>
</template>
