<script setup lang="ts">
import type { DictType } from '#/api/system/dict/dict-data-model';

import { defineEmits, ref } from 'vue';

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

import {
  addDictType,
  dictTypeDetail,
  updateDictType,
} from '#/api/system/dict/dict-data';

import { drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});
const isUpdateRef = ref<boolean>(false);
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { dictId, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate) {
        const dictTypeData = await dictTypeDetail(dictId);
        await formApi.setValues(dictTypeData);
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues<DictType>();
      isUpdateRef.value ? await updateDictType(data) : await addDictType(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
  onClosed() {
    formApi.resetForm();
  },
});
</script>

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