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_components__ from "@tachybase/components";
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_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_antd_style__ from "antd-style";
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__index_mjs__ from "../../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__ from "../../../filter-provider/utils.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_mjs__ from "./hooks.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n      display: flex;\n      > .ant-space-item {\n        width: 100%;\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
const useStyles = (0, __WEBPACK_EXTERNAL_MODULE_antd_style__.createStyles)((param)=>{
    let { css } = param;
    return {
        space: css(_templateObject())
    };
});
const SchemaField = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.createSchemaField)({
    components: {
        Space: __WEBPACK_EXTERNAL_MODULE_antd__.Space,
        Input: __WEBPACK_EXTERNAL_MODULE_antd__.Input,
        ArrayItems: __WEBPACK_EXTERNAL_MODULE__tachybase_components__.ArrayItems,
        FormItem: __WEBPACK_EXTERNAL_MODULE__tachybase_components__.FormItem
    }
});
const Cascade = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.connect)((props)=>{
    var _associationField_componentProps, _fieldSchema_xcomponentprops_service_params, _fieldSchema_xcomponentprops_service, _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops_service_params1, _fieldSchema_xcomponentprops_service1, _fieldSchema_xcomponentprops1, _fieldSchema_xcomponentprops2, _fieldSchema_xcomponentprops3;
    const { data, mapOptions, onChange } = props;
    const [options, setOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(data);
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const [loading, setLoading] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const api = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useAPIClient)();
    const { options: collectionField, field: associationField } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useAssociationFieldContext)();
    const resource = api.resource(collectionField.target);
    const fieldNames = null == associationField ? void 0 : null === (_associationField_componentProps = associationField.componentProps) || void 0 === _associationField_componentProps ? void 0 : _associationField_componentProps.fieldNames;
    const fieldFilter = null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : null === (_fieldSchema_xcomponentprops_service = _fieldSchema_xcomponentprops.service) || void 0 === _fieldSchema_xcomponentprops_service ? void 0 : null === (_fieldSchema_xcomponentprops_service_params = _fieldSchema_xcomponentprops_service.params) || void 0 === _fieldSchema_xcomponentprops_service_params ? void 0 : _fieldSchema_xcomponentprops_service_params.filter;
    const sort = null === (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops1 ? void 0 : null === (_fieldSchema_xcomponentprops_service1 = _fieldSchema_xcomponentprops1.service) || void 0 === _fieldSchema_xcomponentprops_service1 ? void 0 : null === (_fieldSchema_xcomponentprops_service_params1 = _fieldSchema_xcomponentprops_service1.params) || void 0 === _fieldSchema_xcomponentprops_service_params1 ? void 0 : _fieldSchema_xcomponentprops_service_params1.sort;
    const changOnSelect = (null === (_fieldSchema_xcomponentprops2 = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops2 ? void 0 : _fieldSchema_xcomponentprops2.changOnSelect) || false;
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const [selectedOptions, setSelectedOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const [change, setChange] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const [dataList, setDataList] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({});
    const { styles } = useStyles();
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const propsValue = props.value || fieldSchema['x-component-props'].value;
        if (!change && propsValue) {
            if (propsValue.parent || Object.keys(dataList).length) {
                var _values_map;
                const values = [];
                if (!propsValue.parent && Object.keys(dataList).length) {
                    const defValue = transformChildrenData(dataList, [], propsValue.id);
                    values.push(...defValue);
                } else {
                    const defValue = Array.isArray(propsValue) ? extractLastNonNullValueObjects(null == propsValue ? void 0 : propsValue.filter((v)=>v.value), true) : transformNestedData(propsValue);
                    values.push(...defValue);
                }
                const defaultData = null == values ? void 0 : null === (_values_map = values.map) || void 0 === _values_map ? void 0 : _values_map.call(values, (v)=>v.id);
                onDropdownVisibleChange(true);
                setSelectedOptions(defaultData);
            } else resource.list({
                paginate: false,
                filter: propsValue.id ? {
                    id: {
                        $eq: propsValue.id
                    }
                } : {},
                sort,
                tree: true
            }).then((res)=>{
                var _res_data;
                setDataList(null === (_res_data = res.data) || void 0 === _res_data ? void 0 : _res_data.data[0]);
            }).catch(()=>{});
        }
    }, [
        fieldSchema['x-component-props'].value,
        null === (_fieldSchema_xcomponentprops3 = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops3 ? void 0 : _fieldSchema_xcomponentprops3.changOnSelect,
        dataList
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        onDropdownVisibleChange(true);
    }, [
        fieldFilter
    ]);
    const handleGetOptions = async ()=>{
        var _response_data;
        const response = await resource.list({
            paginate: false,
            filter: (0, __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__.mergeFilter)([
                fieldFilter,
                filter
            ]),
            sort,
            tree: true
        });
        return null == response ? void 0 : null === (_response_data = response.data) || void 0 === _response_data ? void 0 : _response_data.data;
    };
    const handleSelect = async (option)=>{
        setChange(true);
        if (option) {
            if ([
                'o2m',
                'm2m'
            ].includes(collectionField.interface)) {
                const fieldValue = Array.isArray(associationField.fieldValue) ? associationField.fieldValue : [];
                fieldValue[field.index] = option[option.length - 1];
                associationField.fieldValue = fieldValue;
            } else associationField.value = option[option.length - 1];
            const options = [];
            options.push({
                key: void 0,
                children: [],
                value: option[0]
            });
            option.forEach((item, index)=>{
                if (index === option.length - 1) options.push({
                    key: item.id,
                    children: item.children || null
                });
                else options.push({
                    key: item.id,
                    children: item.children,
                    value: option[index + 1]
                });
            });
            null == onChange || onChange(options);
        } else null == onChange || onChange({});
    };
    const cascadeOption = (option)=>{
        option.forEach((item)=>{
            item['value'] = item[fieldNames.value];
            item['label'] = item[fieldNames.label];
            if (item.children) item.children = cascadeOption(item.children);
        });
        return option;
    };
    const onDropdownVisibleChange = async (visible)=>{
        if (visible) {
            setLoading(true);
            let result = await handleGetOptions();
            result = cascadeOption(result);
            setLoading(false);
            setOptions(result);
        }
    };
    const filter = (inputValue, path)=>(0, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.fuzzysearch)(inputValue, path.map((option)=>option.label || '').join(''));
    var _selectedOptions_;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Space, {
        wrap: true,
        className: styles.space,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.CustomCascader, {
            style: {
                width: '100%'
            },
            showSearch: {
                filter
            },
            fieldNames: fieldNames,
            defaultValue: selectedOptions,
            options: options,
            onChange: (value, option)=>handleSelect(option),
            onDropdownVisibleChange: (visible)=>{
                onDropdownVisibleChange(visible);
            },
            changeOnSelect: changOnSelect,
            placeholder: "Please select"
        }, null !== (_selectedOptions_ = selectedOptions[0]) && void 0 !== _selectedOptions_ ? _selectedOptions_ : [])
    });
});
const AssociationCascadeSelect = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.connect)((props)=>/*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
        style: {
            width: '100%'
        },
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(Cascade, {
            ...props
        })
    }));
const InternalCascader = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    const { options: collectionField } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useAssociationFieldContext)();
    const selectForm = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>(0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.createForm)(), []);
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    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);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const id = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.uid)();
        selectForm.addEffects(id, ()=>{
            (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.onFormValuesChange)((form)=>{
                if ('m2o' === collectionField.interface) {
                    var _form_values;
                    const value = extractLastNonNullValueObjects(null === (_form_values = form.values) || void 0 === _form_values ? void 0 : _form_values[fieldSchema.name]);
                    setTimeout(()=>{
                        form.setValuesIn(fieldSchema.name, value);
                        props.onChange(value);
                        field.value = value;
                    });
                } else {
                    var _form_values1;
                    const value = extractLastNonNullValueObjects(null === (_form_values1 = form.values) || void 0 === _form_values1 ? void 0 : _form_values1.select_array).filter((v)=>v && Object.keys(v).length > 0);
                    setTimeout(()=>{
                        field.value = value;
                        props.onChange(value);
                    });
                }
            });
        });
        return ()=>{
            selectForm.removeEffects(id);
        };
    }, []);
    const toValue = ()=>{
        if (Array.isArray(field.value) && field.value.length > 0) return field.value;
        return [
            {}
        ];
    };
    const defaultValue = toValue();
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        var _selectForm_values_select_array, _selectForm_values;
        const isChange = null === (_selectForm_values = selectForm.values) || void 0 === _selectForm_values ? void 0 : null === (_selectForm_values_select_array = _selectForm_values.select_array) || void 0 === _selectForm_values_select_array ? void 0 : _selectForm_values_select_array.filter((value)=>value && Object.keys(value).length);
        if ('m2o' !== collectionField.interface && props.value && !isChange.length) selectForm.setInitialValues({
            select_array: defaultValue
        });
    }, [
        props.value
    ]);
    const schema = {
        type: 'object',
        properties: {
            select_array: {
                type: 'array',
                'x-component': 'ArrayItems',
                'x-decorator': 'FormItem',
                default: defaultValue,
                items: {
                    type: 'void',
                    'x-component': 'Space',
                    properties: {
                        sort: {
                            type: 'void',
                            'x-decorator': 'FormItem',
                            'x-component': 'ArrayItems.SortHandle'
                        },
                        select: {
                            type: 'string',
                            'x-decorator': 'FormItem',
                            'x-component': AssociationCascadeSelect,
                            'x-component-props': {
                                ...props,
                                style: {
                                    width: '100%'
                                }
                            },
                            'x-read-pretty': false
                        },
                        remove: {
                            type: 'void',
                            'x-decorator': 'FormItem',
                            'x-component': 'ArrayItems.Remove'
                        }
                    }
                },
                properties: {
                    add: {
                        type: 'void',
                        title: t('Add new'),
                        'x-component': 'ArrayItems.Addition'
                    }
                }
            }
        }
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.FormProvider, {
        form: selectForm,
        children: 'm2o' === collectionField.interface ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaComponent, {
            components: {
                FormItem: __WEBPACK_EXTERNAL_MODULE__tachybase_components__.FormItem
            },
            schema: {
                ...fieldSchema,
                default: field.value,
                title: '',
                'x-component': AssociationCascadeSelect,
                'x-component-props': {
                    ...props,
                    service,
                    style: {
                        width: '100%'
                    }
                },
                'x-read-pretty': false
            }
        }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(SchemaField, {
            schema: schema
        })
    });
}, {
    displayName: 'InternalCascader'
});
function extractLastNonNullValueObjects(data, flag) {
    let result = [];
    if (!Array.isArray(data)) return data;
    for (const sublist of data){
        let lastNonNullValue = null;
        if (Array.isArray(sublist)) {
            for(let i = (null == sublist ? void 0 : sublist.length) - 1; i >= 0; i--)if (sublist[i].value) {
                lastNonNullValue = sublist[i].value;
                break;
            }
            if (lastNonNullValue) result.push(lastNonNullValue);
        } else {
            lastNonNullValue = (null == sublist ? void 0 : sublist.value) ? sublist.value : null;
            if (lastNonNullValue) {
                if (flag) {
                    var _result_push;
                    null == result || null === (_result_push = result.push) || void 0 === _result_push || _result_push.call(result, lastNonNullValue);
                } else result = lastNonNullValue;
            } else {
                var _result_push1;
                null == result || null === (_result_push1 = result.push) || void 0 === _result_push1 || _result_push1.call(result, sublist);
            }
        }
    }
    return result;
}
function transformNestedData(inputData) {
    const resultArray = [];
    function recursiveTransform(data) {
        if (null == data ? void 0 : data.parent) {
            const { parent } = data;
            recursiveTransform(parent);
        }
        const { parent, ...other } = data;
        resultArray.push(other);
    }
    if (inputData) recursiveTransform(inputData);
    return resultArray;
}
const transformChildrenData = (inputData, result, itemId)=>{
    const { children, ...other } = inputData;
    result.push(other);
    if (!children || (null == inputData ? void 0 : inputData.id) === itemId || !children.length) return result;
    {
        const { children } = inputData;
        return transformChildrenData(children[0], result, itemId);
    }
};
export { InternalCascader, transformChildrenData, transformNestedData };
