<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './formScheme.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import {
    functionLoadFormSort,
    functionAddFormSort,
    functionUpdateFormSort,
  } from '@/api/demo/formScheme';

  defineOptions({ name: 'FormSchemeDrawer' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 200,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
    const treeData = await functionLoadFormSort();
    updateSchema({
      field: 'parentId',
      componentProps: { treeData },
    });
    updateSchema({
      field: 'itemDetailId',
      componentProps: { treeData },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增分类' : '编辑分类'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api

      // 新增按钮
      delete values.type;
      if (values?.enabledMark == true) {
        values.enabledMark = 1;
      } else {
        values.enabledMark = 0;
      }
      if (!unref(isUpdate)) {
        await functionAddFormSort(values);
      } else {
        await functionUpdateFormSort(values);
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
