<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 {
  createDoctorInput,
  getDoctorInputDetail,
  updateDoctorInput,
} from '../api';
import { modalFormProps } from '../config/form';

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 ? updateDoctorInput : createDoctorInput;
        submitApi(values)
          .then(() => {
            message.success(isUpdate.value ? '更新成功' : '预填成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values?.id) {
        isUpdate.value = update;
        if (update) {
          const detail = await getDoctorInputDetail(values.id);
          formApi.setValues({
            ...detail,
            stores: detail.store_ids || [],
          });
        } else {
          formApi.setValues({
            ...values,
            stores: values.store_ids || [],
          });
        }
      } else {
        isUpdate.value = false;
        formApi.resetForm();
      }
    }
  },
});
</script>

<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}医生预填`" class="w-[60%]">
    <Form />
  </Modal>
</template>
