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__tachybase_utils_client__ from "@tachybase/utils/client";
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__api_client_index_mjs__ from "../../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__utils_mjs__ from "./utils.mjs";
const isEmptyObject = (val)=>!(0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.isValid)(val) || 'object' == typeof val && 0 === Object.keys(val).length;
const ObjectSelect = (props)=>{
    const { value, options, onChange, mode, fieldNames, loading, rawOptions, defaultValue, ...others } = props;
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const collectionName = fieldSchema['collectionName'];
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (collectionName && fieldSchema['name'].toString().includes('__custom') && defaultValue) {
            const name = fieldSchema['name'].toString().split('.')[1];
            form.values['__custom'][name] = null == defaultValue ? void 0 : defaultValue[fieldNames.value];
        }
    }, []);
    const toValue = (v)=>{
        var _getCurrentOptions;
        if (isEmptyObject(v)) return;
        const values = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.toArr)(v).filter((item)=>item).map((val)=>(0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.isPlainObject)(val) ? val[fieldNames.value] : val);
        const filterOption = options;
        const currentOptions = null === (_getCurrentOptions = (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.getCurrentOptions)(values, filterOption, fieldNames)) || void 0 === _getCurrentOptions ? void 0 : _getCurrentOptions.map((val)=>({
                label: val[fieldNames.label],
                value: val[fieldNames.value]
            }));
        if ([
            'tags',
            'multiple'
        ].includes(mode) || props.multiple) return currentOptions;
        return currentOptions.shift();
    };
    if (fieldNames['formula']) {
        delete others.onSearch;
        delete others.filterOption;
    }
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
        role: "button",
        "data-testid": "select-object-".concat(mode || 'single'),
        value: toValue(value),
        defaultValue: toValue(defaultValue),
        allowClear: {
            clearIcon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CloseCircleFilled, {
                role: "button",
                "aria-label": "icon-close-select"
            })
        },
        labelInValue: true,
        notFoundContent: loading ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {}) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Empty, {
            image: __WEBPACK_EXTERNAL_MODULE_antd__.Empty.PRESENTED_IMAGE_SIMPLE
        }),
        options: options,
        fieldNames: fieldNames,
        showSearch: true,
        popupMatchSelectWidth: false,
        filterOption: (input, option)=>{
            var _option_;
            return (null !== (_option_ = null == option ? void 0 : option[fieldNames.label || 'label']) && void 0 !== _option_ ? _option_ : '').includes(input);
        },
        filterSort: (optionA, optionB)=>{
            if ('number' == typeof optionA[fieldNames.label]) return optionA[fieldNames.label] - optionB[fieldNames.label];
            if ('string' == typeof optionA[fieldNames.label]) {
                var _optionA_, _optionB_;
                return (null !== (_optionA_ = null == optionA ? void 0 : optionA[fieldNames.label || 'label']) && void 0 !== _optionA_ ? _optionA_ : '').toLowerCase().localeCompare((null !== (_optionB_ = null == optionB ? void 0 : optionB[fieldNames.label || 'label']) && void 0 !== _optionB_ ? _optionB_ : '').toLowerCase());
            }
        },
        onChange: (changed)=>{
            const current = (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.getCurrentOptions)((0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.toArr)(changed).map((v)=>v.value), rawOptions || options, fieldNames);
            if ([
                'tags',
                'multiple'
            ].includes(mode) || props.multiple) null == onChange || onChange(current);
            else null == onChange || onChange(current.shift() || null);
            if (collectionName && fieldSchema['name'].toString().includes('__custom')) {
                const name = fieldSchema['name'].toString().split('.')[1];
                form.values['__custom'][name] = null == changed ? void 0 : changed['value'];
            }
        },
        mode: mode,
        tagRender: (props)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                role: "button",
                "aria-label": props.label,
                closeIcon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CloseOutlined, {
                    role: "button",
                    "aria-label": "icon-close-tag"
                }),
                ...props,
                children: props.label
            }),
        ...others
    });
};
const replacePlaceholders = (inputStr, values)=>inputStr.replace(/{{(.*?)}}/g, function(match, placeholder) {
        return Object.prototype.hasOwnProperty.call(values, placeholder) ? values[placeholder] : match;
    });
const useLabelOptions = (others)=>{
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { getField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const collectionField = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>getField(fieldSchema['x-collection-field']), [
        fieldSchema['x-collection-field']
    ]);
    const request = {
        resource: (null == collectionField ? void 0 : collectionField.target) || fieldSchema['collectionName'],
        action: 'list',
        params: {
            paginate: false
        }
    };
    const regex = /{{(.*?)}}/g;
    const matches = [];
    let match;
    while(null !== (match = regex.exec(others.fieldNames.formula)))matches.push(match[1]);
    const association = matches.filter((value)=>value.includes('.'));
    if (association.length) request.params['appends'] = association.map((value)=>value.split('.')[0]);
    const formula = others.fieldNames.formula;
    const [data, setData] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const { run } = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useRequest)(request, {
        manual: true,
        onSuccess: (result)=>{
            setData(result.data);
        }
    });
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (formula) run();
        else setData(others.options);
    }, [
        formula
    ]);
    if (formula) {
        var _others_options;
        null === (_others_options = others.options) || void 0 === _others_options || _others_options.forEach((op)=>{
            const valueOject = {};
            let outputStr = '';
            let match;
            null == data || data.forEach((opValue)=>{
                if (op.id === opValue.id) {
                    while(match = regex.exec(formula))if (match[1].includes('.')) {
                        const opvalue = opValue[match[1].split('.')[0]];
                        const value = opvalue ? opValue[match[1].split('.')[0]][match[1].split('.')[1]] : '';
                        valueOject[match[1]] = null != value ? value : '';
                    } else valueOject[match[1]] = opValue[match[1]] || '';
                    outputStr = replacePlaceholders(formula, valueOject);
                }
            });
            op[others.fieldNames.label] = outputStr;
        });
    }
    return others;
};
const FormulaSelect = (props)=>{
    const { objectValue, loading, value, rawOptions, defaultValue, ...others } = props;
    let mode = props.multiple ? 'multiple' : props.mode;
    const filterField = null == others ? void 0 : others['params'];
    const [options, setOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const [collectionName, setCollectionName] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)('');
    const api = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useAPIClient)();
    if (mode && ![
        'multiple',
        'tags'
    ].includes(mode)) mode = void 0;
    const fieldProps = {
        ...others
    };
    if ((null == others ? void 0 : others.collection) && others.collection !== collectionName) {
        api.request({
            url: others.collection + ':list',
            params: {
                paginate: false,
                filter: filterField ? {
                    ...filterField.filter
                } : {}
            }
        }).then((res)=>{
            setOptions(null == res ? void 0 : res.data.data);
            fieldProps['options'] = null == res ? void 0 : res.data.data;
        }).catch(()=>{});
        setCollectionName(others.collection);
    } else if ((null == others ? void 0 : others.collection) === collectionName) fieldProps['options'] = options.map((option)=>({
            ...option
        }));
    const modifiedProps = useLabelOptions(fieldProps);
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ObjectSelect, {
        rawOptions: rawOptions,
        ...modifiedProps,
        defaultValue: defaultValue,
        value: value,
        mode: mode,
        loading: loading
    });
};
const FormulaSelect_rslib_entry_ = FormulaSelect;
export { FormulaSelect_rslib_entry_ as default };
