<script setup lang="ts">
import { defineEmits, ref } from 'vue';

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

import { useVbenForm } from '#/adapter/form';
import { categoryAdd, categoryInfo, categoryUpdate } from '#/api/workflow/category';

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 [CategoryDrawer, categoryDrawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      categoryDrawerApi.drawerLoading(true);
      let { categoryId, isUpdate, parentId } = categoryDrawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const categoryData = await categoryInfo(categoryId);
        await formApi.setValues({ ...categoryData });
      } else {
        await formApi.setValues({ parentId });
      }
    } catch (error) {
      console.error(error);
    } finally {
      categoryDrawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    try {
      this.confirmLoading = true;
      const data = await formApi.getValues();
      // 动态判断调用新增还是修改
      isUpdateRef.value ? await categoryUpdate(data) : await categoryAdd(data);
      emit('reload');
      categoryDrawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <CategoryDrawer :title="isUpdateRef ? '编辑' : '新增'">
    <Form />
  </CategoryDrawer>
</template>
