/**
 * @since Last modified: 2024-01-19 13:04:00
 * @function validFactory
 * @description The verification factory passes in the verification value and verification rules and returns the verification results.
 * @param {object} data - Data participating in verification.Format is:{value:100,label:'',name:'',ins:'',rules:{'rule01':()=>{},'rule02':()=>{}...},text:{succ:'',fail：''}}
 * @param {string} data.value - The value to be verified.
 * @param {object} data.rules - The rules to be verified.
 * @param {object} [data.text] - The default text.
 * @param {string} [data.text.succ] - The default text of success.
 * @param {string} [data.text.fail] - The default text of failure.
 * @returns  {promise} - A promise,the parameter of resolve is {passed,success,error}.
 * @see {@link https://codepen.io/axui/pen/vYPYyzN|demo @ codepen}
 * @example
 * ax.validFactory({value:100,rules:{'compare':function(){return {passed:this<200}}}});
 * "this" in handler is "{value,name,label,ins}".
 * <!--Return {passed:true,succ:'...',fail:'...'}-->
 */
'use strict';
import ax from "../ax";
import Message from "../modules/Message";
import getDataType from "./getDataType";
import renderTpl from "./renderTpl";
const validFactory = async (data) => {
    let textSucc = data?.text?.succ || ax.lang.valid.succ, textFail = data?.text?.fail || ax.lang.valid.fail, result = { passed: true, succ: renderTpl(textSucc, { label: data.label, name: data.name }), fail: renderTpl(textFail, { label: data.label, name: data.name }) };
    if (data.rules.length === 0) {
        return result;
    }
    try {
        for (let k in data.rules) {
            if (data.rules.hasOwnProperty(k)) {
                let item = data.rules[k], param = { value: data.value, name: data.name, label: data.label, ins: data.ins }, output = await item(param), dataType = getDataType(output);
                if (dataType === 'Object') {
                    if (output?.content?.hasOwnProperty('passed')) {
                        Object.assign(result, output.content);
                    }
                    else {
                        Object.assign(result, output);
                    }
                    if (!result.passed) {
                        break;
                    }
                    ;
                }
            }
        }
    }
    catch (err) {
        result.passed = false;
        new Message({
            result: 'error',
            content: ax.lang.valid.message.wrongRule,
        }).show();
        console.error(err);
    }
    data.cb && data.cb(result);
    return result;
};
export default validFactory;
