<script setup lang="ts">
// @ts-ignore
import type { Department } from '#/api/system/dept/model';

import { ref } from 'vue';

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

// @ts-ignore
import { useVbenForm } from '#/adapter/form';
import {
  addQuestionCategory,
  questionCategoryOne,
  updateQuestionCategory,
  // @ts-ignore
} from '#/api/exam/question/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 [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: any) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      let { id, isUpdate, parentId } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const deptData = await questionCategoryOne(id);
        await formApi.setValues({ ...deptData, isUpdate });
      } else {
        // 如果父节点是0的话说明是根节点，将本节点id复制给根节点用于侧拉显示根节点。
        if (parentId === 0) {
          parentId = id;
        }
        await formApi.setValues({ parentId, isUpdate });
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    try {
      this.confirmLoading = true;
      const data = await formApi.getValues<Department>();
      // 动态判断调用新增还是修改
      isUpdateRef.value
        ? await updateQuestionCategory(data)
        : await addQuestionCategory(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑' : '新增'">
    <Form />
  </Drawer>
</template>
<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
