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

import { ref } from 'vue';

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

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

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

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

const emit = defineEmits(['success']);
const formData = ref<productionApi.production>();
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<productionApi.production>();
      try {
        if (formData.value?.id) {
          await updateProduction(formData.value?.id, data);
        }
        message.success('更新成功');
        emit('success');
        modalApi.close();
      } catch (error) {
        console.error(error);
        modalApi.unlock();
      } finally {
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<productionApi.production>();
      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>
