import { getCurrentInstance, nextTick, ref, unref, watch } from 'vue';
import { tryOnUnmounted } from '@vueuse/core';
import type { ModalFromMethods, UseModalFormReturnType, modalFormProps } from '../type';
import type { modalProps } from '../../Modal/types';
import type { FormActionType, FormProps, FormSchema } from '../../Form/types/form';
export function useModalFrom(props: modalFormProps): UseModalFormReturnType {
  const modalRef = ref<Nullable<ModalFromMethods>>(null);
  const formRef = ref<Nullable<FormActionType>>(null);
  const currentInstance = getCurrentInstance();

  const getModalInstance = () => {
    const instance = unref(modalRef.value);
    if (!instance) {
      console.error('useModal instance is undefined!');
    }
    return instance;
  };

  async function getForm() {
    const form = unref(formRef);
    if (!form) {
      console.error(
        'The form instance has not been obtained, please make sure that the form has been rendered when performing the form operation!'
      );
    }
    await nextTick();
    return form as FormActionType;
  }

  const register = (modalInstance: ModalFromMethods) => {
    tryOnUnmounted(() => {
      modalRef.value = null;
      formRef.value = null;
    });
    modalRef.value = modalInstance;
    currentInstance?.emit('registerModalForm', modalInstance);
    formRef.value = modalInstance;

    watch(
      () => props,
      () => {
        if (props) {
          modalInstance.setModalProps(props.modalConfig);
          // modalInstance.setFormProps(props.formConfig);
        }
      },
      {
        immediate: true,
        deep: true
      }
    );
  };

  const methods: ModalFromMethods = {
    // 表单相关方法
    updateSchema: async (formSchema: Partial<FormSchema> | Partial<FormSchema>[]) => {
      const form = await getForm();
      nextTick(async () => {
        await form.updateSchema(formSchema);
      });
    },
    setFormProps: async (newProps: Partial<FormProps>): Promise<void> => {
      const form = await getForm();
      await form?.setFormProps(newProps);
    },
    submit: async (): Promise<any> => {
      const form = await getForm();
      return await form?.submit();
    },
    setSchema: async schema => {
      const form = await getForm();
      await form?.setSchema(schema);
    },
    setFieldsValue: async values => {
      const form = await getForm();
      form?.setFieldsValue(values);
    },
    clearValidate: async () => {
      const form = await getForm();
      await form?.clearValidate();
    },
    validate: async () => {
      const form = await getForm();
      return await form?.validate();
    },
    resetFields: async () => {
      const form = await getForm();
      form?.resetFields();
    },
    getFieldsValue: async () => {
      const form = await getForm();
      return form?.getFieldsValue();
    },
    setLoading: async status => {
      const form = await getForm();
      form?.setLoading(status);
    },
    restoreValidation: async () => {
      const form = await getForm();
      form?.restoreValidation();
    },

    // 模态框相关方法
    setModalLoading: async status => {
      // console.log(status, 'setModalLoading', getModalInstance());

      getModalInstance()?.setModalLoading(status);
    },
    setModalProps: (newProps: modalProps): void => {
      getModalInstance()?.setModalProps(newProps);
    },
    openModal: (record?: Recordable, isView?: boolean) => {
      getModalInstance()?.openModal(record);
      if (record && !isView && props.modalConfig.isShowHeaderText) {
        getModalInstance()?.setModalProps({ title: `编辑${props.modalConfig.title}` });
      }
      if (!record && !isView && props.modalConfig.isShowHeaderText) {
        getModalInstance()?.setModalProps({ title: `新增${props.modalConfig.title}` });
      }
      if (record && isView && props.modalConfig.isShowHeaderText) {
        getModalInstance()?.setModalProps({ title: `查看${props.modalConfig.title}` });
      }
      nextTick(() => {
        getModalInstance()?.setFormProps(props.formConfig);
        getModalInstance()?.resetFields();
      });
    },
    closeModal: () => {
      getModalInstance()?.closeModal();
    },
    setSubLoading: (status: boolean) => {
      getModalInstance()?.setSubLoading(status);
    }
  };

  return [register, methods];
}
