import { useCallback, useEffect } from "react";
import { reaction, useField, useFieldSchema } from "@tachybase/schema";
import { getValuesByPath } from "@tego/client";
import lodash from "lodash";
import { useRecordIndex } from "../../../../record-provider/index.mjs";
import { useCollection_deprecated } from "../../../../collection-manager/index.mjs";
import { useCollectionRecord } from "../../../../data-source/collection-record/CollectionRecordProvider.mjs";
import { useFlag } from "../../../../flag-provider/index.mjs";
import { DEBOUNCE_WAIT, useLocalVariables, useVariables } from "../../../../variables/index.mjs";
import { getPath } from "../../../../variables/utils/getPath.mjs";
import { getVariableName } from "../../../../variables/utils/getVariableName.mjs";
import { isVariable } from "../../../../variables/utils/isVariable.mjs";
import { transformVariableValue } from "../../../../variables/utils/transformVariableValue.mjs";
import { isSubMode } from "../../association-field/util.mjs";
import { useSpecialCase } from "./useSpecialCase.mjs";
const useParseDefaultValue = ()=>{
    const field = useField();
    const fieldSchema = useFieldSchema();
    const variables = useVariables();
    const localVariables = useLocalVariables();
    const recordV2 = useCollectionRecord();
    const { isInAssignFieldValues, isInSetDefaultValueDialog, isInFormDataTemplate, isInSubTable, isInSubForm } = useFlag() || {};
    const { getField } = useCollection_deprecated();
    const { isSpecialCase, setDefaultValue } = useSpecialCase();
    const index = useRecordIndex();
    const findVariable = useCallback((name)=>{
        let result = null == variables ? void 0 : variables.getVariable(name);
        if (!result) result = localVariables.find((item)=>item.name === name);
        return result;
    }, [
        localVariables,
        variables
    ]);
    useEffect(()=>{
        if (null == fieldSchema.default || isInSetDefaultValueDialog || isInFormDataTemplate || isSubMode(fieldSchema) || !(null == recordV2 ? void 0 : recordV2.isNew) && !isInAssignFieldValues) return;
        const _run = async function() {
            let { forceUpdate = false } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
            if (variables && field && (isVariable(fieldSchema.default) && null == field.value || field.value === fieldSchema.default || forceUpdate)) {
                if (isVariable(field.value)) await field.reset({
                    forceClear: true
                });
                field.loading = true;
                const collectionField = !fieldSchema.name.toString().includes('.') && getField(fieldSchema.name);
                const value = transformVariableValue(await variables.parseVariable(fieldSchema.default, localVariables), {
                    targetCollectionField: collectionField
                });
                if (null == value || '' === value) {
                    field.setInitialValue(null);
                    await field.reset({
                        forceClear: true
                    });
                } else if (isSpecialCase()) {
                    if (0 === index) setDefaultValue(value);
                } else field.setInitialValue(value);
                field.loading = false;
            } else if (!/\{\{.+\}\}/g.test(fieldSchema.default) && field.setInitialValue) field.setInitialValue(fieldSchema.default);
        };
        const run = lodash.debounce(_run, DEBOUNCE_WAIT);
        if (isVariable(fieldSchema.default)) {
            const variableName = getVariableName(fieldSchema.default);
            const variable = findVariable(variableName);
            if (!variable) return console.error("useParseDefaultValue: can not find variable ".concat(variableName));
            _run();
            const dispose = reaction(()=>{
                const obj = {
                    [variableName]: (null == variable ? void 0 : variable.ctx) || {}
                };
                const path = getPath(fieldSchema.default);
                const value = getValuesByPath(obj, path);
                if (void 0 === value) return Math.random();
                return value;
            }, ()=>run({
                    forceUpdate: true
                }));
            return dispose;
        }
        if (null == field.value && (isInSubTable || isInSubForm)) field.setValue(fieldSchema.default);
    }, [
        fieldSchema.default,
        localVariables
    ]);
};
const hooks_useParseDefaultValue = useParseDefaultValue;
export { hooks_useParseDefaultValue as default };
