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_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__builtins_index_mjs__ from "../__builtins__/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__block_provider_index_mjs__ from "../../../block-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__block_provider_FormBlockProvider_mjs__ from "../../../block-provider/FormBlockProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_settings_DataTemplates_FormDataTemplates_mjs__ from "../../../schema-settings/DataTemplates/FormDataTemplates.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__remote_select_index_mjs__ from "../remote-select/index.mjs";
const useDataTemplates = ()=>{
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const { duplicateData } = (0, __WEBPACK_EXTERNAL_MODULE__block_provider_FormBlockProvider_mjs__.useFormBlockContext)();
    const { getCollectionJoinField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.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, __WEBPACK_EXTERNAL_MODULE__builtins_index_mjs__.useToken)();
    const { templates, display, enabled, defaultTemplate } = useDataTemplates();
    const { getCollectionJoinField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const templateOptions = (0, __WEBPACK_EXTERNAL_MODULE__schema_settings_DataTemplates_FormDataTemplates_mjs__.compatibleDataId)(templates);
    const [targetTemplate, setTargetTemplate] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)((null == defaultTemplate ? void 0 : defaultTemplate.key) || 'none');
    const [targetTemplateData, setTemplateData] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(null);
    const api = (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.useAPIClient)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (enabled && defaultTemplate) {
            form.__template = true;
            if ('duplicate' === defaultTemplate.key) handleTemplateDataChange(defaultTemplate.dataId, defaultTemplate);
        }
    }, []);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (!(null == templateOptions ? void 0 : templateOptions.some((v)=>v.key === targetTemplate))) handleTemplateChange('none');
    }, [
        templateOptions
    ]);
    const wrapperStyle = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>({
            display: 'flex',
            alignItems: 'center',
            backgroundColor: token.colorFillAlter,
            padding: '1em',
            ...style
        }), [
        style,
        token.colorFillAlter
    ]);
    const labelStyle = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>({
            fontSize: token.fontSize,
            fontWeight: 'bold',
            whiteSpace: 'nowrap',
            marginRight: token.marginXS
        }), [
        token.fontSize,
        token.marginXS
    ]);
    const handleTemplateChange = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)(async (value)=>{
        setTargetTemplate(value);
        setTemplateData(null);
        null == form || form.reset();
    }, []);
    const handleTemplateDataChange = (0, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_utils_client__.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, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
        style: wrapperStyle,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Space, {
            wrap: true,
            children: [
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("label", {
                    style: labelStyle,
                    children: [
                        t('Data template'),
                        ": "
                    ]
                }),
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.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, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__remote_select_index_mjs__.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, __WEBPACK_EXTERNAL_MODULE__block_provider_index_mjs__.findFormBlock)(fieldSchema);
    if (formSchema) return __WEBPACK_EXTERNAL_MODULE_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;
    });
}
export { Templates, fetchTemplateData };
