import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_components__ from "@tachybase/components";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__ from "@tachybase/utils/client";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_antd_style__ from "antd-style";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__application_hoc_withDynamicSchemaProps_mjs__ from "../../../application/hoc/withDynamicSchemaProps.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__ from "../../../schema-settings/LinkageRules/type.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__ from "../../../variables/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__variables_utils_getPath_mjs__ from "../../../variables/utils/getPath.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__variables_utils_getVariableName_mjs__ from "../../../variables/utils/getVariableName.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__ from "../../../variables/utils/isVariable.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__common_utils_uitls_mjs__ from "../../common/utils/uitls.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_useProps_mjs__ from "../../hooks/useProps.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__utils_mjs__ from "./utils.mjs";
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, __WEBPACK_EXTERNAL_MODULE_antd_style__.createStyles)((param)=>{
    let { css } = param;
    return {
        container: css(_templateObject())
    };
});
const FormComponent = (props)=>{
    const { form, children, ...others } = props;
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const f = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useAttach)(form.createVoidField({
        ...field.props,
        basePath: ''
    }));
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.FieldContext.Provider, {
        value: void 0,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.FormContext.Provider, {
            value: form,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_components__.FormLayout, {
                layout: 'vertical',
                ...others,
                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const f = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useAttach)(form.createVoidField({
        ...field.props,
        basePath: ''
    }));
    const Component = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useComponent)(fieldSchema['x-component'], Def);
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.FieldContext.Provider, {
        value: void 0,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.FormContext.Provider, {
            value: form,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_components__.FormLayout, {
                layout: 'vertical',
                ...others,
                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.FieldContext.Provider, {
                    value: f,
                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(Component, {
                        ...field.componentProps,
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { setFormValueChanged } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useActionContext)();
    const variables = (0, __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__.useVariables)();
    const localVariables = (0, __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__.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, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const id = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.uid)();
        form.addEffects(id, ()=>{
            (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.onFormInputChange)(()=>{
                null == setFormValueChanged || setFormValueChanged(true);
            });
        });
        if (props.disabled) form.disabled = props.disabled;
        return ()=>{
            form.removeEffects(id);
        };
    }, [
        form,
        props.disabled,
        setFormValueChanged
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const id = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.getTempFieldState)(true, field.display),
                                required: (null === (_field_initStateOfLinkageRules1 = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules1 ? void 0 : _field_initStateOfLinkageRules1.required) || (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.getTempFieldState)(true, field.required || false),
                                pattern: (null === (_field_initStateOfLinkageRules2 = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules2 ? void 0 : _field_initStateOfLinkageRules2.pattern) || (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.getTempFieldState)(true, field.pattern),
                                value: (null === (_field_initStateOfLinkageRules3 = field.initStateOfLinkageRules) || void 0 === _field_initStateOfLinkageRules3 ? void 0 : _field_initStateOfLinkageRules3.value) || (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.getTempFieldState)(true, field.value || field.initialValue)
                            };
                            disposes.push((0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(FormDecorator, {
        ...props
    }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(FormComponent, {
        ...props
    });
};
const WithoutForm = (props)=>{
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { setFormValueChanged } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useActionContext)();
    const form = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>(0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.createForm)({
            disabled: props.disabled,
            effects () {
                (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.onFormInputChange)((form)=>{
                    null == setFormValueChanged || setFormValueChanged(true);
                });
            }
        }), []);
    return 'FormV2' === fieldSchema['x-decorator'] ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(FormDecorator, {
        form: form,
        ...props
    }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(FormComponent, {
        form: form,
        ...props
    });
};
const Form = (0, __WEBPACK_EXTERNAL_MODULE__application_hoc_withDynamicSchemaProps_mjs__.withDynamicSchemaProps)((0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const { styles } = useStyles();
    const { form, disabled, ...others } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_useProps_mjs__.useProps)(props);
    const formDisabled = disabled || field.disabled;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.ConfigProvider, {
        componentDisabled: formDisabled,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("form", {
            onSubmit: (e)=>e.preventDefault(),
            className: styles.container,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {
                spinning: field.loading || false,
                children: form ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(WithForm, {
                    form: form,
                    ...others,
                    disabled: formDisabled
                }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(WithoutForm, {
                    ...others,
                    disabled: formDisabled
                })
            })
        })
    });
}), {
    displayName: 'Form'
});
function getSubscriber(action, field, rule, variables, localVariables) {
    return ()=>{
        (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.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 __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.Required:
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.InRequired:
            return 'required';
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.Visible:
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.None:
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.Hidden:
            return 'display';
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.Editable:
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.ReadOnly:
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.ActionType.ReadPretty:
            return 'pattern';
        case __WEBPACK_EXTERNAL_MODULE__schema_settings_LinkageRules_type_mjs__.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, __WEBPACK_EXTERNAL_MODULE__common_utils_uitls_mjs__.getTargetField)(condition).join('.');
                return (0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.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, __WEBPACK_EXTERNAL_MODULE__common_utils_uitls_mjs__.getInnermostKeyAndValue)(condition);
            if (!jsonlogic) return null;
            if ((0, __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__.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(__WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__.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, __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__.isVariable)(variableString)) return;
    const variableName = (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_getVariableName_mjs__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.getValuesByPath)(ctx, (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_getPath_mjs__.getPath)(variableString));
}
export { Form };
