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_antd_style__ from "antd-style";
import * as __WEBPACK_EXTERNAL_MODULE_rc_util_lib_ref__ from "rc-util/lib/ref";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__ from "../../record-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_antd_action_utils_mjs__ from "../../schema-component/antd/action/utils.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_common_utils_uitls_mjs__ from "../../schema-component/common/utils/uitls.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__ from "../../variables/index.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      position: relative;\n      &:hover {\n        .general-schema-designer {\n          display: block;\n        }\n      }\n      .general-schema-designer {\n        position: absolute;\n        z-index: 999;\n        top: 0;\n        bottom: 0;\n        left: 0;\n        right: 0;\n        display: none;\n        background: var(--colorBgSettingsHover);\n        border: 0;\n        pointer-events: none;\n        > .general-schema-designer-icons {\n          position: absolute;\n          right: 2px;\n          top: 2px;\n          line-height: 16px;\n          pointer-events: all;\n          .ant-space-item {\n            background-color: var(--colorSettings);\n            color: #fff;\n            line-height: 16px;\n            width: 16px;\n            padding-left: 1px;\n            align-self: stretch;\n          }\n        }\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      position: relative;\n      &:hover {\n        .general-schema-designer {\n          display: block;\n        }\n      }\n      .general-schema-designer {\n        position: absolute;\n        z-index: 999;\n        top: 0;\n        bottom: 0;\n        left: 0;\n        right: 0;\n        display: none;\n        background: var(--colorBgSettingsHover);\n        border: 0;\n        top: 0;\n        bottom: 0;\n        left: 0;\n        right: 0;\n        pointer-events: none;\n        > .general-schema-designer-icons {\n          position: absolute;\n          right: 2px;\n          top: 2px;\n          line-height: 16px;\n          pointer-events: all;\n          .ant-space-item {\n            background-color: var(--colorSettings);\n            color: #fff;\n            line-height: 16px;\n            width: 16px;\n            padding-left: 1px;\n            align-self: stretch;\n          }\n        }\n      }\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
const useStyles = (0, __WEBPACK_EXTERNAL_MODULE_antd_style__.createStyles)((param)=>{
    let { css } = param;
    return {
        designer: css(_templateObject()),
        actionDesigner: css(_templateObject1())
    };
});
function useAclCheck(actionPath) {
    const aclCheck = useAclCheckFn();
    return aclCheck(actionPath);
}
function useAclCheckFn() {
    const { data, inResources, getResourceActionParams, getStrategyActionParams } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useACLRolesCheck)();
    const recordPkValue = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useRecordPkValue)();
    const collection = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    function actionAclCheck(actionPath) {
        const resource = collection.resource;
        const parseAction = function(actionPath) {
            arguments.length > 1 && void 0 !== arguments[1] && arguments[1];
            const [resourceName] = actionPath.split(':');
            if (null == data ? void 0 : data.allowAll) return {};
            if (inResources(resourceName)) return getResourceActionParams(actionPath);
            return getStrategyActionParams(actionPath);
        };
        if (!actionPath && resource) actionPath = "".concat(resource, ":create}");
        if (!(null == actionPath ? void 0 : actionPath.includes(':'))) actionPath = "".concat(resource, ":").concat(actionPath);
        if (!actionPath) return true;
        const params = parseAction(actionPath, {
            recordPkValue
        });
        if (!params) return false;
        return true;
    }
    return actionAclCheck;
}
const InternalCreateRecordAction = (props, ref)=>{
    const [visible, setVisible] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const collection = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const [currentCollection, setCurrentCollection] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(collection.name);
    const [currentCollectionDataSource, setCurrentCollectionDataSource] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(collection.dataSource);
    const linkageRules = (null == fieldSchema ? void 0 : fieldSchema['x-linkage-rules']) || [];
    const values = (0, __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.useRecord)();
    const ctx = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useActionContext)();
    const variables = (0, __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__.useVariables)();
    const { styles } = useStyles();
    const localVariables = (0, __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__.useLocalVariables)({
        currentForm: {
            values
        }
    });
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        field.stateOfLinkageRules = {};
        linkageRules.filter((k)=>!k.disabled).forEach((v)=>{
            var _v_actions;
            null === (_v_actions = v.actions) || void 0 === _v_actions || _v_actions.forEach((h)=>{
                (0, __WEBPACK_EXTERNAL_MODULE__schema_component_antd_action_utils_mjs__.linkageAction)({
                    operator: h.operator,
                    field,
                    condition: v.condition,
                    variables,
                    localVariables
                });
            });
        });
    }, [
        field,
        linkageRules,
        localVariables,
        variables
    ]);
    const internalRef = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.createRef)();
    const buttonRef = (0, __WEBPACK_EXTERNAL_MODULE_rc_util_lib_ref__.composeRef)(ref, internalRef);
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
        className: styles.actionDesignerCss,
        ref: buttonRef,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.ActionContextProvider, {
            value: {
                ...ctx,
                visible,
                setVisible
            },
            children: [
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(CreateAction, {
                    ...props,
                    onClick: (collectionData)=>{
                        setVisible(true);
                        setCurrentCollection(collectionData.name);
                        setCurrentCollectionDataSource(collectionData.dataSource);
                    }
                }),
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.CollectionProvider_deprecated, {
                    name: currentCollection,
                    dataSource: currentCollectionDataSource,
                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.RecursionField, {
                        schema: fieldSchema,
                        basePath: field.address,
                        onlyRenderProperties: true
                    })
                })
            ]
        })
    });
};
function getLinkageCollection(str, form, field) {
    const variablesCtx = {
        $form: form.values,
        $iteration: form.values
    };
    if (str.includes('$iteration')) {
        const path = field.path.segments.concat([]);
        path.splice(-2);
        str = str.replace('$iteration.', "$iteration.".concat(path.join('.'), "."));
        const data = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_common_utils_uitls_mjs__.parseVariables)(str, variablesCtx);
        return data;
    }
    {
        const data = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_common_utils_uitls_mjs__.parseVariables)(str, {
            $form: form.values
        });
        return data;
    }
}
const CreateAction = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    var _fieldSchema_xcomponentprops;
    const { onClick } = props;
    const collection = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const variables = (0, __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__.useVariables)();
    const aclCheck = useAclCheckFn();
    const enableChildren = fieldSchema['x-enable-children'] || [];
    const allowAddToCurrent = null == fieldSchema ? void 0 : fieldSchema['x-allow-add-to-current'];
    const linkageFromForm = null == fieldSchema ? void 0 : null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops['linkageFromForm'];
    const componentType = 'danger' === field.componentProps.type ? void 0 : field.componentProps.type || 'primary';
    const { getChildrenCollections } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const totalChildCollections = getChildrenCollections(collection.name);
    const inheritsCollections = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>enableChildren.map((k)=>{
            if (!k) return;
            const childCollection = totalChildCollections.find((j)=>j.name === k.collection);
            if (!childCollection) return;
            return {
                ...childCollection.getOptions(),
                title: k.title || childCollection.title
            };
        }).filter((v)=>v && aclCheck("".concat(v.name, ":create"))), [
        enableChildren,
        totalChildCollections
    ]);
    const linkageRules = (null == fieldSchema ? void 0 : fieldSchema['x-linkage-rules']) || [];
    const values = (0, __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.useRecord)();
    const localVariables = (0, __WEBPACK_EXTERNAL_MODULE__variables_index_mjs__.useLocalVariables)({
        currentForm: {
            values
        }
    });
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useCompile)();
    const { designable } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useDesignable)();
    const { styles } = useStyles();
    const icon = props.icon || null;
    const menuItems = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>inheritsCollections.map((option)=>({
                key: option.name,
                label: compile(option.title),
                onClick: ()=>null == onClick ? void 0 : onClick(option)
            })), [
        inheritsCollections,
        onClick
    ]);
    const menu = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>({
            items: menuItems
        }), [
        menuItems
    ]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        field.stateOfLinkageRules = {};
        linkageRules.filter((k)=>!k.disabled).forEach((v)=>{
            var _v_actions;
            null === (_v_actions = v.actions) || void 0 === _v_actions || _v_actions.forEach((h)=>{
                (0, __WEBPACK_EXTERNAL_MODULE__schema_component_antd_action_utils_mjs__.linkageAction)({
                    operator: h.operator,
                    field,
                    condition: v.condition,
                    variables,
                    localVariables
                });
            });
        });
    }, [
        field,
        linkageRules,
        localVariables,
        variables
    ]);
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
        className: styles.actionDesigner,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(FinallyButton, {
            inheritsCollections,
            linkageFromForm,
            allowAddToCurrent,
            props,
            componentType,
            menu,
            onClick,
            collection,
            icon,
            field,
            form,
            designable
        })
    });
}, {
    displayName: 'CreateAction'
});
function FinallyButton(param) {
    let { inheritsCollections, linkageFromForm, allowAddToCurrent, props, componentType, menu, onClick, collection, icon, field, form, designable } = param;
    var _field_data, _field_data1;
    const { getCollection } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    if ((null == inheritsCollections ? void 0 : inheritsCollections.length) > 0) {
        var _field_data2, _field_data3;
        if (!linkageFromForm) return void 0 === allowAddToCurrent || allowAddToCurrent ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Dropdown.Button, {
            "aria-label": props['aria-label'],
            danger: props.danger,
            type: componentType,
            icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.DownOutlined, {}),
            buttonsRender: (param)=>{
                let [leftButton, rightButton] = param;
                return [
                    /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].cloneElement(leftButton, {
                        style: null == props ? void 0 : props.style
                    }),
                    /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].cloneElement(rightButton, {
                        loading: false,
                        style: null == props ? void 0 : props.style
                    })
                ];
            },
            menu: menu,
            onClick: (info)=>{
                null == onClick || onClick(collection);
            },
            children: [
                icon,
                props.children
            ]
        }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Dropdown, {
            menu: menu,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
                "aria-label": props['aria-label'],
                icon: icon,
                type: componentType,
                danger: props.danger,
                style: null == props ? void 0 : props.style,
                children: [
                    props.children,
                    " ",
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.DownOutlined, {})
                ]
            })
        });
        return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
            "aria-label": props['aria-label'],
            type: componentType,
            disabled: field.disabled,
            danger: props.danger,
            icon: icon,
            onClick: (info)=>{
                const collectionName = getLinkageCollection(linkageFromForm, form, field);
                const targetCollectionName = inheritsCollections.find((v)=>v.name === collectionName) ? collectionName : collection.name;
                const targetCollection = getCollection(targetCollectionName);
                null == onClick || onClick(targetCollection);
            },
            style: {
                display: !designable && (null == field ? void 0 : null === (_field_data2 = field.data) || void 0 === _field_data2 ? void 0 : _field_data2.hidden) && 'none',
                opacity: designable && (null == field ? void 0 : null === (_field_data3 = field.data) || void 0 === _field_data3 ? void 0 : _field_data3.hidden) && 0.1
            },
            children: props.children
        });
    }
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
        ...props,
        "aria-label": props['aria-label'],
        type: componentType,
        disabled: field.disabled,
        danger: props.danger,
        icon: icon,
        onClick: (info)=>{
            null == onClick || onClick(collection);
        },
        style: {
            ...null == props ? void 0 : props.style,
            display: !designable && (null == field ? void 0 : null === (_field_data = field.data) || void 0 === _field_data ? void 0 : _field_data.hidden) && 'none',
            opacity: designable && (null == field ? void 0 : null === (_field_data1 = field.data) || void 0 === _field_data1 ? void 0 : _field_data1.hidden) && 0.1
        },
        children: props.children
    });
}
const CreateRecordAction = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.forwardRef)(InternalCreateRecordAction);
export { CreateAction, CreateRecordAction, useAclCheck };
