<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysDeptApi } from '#/api/auth/dept';
import type { PostApi } from '#/api/auth/post';

import { computed, ref } from 'vue';

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

import { useVbenForm } from '#/adapter/form';
import { treeList } from '#/api/auth/dept';
import { apiAdd, apiUpdate } from '#/api/auth/post';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const isUpdate = ref(false);

function genDeptTree(deptList: SysDeptApi.Dept[]): SysDeptApi.Dept[] {
  const top: SysDeptApi.Dept = {
    children: [],
    id: 0,
    name: '顶级部门',
    parentId: -1,
    nodePath: '/',
    orderNum: 0,
    status: 1,
  };
  deptList.forEach((item) => {
    if (item.parentId === 0) {
      top.children?.push(item);
    }
  });
  return [top];
}

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
    label: 'id',
  },
  {
    component: 'ApiTreeSelect',
    componentProps: {
      api: async () => {
        const deptArray = await treeList();
        const deptTree = genDeptTree(deptArray);
        addFullName(deptTree, 'name', ' / ');
        return deptTree;
      },
      class: 'w-full',
      treeLine: { showLeafIcon: false },
      treeIcon: false,
      // 筛选的字段
      treeNodeFilterProp: 'label',
      // 选中后显示在输入框的值
      treeNodeLabelProp: 'fullName',
      getVxePopupContainer,
      labelField: 'name',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'id',
      childrenField: 'children',
    },
    fieldName: 'deptId',
    label: '部门',
  },
  {
    component: 'Input',
    fieldName: 'postName',
    label: '岗位名称',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'postCode',
    label: '岗位编码',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'postCategory',
    label: '岗位类别编码',
  },
  {
    component: 'InputNumber',
    fieldName: 'postSort',
    label: '显示顺序',
    rules: 'required',
    defaultValue: 0,
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_COMMON_STATUS, true),
    },
    defaultValue: 1,
    fieldName: 'status',
    label: '状态',
    rules: 'required',
  },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '备注',
  },
];

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 [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<PostApi.Post>();
    isUpdate.value = !!data.id;
    if (isUpdate.value) {
      await formApi.setValues(data);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<PostApi.Post>();
    try {
      await (isUpdate.value ? apiUpdate(data) : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

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

const getDrawerTitle = computed(() =>
  isUpdate.value ? '修改岗位信息' : '新增岗位信息',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <BasicForm class="mx-4" />
  </Drawer>
</template>
