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_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__ant_design_icons__ from "@ant-design/icons";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_mathjs__ from "mathjs";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../../index.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__remote_select_index_mjs__ from "../remote-select/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_mjs__ from "./hooks.mjs";
const filterAnalyses = (filters)=>{
    if (!filters) return;
    const type = Object.keys(filters)[0] || '$and';
    const conditions = filters[type];
    const results = [];
    null == conditions || conditions.map((c)=>{
        var _jsonlogic_value_match, _jsonlogic_value_match1, _jsonlogic_value;
        const jsonlogic = (0, __WEBPACK_EXTERNAL_MODULE__common_utils_uitls_mjs__.getInnermostKeyAndValue)(c);
        const operator = null == jsonlogic ? void 0 : jsonlogic.key;
        if (!operator) return true;
        const regex = /\{\{\$(?:[a-zA-Z_]\w*)\.([a-zA-Z_]\w*)(?:\.id)?\}\}/;
        const fieldName = null == jsonlogic ? void 0 : null === (_jsonlogic_value = jsonlogic.value) || void 0 === _jsonlogic_value ? void 0 : null === (_jsonlogic_value_match1 = _jsonlogic_value.match) || void 0 === _jsonlogic_value_match1 ? void 0 : null === (_jsonlogic_value_match = _jsonlogic_value_match1.call(_jsonlogic_value, regex)) || void 0 === _jsonlogic_value_match ? void 0 : _jsonlogic_value_match[1];
        if (fieldName) results.push(fieldName);
    });
    return results;
};
const InternalAssociationSelect = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    var _fieldSchema_xcomponentprops, _field_componentProps_service_params, _field_componentProps_service, _field_componentProps;
    const { objectValue = true } = props;
    const { message } = __WEBPACK_EXTERNAL_MODULE_antd__.App.useApp();
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const service = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__["default"])(props);
    const { options: collectionField } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useAssociationFieldContext)();
    const initValue = (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__.isVariable)(props.value) ? void 0 : props.value;
    const value = Array.isArray(initValue) ? initValue.filter(Boolean) : initValue;
    const [innerValue, setInnerValue] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(value);
    const addMode = null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops.addMode;
    const isAllowAddNew = fieldSchema['x-add-new'];
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const { multiple } = props;
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const api = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useAPIClient)();
    const resource = api.resource(collectionField.target);
    const linkageFields = filterAnalyses(null === (_field_componentProps = field.componentProps) || void 0 === _field_componentProps ? void 0 : null === (_field_componentProps_service = _field_componentProps.service) || void 0 === _field_componentProps_service ? void 0 : null === (_field_componentProps_service_params = _field_componentProps_service.params) || void 0 === _field_componentProps_service_params ? void 0 : _field_componentProps_service_params.filter);
    const recordData = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useCollectionRecordData)();
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const initValue = (0, __WEBPACK_EXTERNAL_MODULE__variables_utils_isVariable_mjs__.isVariable)(field.value) ? void 0 : field.value;
        const value = Array.isArray(initValue) ? initValue.filter(Boolean) : initValue;
        setInnerValue(value);
    }, [
        field.value
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const id = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.uid)();
        form.addEffects(id, ()=>{
            if ((null == linkageFields ? void 0 : linkageFields.length) > 0) (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.onFieldInputValueChange)('*', (fieldPath)=>{
                if (linkageFields.includes(fieldPath.props.name) && field.value) {
                    props.onChange(field.initialValue);
                    setInnerValue(field.initialValue);
                }
            });
        });
        return ()=>{
            form.removeEffects(id);
        };
    }, []);
    const handleCreateAction = async (props)=>{
        var _field_componentProps_fieldNames, _field_componentProps;
        const { search: value, callBack } = props;
        const { data: { data } } = await resource.create({
            values: {
                [(null == field ? void 0 : null === (_field_componentProps = field.componentProps) || void 0 === _field_componentProps ? void 0 : null === (_field_componentProps_fieldNames = _field_componentProps.fieldNames) || void 0 === _field_componentProps_fieldNames ? void 0 : _field_componentProps_fieldNames.label) || 'id']: value
            }
        });
        if (data) {
            if ([
                'm2m',
                'o2m'
            ].includes(null == collectionField ? void 0 : collectionField.interface) && false !== multiple) {
                const values = form.getValuesIn(field.path) || [];
                values.push(data);
                form.setValuesIn(field.path, values);
                field.onInput(values);
            } else {
                form.setValuesIn(field.path, data);
                field.onInput(data);
            }
            (0, __WEBPACK_EXTERNAL_MODULE_mathjs__.isFunction)(callBack) && (null == callBack || callBack());
            message.success(t('Saved successfully'));
        }
    };
    const QuickAddContent = (props)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
            onClick: ()=>handleCreateAction(props),
            style: {
                cursor: 'pointer',
                padding: '5px 12px',
                color: '#0d0c0c'
            },
            children: [
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.PlusOutlined, {}),
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("span", {
                    style: {
                        paddingLeft: 5
                    },
                    children: t('Add') + " “".concat(props.search, "” ")
                })
            ]
        });
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Space.Compact, {
            style: {
                display: 'flex',
                lineHeight: '32px'
            },
            children: [
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__remote_select_index_mjs__.RemoteSelect, {
                    style: {
                        width: '100%'
                    },
                    ...props,
                    size: 'middle',
                    objectValue: objectValue,
                    value: value || innerValue,
                    service: service,
                    onChange: (value)=>{
                        var _props_onChange;
                        const val = (null == value ? void 0 : value.length) !== 0 ? value : null;
                        null === (_props_onChange = props.onChange) || void 0 === _props_onChange || _props_onChange.call(props, val);
                    },
                    CustomDropdownRender: 'quickAdd' === addMode && QuickAddContent
                }),
                ('modalAdd' === addMode || isAllowAddNew) && /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.RecordProvider, {
                    isNew: true,
                    record: null,
                    parent: recordData,
                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.RecursionField, {
                        onlyRenderProperties: true,
                        basePath: field.address,
                        schema: fieldSchema,
                        filterProperties: (s)=>'Action' === s['x-component']
                    })
                })
            ]
        })
    }, fieldSchema.name);
}, {
    displayName: 'AssociationSelect'
});
const AssociationSelect = InternalAssociationSelect;
const AssociationSelectReadPretty = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.connect)((props)=>{
    const service = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__["default"])(props);
    (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useApp)();
    if (props.fieldNames) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__remote_select_index_mjs__.RemoteSelect.ReadPretty, {
        ...props,
        service: service
    });
    return null;
}, (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.mapProps)({
    dataSource: 'options',
    loading: true
}, (props, field)=>({
        ...props,
        fieldNames: props.fieldNames && {
            ...props.fieldNames,
            ...field.componentProps.fieldNames
        },
        suffixIcon: (null == field ? void 0 : field['loading']) || (null == field ? void 0 : field['validating']) ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.LoadingOutlined, {}) : props.suffixIcon
    })));
export { AssociationSelect, AssociationSelectReadPretty, filterAnalyses };
