/**
 * @since Last modified: 2024/03/04 15:57:45
 * @namespace field
 * @description Operations on multi-value form fields, such as select-multiple, file-multiple, checkbox, radio types.
 * @see {@link https://codepen.io/axui/pen/jOJbJMy|demo @ codepen}
 */
'use strict';
import clampVal from './clampVal';
import getEl from './getEl';
import isEmpty from './isEmpty';
const field = {
    /**
 * @memberOf field
 * @description Get field data of form fields, including multi-valued form fields and sigle-valued form fields.
 * @param {object} obj  - Parameters.
 * @param {getEl} obj.el  - Dom selector of input.
 * @param {""|"string"|"array"} [obj.format=""]  - Output value type.
 * @param {getEl} [obj.parent=el.closest('form')]  - The parent Dom of input.If el itself is not a form field, you need to use this parameter to specify the parent node of the form field.
 * @param {string} [obj.separator=","]  - The separator character of Output value.if format=false,can use the parameter.
 * @returns {array|string} Return a value array of value string.
 * @see {@link https://codepen.io/axui/pen/jOJbJMy|demo @ codepen}
 * @example
 * ax.field.getVals({el:'select'});
 * <!--return ['BJ','SH','TJ']-->
 */
    getVals: ({ el, format = '', parent, separator = ',' }) => {
        let fieldDom = getEl(el), values = [], none = format === 'array' ? [] : format === 'string' ? '' : null, result;
        try {
            if (fieldDom) {
                let fieldType = fieldDom.type, parentDom = getEl(parent) || fieldDom.closest('form') || document.body;
                if (fieldType.includes('select')) {
                    let options = [...fieldDom.options];
                    options.forEach((k) => {
                        k.selected && k.getAttribute('value') ? values.push(k.value) : null;
                    });
                }
                else if (fieldType === 'checkbox' || fieldType === 'radio') {
                    let fields = [...parentDom.querySelectorAll(`[name="${fieldDom.name}"]`)];
                    fields.forEach((k) => {
                        k.checked && k.getAttribute('value') ? values.push(k.value) : null;
                    });
                }
                else if (fieldType === 'file') {
                    values = [...fieldDom.files];
                }
                else {
                    values = fieldDom.value ? [fieldDom.value] : [];
                }
                if (format === 'string') {
                    result = (fieldType === 'file') ? values.map((k) => k.name.trim()).join(separator) : values.join(separator);
                }
                else if (format === 'array') {
                    result = values;
                }
                else {
                    result = ['select-multiple', 'checkbox', 'file'].includes(fieldType) ? values : (values[0] || '');
                }
                return result;
            }
        }
        catch (e) {
            return none;
        }
    },
    /**
    * @memberOf field
    * @description Set the values of select, checkbox and radio. File cannot be set (it is read-only).
    * @param {object} obj  - Parameters.
    * @param {getEl} obj.el  - Dom selector of field.
    * @param {string | number | string[] | number[]} [obj.val]  - The data for setting.
    * @param {getEl} [obj.parent=closet('form')]  - The parent Dom of input.If el itself is not a form field, you need to use this parameter to specify the parent node of the form field.
     * @param {function} [obj.cb]  - The call back after set values.Parameters is fields and values.
    * @returns {null} - Return null.
    * @see {@link https://codepen.io/axui/pen/jOJbJMy|demo @ codepen}
    * @example
    * ax.field.setVals({'#demo',val:['read','travel']});
    * <!--return null-->
    */
    setVals: ({ el, val, parent, cb }) => {
        let fieldDom = getEl(el), fieldType = fieldDom?.type, values = isEmpty(val) ? [] : (!Array.isArray(val) ? [val] : val), parentDom = getEl(parent) || fieldDom?.closest('form') || document.body, fields = [];
        if (fieldDom) {
            if (fieldType.includes('select')) {
                let options = [...fieldDom.options].filter((k) => k.getAttribute('value')), tmp = values.map((k) => k.toString());
                options.forEach((k) => {
                    k.selected = tmp.includes(k.value) ? true : false;
                });
                fields = [fieldDom];
            }
            else if (fieldType === 'checkbox' || fieldType === 'radio') {
                fields = [...parentDom.querySelectorAll(`[name="${fieldDom.name}"]`)].filter((k) => k.getAttribute('value'));
                let tmp = values.map((k) => k.toString());
                fields.forEach((k) => {
                    k.checked = tmp.includes(k.value) ? true : false;
                });
            }
            else if (fieldType === 'file') {
                fieldDom.value = '';
                console.warn('The field.files property cannot be changed through scripts,this operation is performed by resetting!');
            }
            else if (fieldType === 'number') {
                fieldDom.value = clampVal({
                    val: values[0] || 0,
                    min: fieldDom.min,
                    max: fieldDom.max
                });
            }
            else if (fieldType === 'range') {
                fieldDom.value = values[0] || fieldDom.min || 0;
            }
            else {
                fieldDom.value = values[0] || '';
            }
            cb && cb();
        }
    },
    /**
    * @memberOf field
    * @description Multi-valued fields reset to zero.
    * @param {getEl} obj.el  - Dom selector of field.
    * @param {boolean} [obj.zero=false]  - Whether to return to zero directly.
    * @param {getEl} [obj.parent=closet('form')]  - The parent Dom of input.If el itself is not a form field, you need to use this parameter to specify the parent node of the form field.
    * @returns {null} - Return null.
    * @see {@link https://codepen.io/axui/pen/jOJbJMy|demo @ codepen}
    * @example
    * ax.field.reset({el:'#demo'});
    * <!--return null-->
    */
    reset: ({ el, parent, zero = false }) => {
        let fieldDom = getEl(el), type = fieldDom?.type;
        if (type) {
            if (type?.includes('select')) {
                [...fieldDom.options].forEach((i) => i.selected = !zero ? i.defaultSelected : false);
            }
            else if (type === 'checkbox' || type === 'radio') {
                let parentDom = getEl(parent) || fieldDom?.closest('form') || document.body, fields = [...parentDom.querySelectorAll(`[name="${fieldDom.name}"]`)];
                fields.forEach((k) => {
                    k.checked = !zero ? k.defaultChecked : false;
                });
            }
            else if (['number', 'range'].includes(type)) {
                fieldDom.value = !zero ? fieldDom.defaultValue : (fieldDom.min || 0);
            }
            else {
                fieldDom.value = !zero ? fieldDom.defaultValue : '';
            }
        }
    }
};
export default field;
