"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    Form: ()=>Form
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const components_namespaceObject = require("@tachybase/components");
const schema_namespaceObject = require("@tachybase/schema");
const client_namespaceObject = require("@tachybase/utils/client");
const external_antd_namespaceObject = require("antd");
const external_antd_style_namespaceObject = require("antd-style");
const external_index_js_namespaceObject = require("../index.js");
const external_index_js_namespaceObject_1 = require("../../index.js");
const withDynamicSchemaProps_js_namespaceObject = require("../../../application/hoc/withDynamicSchemaProps.js");
const type_js_namespaceObject = require("../../../schema-settings/LinkageRules/type.js");
const index_js_namespaceObject = require("../../../variables/index.js");
const getPath_js_namespaceObject = require("../../../variables/utils/getPath.js");
const getVariableName_js_namespaceObject = require("../../../variables/utils/getVariableName.js");
const isVariable_js_namespaceObject = require("../../../variables/utils/isVariable.js");
const uitls_js_namespaceObject = require("../../common/utils/uitls.js");
const useProps_js_namespaceObject = require("../../hooks/useProps.js");
const external_utils_js_namespaceObject = require("./utils.js");
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n      .ant-formily-item-feedback-layout-loose {\n        margin-bottom: 12px;\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
const useStyles = (0, external_antd_style_namespaceObject.createStyles)((param)=>{
    let { css } = param;
    return {
        container: css(_templateObject())
    };
});
const FormComponent = (props)=>{
    const { form, children, ...others } = props;
    const field = (0, schema_namespaceObject.useField)();
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const f = (0, external_index_js_namespaceObject_1.useAttach)(form.createVoidField({
        ...field.props,
        basePath: ''
    }));
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.FieldContext.Provider, {
        value: void 0,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.FormContext.Provider, {
            value: form,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(components_namespaceObject.FormLayout, {
                layout: 'vertical',
                ...others,
                children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.RecursionField, {
                    basePath: f.address,
                    schema: fieldSchema,
                    onlyRenderProperties: true
                })
            })
        })
    });
};
const Def = (props)=>props.children;
const FormDecorator = (props)=>{
    const { form, children, disabled, ...others } = props;
    const field = (0, schema_namespaceObject.useField)();
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const f = (0, external_index_js_namespaceObject_1.useAttach)(form.createVoidField({
        ...field.props,
        basePath: ''
    }));
    const Component = (0, external_index_js_namespaceObject_1.useComponent)(fieldSchema['x-component'], Def);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.FieldContext.Provider, {
        value: void 0,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.FormContext.Provider, {
            value: form,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(components_namespaceObject.FormLayout, {
                layout: 'vertical',
                ...others,
                children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.FieldContext.Provider, {
                    value: f,
                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(Component, {
                        ...field.componentProps,
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.RecursionField, {
                            basePath: f.address,
                            schema: fieldSchema,
                            onlyRenderProperties: true
                        })
                    })
                })
            })
        })
    });
};
const getLinkageRules = (fieldSchema)=>{
    let linkageRules = null;
    fieldSchema.mapProperties((schema)=>{
        if (schema['x-linkage-rules']) linkageRules = schema['x-linkage-rules'];
    });
    return linkageRules;
};
const WithForm = (props)=>{
    var _this, _fieldSchema_parent;
    const { form } = props;
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const { setFormValueChanged } = (0, external_index_js_namespaceObject.useActionContext)();
    const variables = (0, index_js_namespaceObject.useVariables)();
    const localVariables = (0, index_js_namespaceObject.useLocalVariables)({
        currentForm: form
    });
    const linkageRules = (null === (_this = getLinkageRules(fieldSchema) || (null === (_fieldSchema_parent = fieldSchema.parent) || void 0 === _fieldSchema_parent ? void 0 : _fieldSchema_parent['x-linkage-rules'])) || void 0 === _this ? void 0 : _this.filter((k)=>!k.disabled)) || [];
    (0, external_react_namespaceObject.useEffect)(()=>{
        const id = (0, schema_namespaceObject.uid)();
        form.addEffects(id, ()=>{
            (0, schema_namespaceObject.onFormInputChange)(()=>{
                null == setFormValueChanged || setFormValueChanged(true);
            });
        });
        if (props.disabled) form.disabled = props.disabled;
        return ()=>{
            form.removeEffects(id);
        };
    }, [
        form,
        props.disabled,
        setFormValueChanged
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        const id = (0, schema_namespaceObject.uid)();
        const disposes = [];
        form.addEffects(id, ()=>{
            linkageRules.forEach((rule)=>{
                var _rule_actions;
                null === (_rule_actions = rule.actions) || void 0 === _rule_actions || _rule_actions.forEach((action)=>{
                    var _action_targetFields;
                    if (null === (_action_targetFields = action.targetFields) || void 0 === _action_targetFields ? void 0 : _action_targetFields.length) {
                        const fields = action.targetFields.join(',');
                        (0, schema_namespaceObject.onFieldInit)("*(".concat(fields, ")"), (field, form)=>{
                            var _field_initStateOfLinkageRules, _field_initStateOfLinkageRules1, _field_initStateOfLinkageRules2, _field_initStateOfLinkageRules3;
                            field['initStateOfLinkageRules'] = {
                                display: (null === (_field_initStateOfLinkageRules = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules ? void 0 : _field_initStateOfLinkageRules.display) || (0, external_utils_js_namespaceObject.getTempFieldState)(true, field.display),
                                required: (null === (_field_initStateOfLinkageRules1 = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules1 ? void 0 : _field_initStateOfLinkageRules1.required) || (0, external_utils_js_namespaceObject.getTempFieldState)(true, field.required || false),
                                pattern: (null === (_field_initStateOfLinkageRules2 = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules2 ? void 0 : _field_initStateOfLinkageRules2.pattern) || (0, external_utils_js_namespaceObject.getTempFieldState)(true, field.pattern),
                                value: (null === (_field_initStateOfLinkageRules3 = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules3 ? void 0 : _field_initStateOfLinkageRules3.value) || (0, external_utils_js_namespaceObject.getTempFieldState)(true, field.value || field.initialValue)
                            };
                            disposes.push((0, schema_namespaceObject.reaction)(()=>{
                                const fieldValuesInCondition = getFieldValuesInCondition({
                                    linkageRules,
                                    formValues: form.values
                                });
                                const variableValuesInCondition = getVariableValuesInCondition({
                                    linkageRules,
                                    localVariables
                                });
                                const variableValuesInExpression = getVariableValuesInExpression({
                                    action,
                                    localVariables
                                });
                                const result = [
                                    fieldValuesInCondition,
                                    variableValuesInCondition,
                                    variableValuesInExpression
                                ].map((item)=>JSON.stringify(item)).join(',');
                                return result;
                            }, getSubscriber(action, field, rule, variables, localVariables), {
                                fireImmediately: true
                            }));
                        });
                    }
                });
            });
        });
        return ()=>{
            form.removeEffects(id);
            disposes.forEach((dispose)=>{
                dispose();
            });
        };
    }, [
        linkageRules
    ]);
    return 'FormV2' === fieldSchema['x-decorator'] ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(FormDecorator, {
        ...props
    }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(FormComponent, {
        ...props
    });
};
const WithoutForm = (props)=>{
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const { setFormValueChanged } = (0, external_index_js_namespaceObject.useActionContext)();
    const form = (0, external_react_namespaceObject.useMemo)(()=>(0, schema_namespaceObject.createForm)({
            disabled: props.disabled,
            effects () {
                (0, schema_namespaceObject.onFormInputChange)((form)=>{
                    null == setFormValueChanged || setFormValueChanged(true);
                });
            }
        }), []);
    return 'FormV2' === fieldSchema['x-decorator'] ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(FormDecorator, {
        form: form,
        ...props
    }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(FormComponent, {
        form: form,
        ...props
    });
};
const Form = (0, withDynamicSchemaProps_js_namespaceObject.withDynamicSchemaProps)((0, schema_namespaceObject.observer)((props)=>{
    const field = (0, schema_namespaceObject.useField)();
    const { styles } = useStyles();
    const { form, disabled, ...others } = (0, useProps_js_namespaceObject.useProps)(props);
    const formDisabled = disabled || field.disabled;
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.ConfigProvider, {
        componentDisabled: formDisabled,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("form", {
            onSubmit: (e)=>e.preventDefault(),
            className: styles.container,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Spin, {
                spinning: field.loading || false,
                children: form ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(WithForm, {
                    form: form,
                    ...others,
                    disabled: formDisabled
                }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(WithoutForm, {
                    ...others,
                    disabled: formDisabled
                })
            })
        })
    });
}), {
    displayName: 'Form'
});
function getSubscriber(action, field, rule, variables, localVariables) {
    return ()=>{
        (0, external_utils_js_namespaceObject.collectFieldStateOfLinkageRules)({
            operator: action.operator,
            value: action.value,
            field,
            condition: rule.condition,
            variables,
            localVariables
        });
        setTimeout(async ()=>{
            var _field_stateOfLinkageRules;
            const fieldName = getFieldNameByOperator(action.operator);
            if (!(null === (_field_stateOfLinkageRules = field.stateOfLinkageRules) || void 0 === _field_stateOfLinkageRules ? void 0 : _field_stateOfLinkageRules[fieldName])) return;
            let stateList = field.stateOfLinkageRules[fieldName];
            stateList = await Promise.all(stateList);
            stateList = stateList.filter((v)=>v.condition);
            const lastState = stateList[stateList.length - 1];
            if ('value' === fieldName) {
                if (stateList.length > 1) field.value = lastState.value;
            } else {
                field[fieldName] = null == lastState ? void 0 : lastState.value;
                if ('display' === fieldName && (null == lastState ? void 0 : lastState.value) === 'none') field.value = void 0;
            }
            field.stateOfLinkageRules[fieldName] = null;
        });
    };
}
function getFieldNameByOperator(operator) {
    switch(operator){
        case type_js_namespaceObject.ActionType.Required:
        case type_js_namespaceObject.ActionType.InRequired:
            return 'required';
        case type_js_namespaceObject.ActionType.Visible:
        case type_js_namespaceObject.ActionType.None:
        case type_js_namespaceObject.ActionType.Hidden:
            return 'display';
        case type_js_namespaceObject.ActionType.Editable:
        case type_js_namespaceObject.ActionType.ReadOnly:
        case type_js_namespaceObject.ActionType.ReadPretty:
            return 'pattern';
        case type_js_namespaceObject.ActionType.Value:
            return 'value';
        default:
            return null;
    }
}
function getFieldValuesInCondition(param) {
    let { linkageRules, formValues } = param;
    return linkageRules.map((rule)=>{
        const run = (condition)=>{
            const type = Object.keys(condition)[0] || '$and';
            const conditions = condition[type];
            return conditions.map((condition)=>{
                if ('$and' in condition || '$or' in condition) return run(condition);
                const path = (0, uitls_js_namespaceObject.getTargetField)(condition).join('.');
                return (0, client_namespaceObject.getValuesByPath)(formValues, path);
            }).filter(Boolean);
        };
        return run(rule.condition);
    });
}
function getVariableValuesInCondition(param) {
    let { linkageRules, localVariables } = param;
    return linkageRules.map((rule)=>{
        const type = Object.keys(rule.condition)[0] || '$and';
        const conditions = rule.condition[type];
        return conditions.map((condition)=>{
            const jsonlogic = (0, uitls_js_namespaceObject.getInnermostKeyAndValue)(condition);
            if (!jsonlogic) return null;
            if ((0, isVariable_js_namespaceObject.isVariable)(jsonlogic.value)) return getVariableValue(jsonlogic.value, localVariables);
            return jsonlogic.value;
        }).filter(Boolean);
    });
}
function getVariableValuesInExpression(param) {
    let { action, localVariables } = param;
    var _value_match;
    const actionValue = action.value;
    const mode = null == actionValue ? void 0 : actionValue.mode;
    const value = (null == actionValue ? void 0 : actionValue.value) || (null == actionValue ? void 0 : actionValue.result);
    if ('express' !== mode) return;
    if (null == value) return;
    return null === (_value_match = value.match(isVariable_js_namespaceObject.REGEX_OF_VARIABLE)) || void 0 === _value_match ? void 0 : _value_match.map((variableString)=>getVariableValue(variableString, localVariables)).filter(Boolean);
}
function getVariableValue(variableString, localVariables) {
    var _localVariables_find;
    if (!(0, isVariable_js_namespaceObject.isVariable)(variableString)) return;
    const variableName = (0, getVariableName_js_namespaceObject.getVariableName)(variableString);
    const ctx = {
        [variableName]: null === (_localVariables_find = localVariables.find((item)=>item.name === variableName)) || void 0 === _localVariables_find ? void 0 : _localVariables_find.ctx
    };
    return (0, client_namespaceObject.getValuesByPath)(ctx, (0, getPath_js_namespaceObject.getPath)(variableString));
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
