<script lang="ts">
import { computed, defineComponent, onMounted, ref, unref } from 'vue';
import { useModal } from '../Modal/hooks/useModal';
import { useForm } from '../Form/hooks/useForm';
import type { modalProps } from '../Modal/types';
import type { FormProps } from '../Form/types/form';
import type { ModalFromMethods } from './type';

export default defineComponent({
  name: 'ModalForm',
  emits: ['registerModalForm', 'submitForm'],
  setup(props, { emit }) {
    const modelPropsRef = ref<Partial<modalProps>>();
    const formPropsRef = ref<Partial<FormProps>>();
    console.log(props, 'registerModalForm');

    const formComputRef = computed(() => {
      return {
        labelWidth: 180,
        layout: 'horizontal',
        gridProps: {
          cols: '1 xl:4 s:1 l:3',
          itemResponsive: true
        },
        collapsedRows: 1,
        showActionButtonGroup: false,
        ...unref(formPropsRef)
      };
    });
    const modalComputRef = computed(() => {
      return {
        ...unref(modelPropsRef)
      };
    });
    const [registerModal, { openModal, closeModal, setSubLoading, setModalProps, setModalLoading }] = useModal(
      unref(modalComputRef)
    );
    const [
      registerForm,
      {
        validate,
        restoreValidation,
        setFieldsValue,
        resetFields,
        setLoading,
        setSchema,
        submit,
        clearValidate,
        getFieldsValue,
        setFormProps,
        updateSchema
      }
    ] = useForm(formComputRef.value);
    const methods: ModalFromMethods = {
      setModalProps,
      openModal,
      closeModal,
      setFieldsValue,
      resetFields,
      setFormProps,
      setLoading,
      setSchema,
      submit,
      validate,
      clearValidate,
      getFieldsValue,
      restoreValidation,
      setSubLoading,
      updateSchema,
      setModalLoading
    };

    onMounted(() => {
      emit('registerModalForm', methods);
    });
    async function handleSubmitForm() {
      setSubLoading(false);
      await validate();
      setSubLoading(true);
      emit('submitForm');
    }
    return {
      registerModal,
      registerForm,
      handleSubmitForm
    };
  }
});
</script>

<template>
  <BasicModal @register-modal="registerModal" @ok="handleSubmitForm">
    <BasicForm @register-form="registerForm"></BasicForm>
  </BasicModal>
</template>

<style scoped></style>
