"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    fetchTemplateData: ()=>fetchTemplateData,
    Templates: ()=>Templates
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const client_namespaceObject = require("@tachybase/utils/client");
const external_antd_namespaceObject = require("antd");
const external_lodash_namespaceObject = require("lodash");
var external_lodash_default = /*#__PURE__*/ __webpack_require__.n(external_lodash_namespaceObject);
const external_react_i18next_namespaceObject = require("react-i18next");
const index_js_namespaceObject = require("../__builtins__/index.js");
const external_api_client_index_js_namespaceObject = require("../../../api-client/index.js");
const external_block_provider_index_js_namespaceObject = require("../../../block-provider/index.js");
const FormBlockProvider_js_namespaceObject = require("../../../block-provider/FormBlockProvider.js");
const external_collection_manager_index_js_namespaceObject = require("../../../collection-manager/index.js");
const FormDataTemplates_js_namespaceObject = require("../../../schema-settings/DataTemplates/FormDataTemplates.js");
const external_remote_select_index_js_namespaceObject = require("../remote-select/index.js");
const useDataTemplates = ()=>{
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const { duplicateData } = (0, FormBlockProvider_js_namespaceObject.useFormBlockContext)();
    const { getCollectionJoinField } = (0, external_collection_manager_index_js_namespaceObject.useCollectionManager_deprecated)();
    if (duplicateData) return duplicateData;
    const { items = [], display = true } = findDataTemplates(fieldSchema);
    items.forEach((item)=>{
        try {
            var _item_fields;
            item.fields = null === (_item_fields = item.fields) || void 0 === _item_fields ? void 0 : _item_fields.map((field)=>{
                const joinField = getCollectionJoinField("".concat(item.collection, ".").concat(field));
                if (joinField) return field;
                return '';
            }).filter(Boolean);
        } catch (err) {
            (0, client_namespaceObject.error)(err);
            item.fields = [];
        }
    });
    const templates = [
        {
            key: 'none',
            title: t('None')
        }
    ].concat(items.map((t, i)=>({
            key: i,
            ...t,
            isLeaf: null !== t.dataId && void 0 !== t.dataId,
            titleCollectionField: (null == t ? void 0 : t.titleField) && getCollectionJoinField("".concat(t.collection, ".").concat(t.titleField))
        })));
    const defaultTemplate = items.find((item)=>item.default);
    return {
        templates,
        display,
        defaultTemplate,
        enabled: items.length > 0 && items.every((item)=>item.dataId || item.dataScope)
    };
};
const Templates = (param)=>{
    let { style = {}, form } = param;
    const { token } = (0, index_js_namespaceObject.useToken)();
    const { templates, display, enabled, defaultTemplate } = useDataTemplates();
    const { getCollectionJoinField } = (0, external_collection_manager_index_js_namespaceObject.useCollectionManager_deprecated)();
    const templateOptions = (0, FormDataTemplates_js_namespaceObject.compatibleDataId)(templates);
    const [targetTemplate, setTargetTemplate] = (0, external_react_namespaceObject.useState)((null == defaultTemplate ? void 0 : defaultTemplate.key) || 'none');
    const [targetTemplateData, setTemplateData] = (0, external_react_namespaceObject.useState)(null);
    const api = (0, external_api_client_index_js_namespaceObject.useAPIClient)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (enabled && defaultTemplate) {
            form.__template = true;
            if ('duplicate' === defaultTemplate.key) handleTemplateDataChange(defaultTemplate.dataId, defaultTemplate);
        }
    }, []);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (!(null == templateOptions ? void 0 : templateOptions.some((v)=>v.key === targetTemplate))) handleTemplateChange('none');
    }, [
        templateOptions
    ]);
    const wrapperStyle = (0, external_react_namespaceObject.useMemo)(()=>({
            display: 'flex',
            alignItems: 'center',
            backgroundColor: token.colorFillAlter,
            padding: '1em',
            ...style
        }), [
        style,
        token.colorFillAlter
    ]);
    const labelStyle = (0, external_react_namespaceObject.useMemo)(()=>({
            fontSize: token.fontSize,
            fontWeight: 'bold',
            whiteSpace: 'nowrap',
            marginRight: token.marginXS
        }), [
        token.fontSize,
        token.marginXS
    ]);
    const handleTemplateChange = (0, external_react_namespaceObject.useCallback)(async (value)=>{
        setTargetTemplate(value);
        setTemplateData(null);
        null == form || form.reset();
    }, []);
    const handleTemplateDataChange = (0, external_react_namespaceObject.useCallback)(async (value, option)=>{
        const template = {
            ...option,
            dataId: value
        };
        setTemplateData(option);
        fetchTemplateData(api, template, t).then((data)=>{
            if (form && data) {
                form.reset();
                form.__template = true;
                (0, client_namespaceObject.forEach)(data, (value, key)=>{
                    if (value) {
                        var _form_setInitialValuesIn;
                        form.values[key] = value;
                        null == form || null === (_form_setInitialValuesIn = form.setInitialValuesIn) || void 0 === _form_setInitialValuesIn || _form_setInitialValuesIn.call(form, key, value);
                    }
                });
            }
            return data;
        }).catch((err)=>{
            console.error(err);
        });
    }, []);
    if (!enabled || !display) return null;
    const template = null == templateOptions ? void 0 : templateOptions.find((v)=>v.key === targetTemplate);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
        style: wrapperStyle,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_antd_namespaceObject.Space, {
            wrap: true,
            children: [
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("label", {
                    style: labelStyle,
                    children: [
                        t('Data template'),
                        ": "
                    ]
                }),
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Select, {
                    role: "button",
                    "data-testid": "select-form-data-template",
                    popupMatchSelectWidth: false,
                    options: templateOptions,
                    fieldNames: {
                        label: 'title',
                        value: 'key'
                    },
                    value: targetTemplate,
                    onChange: handleTemplateChange
                }),
                'none' !== targetTemplate && template && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_remote_select_index_js_namespaceObject.RemoteSelect, {
                    style: {
                        width: 220
                    },
                    fieldNames: {
                        label: null == template ? void 0 : template.titleField,
                        value: 'id'
                    },
                    target: null == template ? void 0 : template.collection,
                    value: targetTemplateData,
                    objectValue: true,
                    service: {
                        resource: null == template ? void 0 : template.collection,
                        params: {
                            filter: null == template ? void 0 : template.dataScope
                        }
                    },
                    onChange: (value)=>handleTemplateDataChange(null == value ? void 0 : value.id, {
                            ...value,
                            ...template
                        }),
                    targetField: getCollectionJoinField("".concat(null == template ? void 0 : template.collection, ".").concat(template.titleField))
                })
            ]
        })
    });
};
function findDataTemplates(fieldSchema) {
    const formSchema = (0, external_block_provider_index_js_namespaceObject.findFormBlock)(fieldSchema);
    if (formSchema) return external_lodash_default().cloneDeep(formSchema['x-data-templates']) || {};
    return {};
}
async function fetchTemplateData(api, template, t) {
    if (0 === template.fields.length || !template.dataId) return;
    return api.resource(template.collection).get({
        filterByTk: template.dataId,
        fields: template.fields,
        isTemplate: true
    }).then((data)=>{
        var _data_data;
        return null === (_data_data = data.data) || void 0 === _data_data ? void 0 : _data_data.data;
    });
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
