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

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

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

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

import { createServicePack, updateServicePack } from '../api';
import { modalFormProps } from '../config/form';


const userStore = useUserStore();

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
          ? updateServicePack
          : createServicePack;
        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);
        if (userStore?.userInfo?.roles?.user_type === 3 && !isUpdate.value) {
          formApi.setValues({
            supplier_id: userStore?.userInfo?.supplier_id,
          });
        }
      }
    }
  },
});
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}产品服务包`"
    class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]"
  >
    <Form />
  </Modal>
</template>
