import { jsx } from "react/jsx-runtime";
import { useCallback } from "react";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { Variable, useVariableScope } from "../../schema-component/index.mjs";
import { useValues } from "../../schema-component/antd/filter/useValues.mjs";
import { isVariable } from "../../variables/utils/isVariable.mjs";
import { useBlockCollection } from "./hooks/useBlockCollection.mjs";
import { useContextAssociationFields } from "./hooks/useContextAssociationFields.mjs";
import { useCurrentRecordVariable } from "./hooks/useRecordVariable.mjs";
import { useCurrentUserVariable } from "./hooks/useUserVariable.mjs";
import { useVariableOptions } from "./hooks/useVariableOptions.mjs";
const VariableInput = (props)=>{
    const { value, onChange, renderSchemaComponent: RenderSchemaComponent, style, schema, className, contextCollectionName, collectionField, shouldChange, form, record, returnScope = lodash.identity, targetFieldSchema } = props;
    const { name: blockCollectionName } = useBlockCollection();
    const scope = useVariableScope();
    const { operator, schema: uiSchema = null == collectionField ? void 0 : collectionField.uiSchema } = useValues();
    const variableOptions = useVariableOptions({
        collectionField,
        form,
        record,
        operator,
        uiSchema,
        targetFieldSchema
    });
    const contextVariable = useContextAssociationFields({
        schema,
        maxDepth: 2,
        contextCollectionName,
        collectionField
    });
    const { compatOldVariables } = useCompatOldVariables({
        collectionField,
        uiSchema,
        targetFieldSchema,
        blockCollectionName
    });
    if (contextCollectionName && variableOptions.every((item)=>item.value !== contextVariable.value)) variableOptions.push(contextVariable);
    const handleChange = useCallback((value, optionPath)=>{
        if (!shouldChange) return onChange(value);
        setTimeout(async ()=>{
            if (await shouldChange(value, optionPath)) onChange(value);
        });
    }, [
        onChange,
        shouldChange
    ]);
    return /*#__PURE__*/ jsx(Variable.Input, {
        className: className,
        value: value,
        onChange: handleChange,
        scope: returnScope(compatOldVariables(lodash.isEmpty(scope) ? variableOptions : scope, {
            value
        })),
        style: style,
        changeOnSelect: true,
        children: /*#__PURE__*/ jsx(RenderSchemaComponent, {
            value: value,
            onChange: onChange
        })
    });
};
const getShouldChange = (param)=>{
    let { collectionField, variables, localVariables, getAllCollectionsInheritChain } = param;
    const collectionsInheritChain = collectionField ? getAllCollectionsInheritChain(collectionField.target) : [];
    return async (value, optionPath)=>{
        if (lodash.isString(value) && value.includes('$nRole')) return true;
        if (!isVariable(value) || !variables || !collectionField) return true;
        if ('json' === collectionField.interface) return true;
        const lastOption = optionPath[optionPath.length - 1];
        if (lastOption && lodash.isEmpty(lastOption.children) && !lastOption.loadChildren) return true;
        const collectionFieldOfVariable = await variables.getCollectionField(value, localVariables);
        if (!collectionField) return false;
        if ([
            'o2o',
            'o2m',
            'oho'
        ].includes(null == collectionFieldOfVariable ? void 0 : collectionFieldOfVariable.interface)) return false;
        if (!collectionField.target && (null == collectionFieldOfVariable ? void 0 : collectionFieldOfVariable.target)) return false;
        if (collectionField.target && !(null == collectionFieldOfVariable ? void 0 : collectionFieldOfVariable.target)) return false;
        if (collectionField.target && (null == collectionFieldOfVariable ? void 0 : collectionFieldOfVariable.target) && !collectionsInheritChain.includes(null == collectionFieldOfVariable ? void 0 : collectionFieldOfVariable.target)) return false;
        return true;
    };
};
function useCompatOldVariables(props) {
    const { uiSchema, collectionField, noDisabled, targetFieldSchema, blockCollectionName } = props;
    const { t } = useTranslation();
    const { currentUserSettings } = useCurrentUserVariable({
        maxDepth: 1,
        uiSchema: uiSchema,
        collectionField,
        noDisabled,
        targetFieldSchema
    });
    const { currentRecordSettings } = useCurrentRecordVariable({
        schema: uiSchema,
        collectionField,
        noDisabled,
        targetFieldSchema
    });
    const compatOldVariables = useCallback((variables, param)=>{
        let { value } = param;
        if (!isVariable(value)) return variables;
        variables = lodash.cloneDeep(variables);
        const systemVariable = {
            value: '$system',
            key: '$system',
            label: t('System variables'),
            isLeaf: false,
            children: [
                {
                    value: 'now',
                    key: 'now',
                    label: t('Current time'),
                    isLeaf: true,
                    depth: 1
                }
            ],
            depth: 0
        };
        const currentTime = {
            value: 'currentTime',
            label: t('Current time'),
            children: null
        };
        if (value.includes('$system')) variables.push(systemVariable);
        if (value.includes("".concat(blockCollectionName, "."))) {
            const variable = variables.find((item)=>'$nForm' === item.value || '$nRecord' === item.value);
            if (variable) variable.value = blockCollectionName;
        }
        if (value.includes('$form')) {
            const variable = variables.find((item)=>'$nForm' === item.value);
            if (variable) variable.value = '$form';
        }
        if (value.includes('currentUser')) {
            const userVariable = variables.find((item)=>'$user' === item.value);
            if (userVariable) userVariable.value = 'currentUser';
            else variables.unshift({
                ...currentUserSettings,
                value: 'currentUser'
            });
        }
        if (value.includes('currentRecord')) {
            const formVariable = variables.find((item)=>'$nRecord' === item.value);
            if (formVariable) formVariable.value = 'currentRecord';
            else variables.unshift({
                ...currentRecordSettings,
                value: 'currentRecord'
            });
        }
        if (value.includes('currentTime')) variables.push(currentTime);
        if (value.includes('$date')) {
            const formVariable = variables.find((item)=>'$nDate' === item.value);
            if (formVariable) formVariable.value = '$date';
        }
        return variables;
    }, [
        blockCollectionName
    ]);
    return {
        compatOldVariables
    };
}
export { VariableInput, getShouldChange, useCompatOldVariables };
