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

import { ref } from 'vue';

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

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

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

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

const emit = defineEmits(['success']);
const userStore = useUserStore();
const formData = ref<DeviceApi.Device>();
const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: useCreateSchema(),
  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<DeviceApi.Device>();
      data.org_id = userStore?.userInfo?.org_id || '';
      console.warn('user data', data);
      try {
        await createDevice(data);
        modalApi.close();
        emit('success');
      } catch (error) {
        console.warn(error);
      } finally {
        modalApi.close();
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<DeviceApi.Device>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
      }
    }
  },
});
</script>

<template>
  <Drawer>
    <Form>
      <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>
