import { jsx } from "react/jsx-runtime";
import { useEffect, useMemo } from "react";
import { FormLayout } from "@tachybase/components";
import { FieldContext, FormContext, RecursionField, createForm, observer, onFieldInit, onFormInputChange, reaction, uid, useField, useFieldSchema } from "@tachybase/schema";
import { getValuesByPath } from "@tachybase/utils/client";
import { ConfigProvider, Spin } from "antd";
import { createStyles } from "antd-style";
import { useActionContext } from "../index.mjs";
import { useAttach, useComponent } from "../../index.mjs";
import { withDynamicSchemaProps } from "../../../application/hoc/withDynamicSchemaProps.mjs";
import { ActionType } from "../../../schema-settings/LinkageRules/type.mjs";
import { useLocalVariables, useVariables } from "../../../variables/index.mjs";
import { getPath } from "../../../variables/utils/getPath.mjs";
import { getVariableName } from "../../../variables/utils/getVariableName.mjs";
import { REGEX_OF_VARIABLE, isVariable } from "../../../variables/utils/isVariable.mjs";
import { getInnermostKeyAndValue, getTargetField } from "../../common/utils/uitls.mjs";
import { useProps } from "../../hooks/useProps.mjs";
import { collectFieldStateOfLinkageRules, getTempFieldState } 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 = createStyles((param)=>{
    let { css } = param;
    return {
        container: css(_templateObject())
    };
});
const FormComponent = (props)=>{
    const { form, children, ...others } = props;
    const field = useField();
    const fieldSchema = useFieldSchema();
    const f = useAttach(form.createVoidField({
        ...field.props,
        basePath: ''
    }));
    return /*#__PURE__*/ jsx(FieldContext.Provider, {
        value: void 0,
        children: /*#__PURE__*/ jsx(FormContext.Provider, {
            value: form,
            children: /*#__PURE__*/ jsx(FormLayout, {
                layout: 'vertical',
                ...others,
                children: /*#__PURE__*/ jsx(RecursionField, {
                    basePath: f.address,
                    schema: fieldSchema,
                    onlyRenderProperties: true
                })
            })
        })
    });
};
const Def = (props)=>props.children;
const FormDecorator = (props)=>{
    const { form, children, disabled, ...others } = props;
    const field = useField();
    const fieldSchema = useFieldSchema();
    const f = useAttach(form.createVoidField({
        ...field.props,
        basePath: ''
    }));
    const Component = useComponent(fieldSchema['x-component'], Def);
    return /*#__PURE__*/ jsx(FieldContext.Provider, {
        value: void 0,
        children: /*#__PURE__*/ jsx(FormContext.Provider, {
            value: form,
            children: /*#__PURE__*/ jsx(FormLayout, {
                layout: 'vertical',
                ...others,
                children: /*#__PURE__*/ jsx(FieldContext.Provider, {
                    value: f,
                    children: /*#__PURE__*/ jsx(Component, {
                        ...field.componentProps,
                        children: /*#__PURE__*/ jsx(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 = useFieldSchema();
    const { setFormValueChanged } = useActionContext();
    const variables = useVariables();
    const localVariables = useLocalVariables({
        currentForm: form
    });
    const linkageRules = (null == (_this = getLinkageRules(fieldSchema) || (null == (_fieldSchema_parent = fieldSchema.parent) ? void 0 : _fieldSchema_parent['x-linkage-rules'])) ? void 0 : _this.filter((k)=>!k.disabled)) || [];
    useEffect(()=>{
        const id = uid();
        form.addEffects(id, ()=>{
            onFormInputChange(()=>{
                null == setFormValueChanged || setFormValueChanged(true);
            });
        });
        if (props.disabled) form.disabled = props.disabled;
        return ()=>{
            form.removeEffects(id);
        };
    }, [
        form,
        props.disabled,
        setFormValueChanged
    ]);
    useEffect(()=>{
        const id = uid();
        const disposes = [];
        form.addEffects(id, ()=>{
            linkageRules.forEach((rule)=>{
                var _rule_actions;
                null == (_rule_actions = rule.actions) || _rule_actions.forEach((action)=>{
                    var _action_targetFields;
                    if (null == (_action_targetFields = action.targetFields) ? void 0 : _action_targetFields.length) {
                        const fields = action.targetFields.join(',');
                        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.display) || getTempFieldState(true, field.display),
                                required: (null == (_field_initStateOfLinkageRules1 = field.initStateOfLinkageRules) ? void 0 : _field_initStateOfLinkageRules1.required) || getTempFieldState(true, field.required || false),
                                pattern: (null == (_field_initStateOfLinkageRules2 = field.initStateOfLinkageRules) ? void 0 : _field_initStateOfLinkageRules2.pattern) || getTempFieldState(true, field.pattern),
                                value: (null == (_field_initStateOfLinkageRules3 = field.initStateOfLinkageRules) ? void 0 : _field_initStateOfLinkageRules3.value) || getTempFieldState(true, field.value || field.initialValue)
                            };
                            disposes.push(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__*/ jsx(FormDecorator, {
        ...props
    }) : /*#__PURE__*/ jsx(FormComponent, {
        ...props
    });
};
const WithoutForm = (props)=>{
    const fieldSchema = useFieldSchema();
    const { setFormValueChanged } = useActionContext();
    const form = useMemo(()=>createForm({
            disabled: props.disabled,
            effects () {
                onFormInputChange((form)=>{
                    null == setFormValueChanged || setFormValueChanged(true);
                });
            }
        }), []);
    return 'FormV2' === fieldSchema['x-decorator'] ? /*#__PURE__*/ jsx(FormDecorator, {
        form: form,
        ...props
    }) : /*#__PURE__*/ jsx(FormComponent, {
        form: form,
        ...props
    });
};
const Form = withDynamicSchemaProps(observer((props)=>{
    const field = useField();
    const { styles } = useStyles();
    const { form, disabled, ...others } = useProps(props);
    const formDisabled = disabled || field.disabled;
    return /*#__PURE__*/ jsx(ConfigProvider, {
        componentDisabled: formDisabled,
        children: /*#__PURE__*/ jsx("form", {
            onSubmit: (e)=>e.preventDefault(),
            className: styles.container,
            children: /*#__PURE__*/ jsx(Spin, {
                spinning: field.loading || false,
                children: form ? /*#__PURE__*/ jsx(WithForm, {
                    form: form,
                    ...others,
                    disabled: formDisabled
                }) : /*#__PURE__*/ jsx(WithoutForm, {
                    ...others,
                    disabled: formDisabled
                })
            })
        })
    });
}), {
    displayName: 'Form'
});
function getSubscriber(action, field, rule, variables, localVariables) {
    return ()=>{
        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[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 ActionType.Required:
        case ActionType.InRequired:
            return 'required';
        case ActionType.Visible:
        case ActionType.None:
        case ActionType.Hidden:
            return 'display';
        case ActionType.Editable:
        case ActionType.ReadOnly:
        case ActionType.ReadPretty:
            return 'pattern';
        case 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 = getTargetField(condition).join('.');
                return 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 = getInnermostKeyAndValue(condition);
            if (!jsonlogic) return null;
            if (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(REGEX_OF_VARIABLE)) ? void 0 : _value_match.map((variableString)=>getVariableValue(variableString, localVariables)).filter(Boolean);
}
function getVariableValue(variableString, localVariables) {
    var _localVariables_find;
    if (!isVariable(variableString)) return;
    const variableName = getVariableName(variableString);
    const ctx = {
        [variableName]: null == (_localVariables_find = localVariables.find((item)=>item.name === variableName)) ? void 0 : _localVariables_find.ctx
    };
    return getValuesByPath(ctx, getPath(variableString));
}
export { Form };
