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_ahooks__ from "ahooks";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_flat__ from "flat";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE_react_intersection_observer__ from "react-intersection-observer";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../../../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_index_mjs__ from "../../../../data-source/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_collection_record_isNewRecord_mjs__ from "../../../../data-source/collection-record/isNewRecord.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_mjs__ from "../hooks.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hook_mjs__ from "./hook.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__styles_mjs__ from "./styles.mjs";
const ObservableItem = (param)=>{
    let { item, onChange, leftRef } = param;
    var _item_childrenItems;
    const { ref } = (0, __WEBPACK_EXTERNAL_MODULE_react_intersection_observer__.useInView)({
        threshold: 0.1,
        onChange: (inView)=>{
            if (inView && leftRef.current) {
                const currentId = '#parent-item-' + item.id;
                leftRef.current.querySelector(currentId).scrollIntoView({
                    behavior: 'auto',
                    block: 'nearest',
                    inline: 'start'
                });
            }
        }
    });
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
        id: 'item-' + item.id,
        ref: ref,
        children: null == item ? void 0 : null === (_item_childrenItems = item.childrenItems) || void 0 === _item_childrenItems ? void 0 : _item_childrenItems.sort((a, b)=>null != a.sort ? a.sort - b.sort : a.id - b.id).map((childrenitem, index)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
                onClick: ()=>{
                    onChange(childrenitem);
                },
                icon: childrenitem.checked ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CheckOutlined, {}) : null,
                children: childrenitem.label
            }, index))
    }, item.id);
};
const InternalTabs = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    var _fieldSchema_parent_xcomponentprops, _quickAddSchema_xcomponentprops_service, _quickAddSchema_xcomponentprops, _Object_values;
    const ref = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)();
    const { styles } = (0, __WEBPACK_EXTERNAL_MODULE__styles_mjs__.useStyles)();
    const { fieldValue, setFieldValue } = props;
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const cm = (0, __WEBPACK_EXTERNAL_MODULE__data_source_index_mjs__.useCollectionManager)();
    const api = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useAPIClient)();
    const [filter, setFilter] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)('');
    const isQuickAdd = fieldSchema['parent']['x-component-props']['isQuickAdd'];
    const { value: quickAddField, fieldInterface } = (null === (_fieldSchema_parent_xcomponentprops = fieldSchema['parent']['x-component-props']) || void 0 === _fieldSchema_parent_xcomponentprops ? void 0 : _fieldSchema_parent_xcomponentprops['quickAddField']) || {};
    const quickAddParentField = fieldSchema['parent']['x-component-props']['quickAddParentCollection'];
    const [defOptions, setDefOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const { field } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useAssociationFieldContext)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const [changeForm, setChangeForm] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)();
    const quickAddSchema = fieldSchema.reduceProperties((buf, schema)=>{
        const found = schema.reduceProperties((buf, schema)=>{
            if (schema.name === quickAddField) return schema;
            return buf;
        });
        if (found) return found;
        return buf;
    }, new __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.Schema({}));
    const tabparams = null === (_quickAddSchema_xcomponentprops = quickAddSchema['x-component-props']) || void 0 === _quickAddSchema_xcomponentprops ? void 0 : null === (_quickAddSchema_xcomponentprops_service = _quickAddSchema_xcomponentprops['service']) || void 0 === _quickAddSchema_xcomponentprops_service ? void 0 : _quickAddSchema_xcomponentprops_service['params'];
    const [fieldServiceFilter] = (0, __WEBPACK_EXTERNAL_MODULE__hook_mjs__.useFieldServiceFilter)(null == tabparams ? void 0 : tabparams.filter);
    const formFilter = (0, __WEBPACK_EXTERNAL_MODULE_flat__["default"])((null == tabparams ? void 0 : tabparams.filter) || {});
    const formFieldFilter = null === (_Object_values = Object.values(formFilter)) || void 0 === _Object_values ? void 0 : _Object_values.map((item)=>{
        const field = item;
        const match = field.match(/^{{\$nForm\.(.*?)\./);
        if (match) return match[1];
    }).filter(Boolean);
    (0, __WEBPACK_EXTERNAL_MODULE_ahooks__.useAsyncEffect)(async ()=>{
        const itemParams = {};
        const optionsItem = [];
        if ((null == tabparams ? void 0 : tabparams.filter) && !fieldServiceFilter) return;
        if ((quickAddField || 'none' !== quickAddField || !isQuickAdd) && fieldSchema.properties) {
            const params = {
                pageSize: 99999,
                filter: JSON.stringify(fieldServiceFilter)
            };
            if (quickAddParentField && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none') {
                var _parentItem_data;
                params['appends'] = [
                    quickAddParentField.value
                ];
                const collection = cm.getCollection(quickAddParentField.collectionField);
                const parentItem = await api.request({
                    url: collection.name + ':list',
                    params: {
                        pageSize: 99999
                    }
                });
                itemParams['parentTitleField'] = collection.titleField;
                itemParams['parentOptions'] = null == parentItem ? void 0 : null === (_parentItem_data = parentItem.data) || void 0 === _parentItem_data ? void 0 : _parentItem_data.data;
            }
            if (quickAddSchema && 'm2o' === fieldInterface) {
                var _childrenItem_data, _itemParams_parentOptions, _itemParams_childrenOptions, _itemParams_childrenOptions1;
                itemParams['service'] = quickAddSchema['x-component-props'].service;
                itemParams['collectionName'] = cm.getCollection(quickAddSchema['x-collection-field']).name;
                const childrenItem = await api.request({
                    url: itemParams['collectionName'] + ':list',
                    params
                });
                itemParams['childrenTitleField'] = cm.getCollection(itemParams['collectionName']).titleField;
                itemParams['childrenOptions'] = null == childrenItem ? void 0 : null === (_childrenItem_data = childrenItem.data) || void 0 === _childrenItem_data ? void 0 : _childrenItem_data.data;
                if ((null === (_itemParams_parentOptions = itemParams['parentOptions']) || void 0 === _itemParams_parentOptions ? void 0 : _itemParams_parentOptions.length) && (null === (_itemParams_childrenOptions = itemParams['childrenOptions']) || void 0 === _itemParams_childrenOptions ? void 0 : _itemParams_childrenOptions.length) && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none') itemParams['parentOptions'].forEach((parentItem)=>{
                    const items = itemParams['childrenOptions'].map((item)=>{
                        var _item_quickAddParentField_value;
                        if ((null === (_item_quickAddParentField_value = item[null == quickAddParentField ? void 0 : quickAddParentField.value]) || void 0 === _item_quickAddParentField_value ? void 0 : _item_quickAddParentField_value.id) === parentItem.id) return {
                            ...item,
                            label: item[itemParams['childrenTitleField']],
                            keys: item.id,
                            value: item.id,
                            checked: false
                        };
                    }).filter(Boolean);
                    if (!items.length) return;
                    optionsItem.push({
                        ...parentItem,
                        value: null == parentItem ? void 0 : parentItem.id,
                        label: parentItem[itemParams['parentTitleField']],
                        key: parentItem.id,
                        childrenItems: items
                    });
                });
                else if ((null === (_itemParams_childrenOptions1 = itemParams['childrenOptions']) || void 0 === _itemParams_childrenOptions1 ? void 0 : _itemParams_childrenOptions1.length) && (!quickAddParentField || (null == quickAddParentField ? void 0 : quickAddParentField.value) === 'none')) itemParams['childrenOptions'].forEach((item)=>{
                    optionsItem.push({
                        ...item,
                        label: item[itemParams['childrenTitleField']],
                        value: null == item ? void 0 : item.id,
                        key: null == item ? void 0 : item.id,
                        checked: false
                    });
                });
                setDefOptions(optionsItem);
            } else if (quickAddSchema) {
                const fieldItem = cm.getCollectionField(quickAddSchema['x-collection-field']);
                if (!(null == fieldItem ? void 0 : fieldItem.uiSchema) || !(null == fieldItem ? void 0 : fieldItem.uiSchema.enum)) return;
                fieldItem.uiSchema.enum.forEach((item)=>{
                    optionsItem.push(item);
                });
                setDefOptions(optionsItem);
            }
        }
    }, [
        fieldServiceFilter,
        null == tabparams ? void 0 : tabparams.filter,
        changeForm,
        isQuickAdd,
        quickAddField,
        quickAddParentField
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_ahooks__.useDeepCompareEffect)(()=>{
        if (!defOptions.length) return;
        const fieldTabs = field.value;
        if (quickAddParentField && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none') {
            const filterParantOptions = tabsParantFilterOptions(defOptions, fieldTabs, quickAddField);
            setDefOptions(filterParantOptions);
        } else {
            const filterDefOptions = tabsFilterOptions(defOptions, fieldTabs, quickAddField);
            setDefOptions(filterDefOptions);
        }
    }, [
        quickAddField,
        fieldValue
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFormEffects)(()=>{
        (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.onFieldChange)(formFieldFilter, (field)=>{
            setChangeForm(field);
        });
    });
    let options = defOptions;
    if (quickAddParentField && 'none' !== quickAddParentField.value) {
        const filterOption = null == defOptions ? void 0 : defOptions.map((item)=>{
            var _item_childrenItems;
            const filterItem = null == item ? void 0 : null === (_item_childrenItems = item.childrenItems) || void 0 === _item_childrenItems ? void 0 : _item_childrenItems.filter((childrenItem)=>(0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.fuzzysearch)(filter, null == childrenItem ? void 0 : childrenItem.label));
            if ((0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.fuzzysearch)(filter, null == item ? void 0 : item.label) || (null == filterItem ? void 0 : filterItem.length)) return {
                ...item,
                childrenItems: (null == filterItem ? void 0 : filterItem.length) ? filterItem : item.childrenItems
            };
        }).filter(Boolean);
        options = filterOption;
    } else {
        const filterOption = defOptions.filter((item)=>(0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.fuzzysearch)(filter, null == item ? void 0 : item.label));
        options = filterOption;
    }
    const onChange = (item)=>{
        field.value = field.value || [];
        const addItem = {};
        addItem[quickAddField] = item;
        field.value.push((0, __WEBPACK_EXTERNAL_MODULE__data_source_collection_record_isNewRecord_mjs__.markRecordAsNew)(addItem));
        setFieldValue([
            ...field.value
        ]);
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Input, {
                placeholder: t('Please enter search content'),
                prefix: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.SearchOutlined, {}),
                value: filter,
                onChange: (e)=>{
                    setFilter(e.target.value);
                }
            }),
            quickAddParentField && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none' ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
                className: styles.container,
                ref: ref,
                children: [
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                        className: "left-pane",
                        children: options.sort((a, b)=>null != a.sort ? a.sort - b.sort : a.id - b.id).map((item)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                                id: 'parent-item-' + item.id,
                                onClick: ()=>{
                                    var _ref_current;
                                    null === (_ref_current = ref.current) || void 0 === _ref_current || _ref_current.querySelector('#item-' + item.id).scrollIntoView({
                                        behavior: 'auto',
                                        block: 'nearest',
                                        inline: 'start'
                                    });
                                    const currentId = '#parent-item-' + item.id;
                                    ref.current.querySelector(currentId).scrollIntoView({
                                        behavior: 'auto',
                                        block: 'nearest',
                                        inline: 'start'
                                    });
                                    ref.current.querySelector(currentId).style.color = '#166cff';
                                    const allElements = ref.current.querySelectorAll('div:not(' + currentId + ')');
                                    null == allElements || allElements.forEach(function(element) {
                                        element.style.color = '#1e1e1e';
                                    });
                                },
                                children: item.label
                            }, item.id))
                    }),
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                        className: "right-pane",
                        children: options.sort((a, b)=>null != a.sort ? a.sort - b.sort : a.id - b.id).map((item)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ObservableItem, {
                                item: item,
                                onChange: onChange,
                                leftRef: ref
                            }, item.id))
                    })
                ]
            }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Space, {
                style: {
                    maxHeight: '30vh',
                    overflow: 'auto',
                    padding: '10px'
                },
                children: options.map((item, index)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
                        onClick: ()=>{
                            onChange(item);
                        },
                        icon: item.checked ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CheckOutlined, {}) : null,
                        children: item.label
                    }, index))
            })
        ]
    });
});
const tabsParantFilterOptions = (options, fieldTabs, arrayField)=>{
    const filterOptions = null == options ? void 0 : options.map((oItem)=>{
        const filterItem = oItem.childrenItems.map((childrenItem)=>{
            const fieldTabsValue = fieldTabs.find((item)=>{
                var _item_arrayField;
                return (null === (_item_arrayField = item[arrayField]) || void 0 === _item_arrayField ? void 0 : _item_arrayField.value) === childrenItem.value;
            });
            return {
                ...childrenItem,
                checked: !!fieldTabsValue || false
            };
        });
        return {
            ...oItem,
            childrenItems: filterItem
        };
    });
    return filterOptions;
};
const tabsFilterOptions = (optitons, filterTabs, arrayField)=>{
    const filterOptions = optitons.map((item)=>{
        const filterValue = filterTabs.find((filterTabsItem)=>{
            var _filterTabsItem_arrayField;
            return (null === (_filterTabsItem_arrayField = filterTabsItem[arrayField]) || void 0 === _filterTabsItem_arrayField ? void 0 : _filterTabsItem_arrayField.value) === item.value;
        });
        return {
            ...item,
            checked: !!filterValue || false
        };
    });
    return filterOptions;
};
const InternalCollapse = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    var _fieldSchema_parent_xcomponentprops;
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const isQuickAdd = fieldSchema['parent']['x-component-props']['isQuickAdd'];
    const { value: quickAddField } = (null === (_fieldSchema_parent_xcomponentprops = fieldSchema['parent']['x-component-props']) || void 0 === _fieldSchema_parent_xcomponentprops ? void 0 : _fieldSchema_parent_xcomponentprops['quickAddField']) || {};
    const items = [
        {
            key: '1',
            label: t('Quick create'),
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(InternalTabs, {
                ...props
            })
        }
    ];
    return isQuickAdd && quickAddField && 'none' !== quickAddField ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Collapse, {
        items: items,
        defaultActiveKey: [
            '1'
        ]
    }) : null;
});
export { InternalCollapse, InternalTabs, ObservableItem };
