import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__context_mjs__ from "./context.mjs";
const findOption = function() {
    let dataIndex = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : [], options = arguments.length > 1 ? arguments[1] : void 0;
    var _dataIndex_forEach;
    let items = options;
    let option;
    null == dataIndex || null === (_dataIndex_forEach = dataIndex.forEach) || void 0 === _dataIndex_forEach || _dataIndex_forEach.call(dataIndex, (name, index)=>{
        const item = items.find((v)=>v.name === name);
        if (item) option = item;
        items = (null == item ? void 0 : item.children) || [];
    });
    return option;
};
const useValues = (options)=>{
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const logic = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(__WEBPACK_EXTERNAL_MODULE__context_mjs__.LinkageLogicContext);
    const value2data = ()=>{
        var _field_data;
        field.data = {
            ...field.initialValue || field.value
        };
        const dataIndex = null === (_field_data = field.data) || void 0 === _field_data ? void 0 : _field_data.targetFields;
        const option = dataIndex && findOption(dataIndex, options) || {};
        const operators = (null == option ? void 0 : option.operators) || [];
        field.data.operators = operators;
        field.data.schema = null == option ? void 0 : option.schema;
    };
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(value2data, [
        logic
    ]);
    return {
        fields: options,
        ...field.data,
        setDataIndex (dataIndex) {
            const option = findOption(dataIndex, options);
            field.data = field.data || {};
            const operators = null == option ? void 0 : option.operators;
            field.data.operators = null == operators ? void 0 : operators.filter((v)=>true);
            field.data.schema = null == option ? void 0 : option.schema;
            field.value = field.value || [];
            field.data.operator = void 0;
            field.data.value = void 0;
            field.value = {
                ...field.value,
                targetFields: dataIndex,
                operator: void 0,
                value: void 0
            };
        },
        setOperator (operatorValue) {
            field.data.operator = operatorValue;
            field.value = {
                ...field.value,
                operator: operatorValue
            };
        },
        setValue (value) {
            field.data.value = value;
            field.value = {
                ...field.value,
                value
            };
        }
    };
};
export { useValues };
