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

import { computed, ref } from 'vue';

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

import { useRequest } from '@six/request';
import { Button } from 'ant-design-vue';

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

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

const emit = defineEmits(['success']);

const edit = useRequest(editUserMethod, { immediate: false }).onSuccess(() => {
  emit('success');
});

const formData = ref<SystemModel.User>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', [$t('system.user._')])
    : $t('ui.actionTitle.create', [$t('system.user._')]);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 135, // 单位 px，按实际文案长度调整
  },
  schema: useUserFormSchema('add'),
  showDefaultActions: false,
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues(formData.value || {});
}

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues();
      if (formData.value?.id && !data.password) {
        delete data.password;
      }
      try {
        await edit.send({ ...formData.value, ...data });
        await modalApi.close();
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<SystemModel.User>();
      if (data) {
        formApi.setState({
          schema: useUserFormSchema(data.id ? 'edit' : 'add'),
        });
        formData.value = data;
        formData.value.roles = data.roles?.map((role) =>
          typeof role === 'string' ? role : role.id,
        );
        formData.value.userType = data.userType === '01' ? '01' : '00';
        formApi.setValues(formData.value);
      }
    }
  },
});
</script>

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