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

import { computed } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';
import {
  createCustomer,
  getCustomer,
  getMaxSn,
  updateCustomer,
} from '#/api/license/customer';
import { $t } from '#/locales';

import { formData, useFormSchema } from '../data';

const emit = defineEmits(['success']);
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', [$t('customer.customer')])
    : $t('ui.actionTitle.create', [$t('customer.customer')]);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    // formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
  // 大屏一行显示3个，中屏一行显示2个，小屏一行显示1个
  wrapperClass: 'grid-cols-1 md:grid-cols-2',
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const values = await formApi.getValues();
    const data = {
      ...values,
      areaId: values?.areaIds[values?.areaIds.length - 1],
    } as CustomerApi.Customer;
    try {
      await (formData.value?.id ? updateCustomer(data) : createCustomer(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    let data = modalApi.getData<CustomerApi.Customer>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.setState({ loading: true });
      data = await getCustomer(data.id);
    }

    // 设置到 values
    formData.value = data;
    await formApi.setValues(formData.value);

    // 设置最大SN
    const maxSn = await getMaxSn();
    if (!formData.value?.code) {
      formApi.setFieldValue('code', maxSn);
    }

    modalApi.setState({ loading: false });
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-1/2">
    <Form class="mx-4" />
  </Modal>
</template>
