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_dayjs__ from "dayjs";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
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__data_source_data_source_DataSourceProvider_mjs__ from "../../../data-source/data-source/DataSourceProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_utils_mjs__ from "../../../data-source/utils.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__ from "../../../filter-provider/utils.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__select_index_mjs__ from "../select/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__ReadPretty_mjs__ from "./ReadPretty.mjs";
const EMPTY = 'N/A';
const InternalRemoteSelect = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.connect)((props)=>{
    var _fieldSchema_xcomponentprops, _service_params;
    const { fieldNames = {}, service = {}, wait = 300, value, defaultValue, objectValue, manual = true, mapOptions, targetField: _targetField, CustomDropdownRender, optionFilter, ...others } = props;
    const dataSource = (0, __WEBPACK_EXTERNAL_MODULE__data_source_data_source_DataSourceProvider_mjs__.useDataSourceKey)();
    const headers = (0, __WEBPACK_EXTERNAL_MODULE__data_source_utils_mjs__.useDataSourceHeaders)(dataSource);
    const [open, setOpen] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const firstRun = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(false);
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const isQuickAdd = (null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops.addMode) === 'quickAdd';
    const { getField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const searchData = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(null);
    const { getCollectionJoinField, getInterface } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const colletionFieldName = fieldSchema['x-collection-field'] || fieldSchema.name;
    const collectionField = getField(colletionFieldName) || getCollectionJoinField(colletionFieldName);
    const targetField = _targetField || (null == collectionField ? void 0 : collectionField.target) && (null == fieldNames ? void 0 : fieldNames.label) && getCollectionJoinField("".concat(collectionField.target, ".").concat(fieldNames.label));
    const operator = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
        if (null == targetField ? void 0 : targetField.interface) {
            var _getInterface_filterable_operators_, _getInterface_filterable_operators, _getInterface_filterable, _getInterface;
            return (null === (_getInterface = getInterface(targetField.interface)) || void 0 === _getInterface ? void 0 : null === (_getInterface_filterable = _getInterface.filterable) || void 0 === _getInterface_filterable ? void 0 : null === (_getInterface_filterable_operators = _getInterface_filterable.operators) || void 0 === _getInterface_filterable_operators ? void 0 : null === (_getInterface_filterable_operators_ = _getInterface_filterable_operators[0]) || void 0 === _getInterface_filterable_operators_ ? void 0 : _getInterface_filterable_operators_.value) || '$includes';
        }
        return '$includes';
    }, [
        targetField
    ]);
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCompile)();
    const mapOptionsToTags = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((options)=>{
        try {
            return options.filter((v)=>[
                    'number',
                    'string'
                ].includes(typeof v[fieldNames.value])).map((option)=>{
                var _targetField_uiSchema;
                let label = compile(option[fieldNames.label]);
                if (null == targetField ? void 0 : null === (_targetField_uiSchema = targetField.uiSchema) || void 0 === _targetField_uiSchema ? void 0 : _targetField_uiSchema.enum) {
                    if (Array.isArray(label)) label = label.map((item, index)=>{
                        const option = targetField.uiSchema.enum.find((i)=>i.value === item);
                        if (option) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                            role: "button",
                            color: option.color,
                            style: {
                                marginRight: 3
                            },
                            children: (null == option ? void 0 : option.label) || item
                        }, index);
                        return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                            role: "button",
                            children: item
                        }, item);
                    }).reverse();
                    else {
                        const item = targetField.uiSchema.enum.find((i)=>i.value === label);
                        if (item) label = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Tag, {
                            role: "button",
                            color: item.color,
                            children: item.label
                        });
                    }
                }
                if ((null == targetField ? void 0 : targetField.type) === 'date') label = (0, __WEBPACK_EXTERNAL_MODULE_dayjs__["default"])(label).format('YYYY-MM-DD');
                if (mapOptions) return mapOptions({
                    [fieldNames.label]: label || EMPTY,
                    [fieldNames.value]: option[fieldNames.value]
                });
                return {
                    ...option,
                    [fieldNames.label]: label || EMPTY,
                    [fieldNames.value]: option[fieldNames.value]
                };
            }).filter(Boolean);
        } catch (err) {
            console.error(err);
            return options;
        }
    }, [
        null == targetField ? void 0 : targetField.uiSchema,
        fieldNames
    ]);
    const params = {
        ...null == service ? void 0 : service.params,
        filter: null == service ? void 0 : null === (_service_params = service.params) || void 0 === _service_params ? void 0 : _service_params.filter
    };
    if (fieldNames['formula']) params['paginate'] = false;
    else params['pageSize'] = 200;
    const { data, run, loading } = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useRequest)({
        action: 'list',
        ...service,
        headers,
        params
    }, {
        manual,
        debounceWait: wait
    });
    const runDep = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>JSON.stringify({
            service,
            fieldNames
        }), [
        service,
        fieldNames
    ]);
    const CustomRenderCom = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)(()=>{
        if (searchData.current && CustomDropdownRender) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(CustomDropdownRender, {
            search: searchData.current,
            callBack: ()=>{
                searchData.current = null;
                setOpen(false);
            }
        });
        return null;
    }, [
        searchData.current
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (firstRun.current) run();
    }, [
        runDep
    ]);
    const onSearch = async (search)=>{
        var _service_params;
        run({
            filter: (0, __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__.mergeFilter)([
                search ? {
                    [fieldNames.label]: {
                        [operator]: search
                    }
                } : {},
                null == service ? void 0 : null === (_service_params = service.params) || void 0 === _service_params ? void 0 : _service_params.filter
            ])
        });
        searchData.current = search;
    };
    const options = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
        var _data_data;
        const v = value || defaultValue;
        if (!(null == data ? void 0 : null === (_data_data = data.data) || void 0 === _data_data ? void 0 : _data_data.length)) return null != v ? Array.isArray(v) ? v : [
            v
        ] : [];
        const valueOptions = null != v && (Array.isArray(v) ? v : [
            {
                ...v,
                [fieldNames.value]: v[fieldNames.value] || v
            }
        ]) || [];
        const filtered = 'function' == typeof optionFilter ? data.data.filter(optionFilter) : data.data;
        return (0, __WEBPACK_EXTERNAL_MODULE_lodash__.uniqBy)(filtered.concat(null != valueOptions ? valueOptions : []), fieldNames.value);
    }, [
        value,
        defaultValue,
        null == data ? void 0 : data.data,
        fieldNames.value,
        optionFilter
    ]);
    const onDropdownVisibleChange = (visible)=>{
        setOpen(visible);
        searchData.current = null;
        if (visible) run();
        firstRun.current = true;
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__select_index_mjs__.Select, {
        open: open,
        popupMatchSelectWidth: false,
        autoClearSearchValue: true,
        filterOption: false,
        filterSort: null,
        fieldNames: fieldNames,
        onSearch: onSearch,
        onDropdownVisibleChange: onDropdownVisibleChange,
        objectValue: objectValue,
        value: value,
        defaultValue: defaultValue,
        ...others,
        loading: !data || loading,
        options: mapOptionsToTags(options),
        rawOptions: options,
        dropdownRender: (menu)=>{
            const isFullMatch = options.some((v)=>v[fieldNames.label] === searchData.current);
            return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
                children: isQuickAdd ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
                    children: [
                        !((null == data ? void 0 : data.data.length) === 0 && (null == searchData ? void 0 : searchData.current)) && menu,
                        (null == data ? void 0 : data.data.length) > 0 && (null == searchData ? void 0 : searchData.current) && !isFullMatch && /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Divider, {
                            style: {
                                margin: 0
                            }
                        }),
                        !isFullMatch && /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(CustomRenderCom, {})
                    ]
                }) : menu
            });
        }
    });
}, (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.mapProps)({
    dataSource: 'options'
}, (props, field)=>{
    var _fieldSchema_xcomponentprops;
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    return {
        ...props,
        fieldNames: {
            ...__WEBPACK_EXTERNAL_MODULE__select_index_mjs__.defaultFieldNames,
            ...props.fieldNames,
            ...field.componentProps.fieldNames,
            ...null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops.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
    };
}), (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.mapReadPretty)(__WEBPACK_EXTERNAL_MODULE__ReadPretty_mjs__.ReadPretty));
const RemoteSelect = InternalRemoteSelect;
RemoteSelect.ReadPretty = __WEBPACK_EXTERNAL_MODULE__ReadPretty_mjs__.ReadPretty;
const RemoteSelect_rslib_entry_ = RemoteSelect;
export { RemoteSelect, RemoteSelect_rslib_entry_ as default };
