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

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

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

import { useVbenForm } from '#/adapter/form';

import {
  createStoreMembershipLevelApi,
  updateStoreMembershipLevelApi,
} from '../api';
import { modalFormProps } from '../config/form';

defineOptions({
  name: 'StoreMembershipLevelDemo',
});

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value
          ? updateStoreMembershipLevelApi
          : createStoreMembershipLevelApi;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values) {
        isUpdate.value = update;
        formApi.setValues(values);
      }
    }
  },
});
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}店铺会员等级`"
    class="w-[30%]"
  >
    <Form />
  </Modal>
</template>
