<script lang="ts" setup>
import { computed, ref, unref } from 'vue';

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

import { useFormOptions, useVbenForm } from '#/adapter';
import { TenantApi } from '#/api';

import { useSchema } from '../data.config';

defineOptions({
  name: 'TenantEdit',
});
const emit = defineEmits(['success']);
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);

const [Form, { validate, setValues, getValues }] = useVbenForm(
  useFormOptions({
    schema: useSchema(),
    wrapperClass: 'grid-cols-2',
  }),
);

const [Modal, { close, setState, getData, lock, unlock }] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  closeOnClickModal: false,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await validate();
      if (!valid) return;
      const values = await getValues();
      lock();
      const postParams = unref(modelRef);
      Object.assign(postParams, values);
      await (unref(isUpdate)
        ? TenantApi.editDetail(postParams as TenantApi.RecordItem)
        : TenantApi.addDetail(postParams as TenantApi.BasicRecordItem));
      alert('操作成功');

      emit('success');
      close();
    } finally {
      unlock();
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };

      if (unref(isUpdate)) {
        const entity = await TenantApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };
        setValues(entity);
      }
      setState({ loading: false });
    }
  },
});

const getTitle = computed(() => (unref(isUpdate) ? '编辑租户' : '新增租户'));
</script>
<template>
  <Modal class="w-[1000px]" :title="getTitle">
    <Form />
  </Modal>
</template>
