/**
 * @since Last modified: 2024/05/19 16:06:13
 * @function ajaxSubmit
 * @description Get data in synchronization or asynchronous manner.
 * @param {object} content  - Insert content with multiple format.
 * @param {getEl} elem - The host node of content.
 * @param {'override' | 'afterbegin' | 'beforeend'} [position='override'] - Position of inserting content.
 * @returns null.
 * @see {@link https://codepen.io/axui/pen/poGqNYp|demo @ codepen}
 * @example
 * ax.ajaxSubmit('I love you');
 * <!--return null-->
 */
'use strict';
import ax from '../ax';
import Message from '../modules/Message';
import ajax from './ajax';
import getEl from './getEl';
import serialize from './serialize';
const ajaxSubmit = ({ url = '', parent, target, type = 'post', delay = 1000, buffer = '', success, before, error, opened, }) => {
    if (!url || !parent) {
        throw new Error('The request url and form node are required!');
    }
    let parentDom = getEl(parent), targetEl = getEl(target), targetText = targetEl ? targetEl.innerHTML : '', resume = () => {
        parentDom.classList.remove(`${ax.pfx}ajax-overlay`);
        if (targetEl) {
            if (buffer === 'loading' || buffer === 'text') {
                targetEl.removeAttribute('inert');
                targetEl.innerHTML = targetText;
            }
            else {
                targetEl.removeAttribute('cheking');
            }
        }
    };
    if (parentDom.classList.contains(`${ax.pfx}ajax-overlay`)) {
        return false;
    }
    return ajax({
        url,
        data: serialize(parentDom, 'formdata'),
        type,
        opened: (response) => {
            opened && opened(response);
        },
        before: (response) => {
            parentDom.classList.add(`${ax.pfx}ajax-overlay`);
            if (targetEl) {
                if (buffer === 'loading') {
                    targetEl.innerHTML = response.content;
                    targetEl.setAttribute('inert', '');
                }
                else if (buffer === 'text') {
                    targetEl.innerHTML = ax.lang.ajax.submit.btn;
                    targetEl.setAttribute('inert', '');
                }
                else {
                    targetEl.setAttribute('checking', '');
                }
            }
            before && before(response);
        },
        success: (response) => {
            setTimeout(() => {
                resume();
                new Message({
                    content: ax.lang.ajax.submit.succ,
                    result: 'succ',
                    iconShow: true,
                });
                success && success(response);
            }, delay);
        },
        error: (response) => {
            resume();
            new Message({
                content: ax.lang.ajax.submit.fail,
                result: 'error',
                iconShow: true,
            });
            error && error(response);
        }
    });
};
export default ajaxSubmit;
