<script setup lang="ts">
import type { classificationApi } from '#/api';

import { ref } from 'vue';

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

import { Button } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { updateClassification } from '#/api';
import { $t } from '#/locales';

import { useEditSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<classificationApi.classification>();
const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: useEditSchema(),
  showDefaultActions: false,
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues(formData.value || {});
}
const [Drawer, modalApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues<classificationApi.classification>();
      console.warn('user data', data);
      try {
        if (formData.value?.id) {
          await updateClassification(formData.value?.id, data);
        }
        emit('success');
        modalApi.close();
      } catch (error) {
        console.error(error);
        modalApi.unlock();
      } finally {
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<classificationApi.classification>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
      }
    }
  },
});
</script>

<template>
  <Drawer>
    <Form :title="$t('system.user.title')">
      <template #prepend-footer>
        <div class="flex-auto">
          <Button type="primary" danger @click="resetForm">
            {{ $t('common.reset') }}
          </Button>
        </div>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped></style>
