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

import { ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import { updateUser } from '#/api/system/user';
import { $t } from '#/locales';

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

const emit = defineEmits(['success']);
const formData = ref<SystemUserApi.SystemUser>();
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<SystemUserApi.SystemUser>();
      console.warn('user data', formData.value);
      try {
        await updateUser(formData.value!.id, data);
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<SystemUserApi.SystemUser>();
      if (data) {
        if (data.pid === 0) {
          data.pid = undefined;
        }
        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>
