"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddFieldButton = AddFieldButton;
const i18n_1 = __importDefault(require("../../../../../../locales/i18n.js"));
const react_1 = __importStar(require("react"));
const classnames_1 = __importDefault(require("classnames"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const stark_data_1 = require("@ice/stark-data");
const mobx_react_simpler_1 = require("../../../../../../utils/mobx-react-simpler/index.js");
const field_selector_1 = require("../../../../../../cn-ai-table/view/components/selectors/field-selector/field-selector");
const cn_domain_popup_1 = require("@cainiaofe/cn-domain-popup");
const hooks_1 = require("../../../../../../cn-ai-table/view/hooks");
const cn_ai_list_event_context_1 = require("../../../../../../cn-ai-agent/context/cn-ai-list-event-context");
const arms_hot_tag_log_1 = require("../../../../../../utils/arms/arms-hot-tag-log.js");
const floating_layer_1 = require("../../../../../../utils/floating-layer.js");
const field_system_1 = require("../../../../../../cn-ai-table/view/field-system");
const types_1 = require("../../../../../../cn-ai-table/types");
function AddFieldButton({ viewId, enableAiFields = true, enableLookup = true, enableFormula = true, }) {
    var _a, _b, _c;
    const cnAiListEventNames = (0, cn_ai_list_event_context_1.useCnAiListEventNames)();
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const [selectorVisible, setSelectorVisible] = (0, react_1.useState)(false);
    const [activeDriverType, setActiveDriverType] = (0, react_1.useState)(null);
    const [selectedFieldLabel, setSelectedFieldLabel] = (0, react_1.useState)('');
    const { saveAiColumn, savingAiColumn, executingColumnTask } = (0, hooks_1.useAiColumns)({
        tableId: dataModel.tableId,
        enabled: enableAiFields,
        bizRequestConfig: {
            aiColumn: (_a = dataModel.bizRequestConfig) === null || _a === void 0 ? void 0 : _a.aiColumn,
            cubePlatform: (_b = dataModel.bizRequestConfig) === null || _b === void 0 ? void 0 : _b.cubePlatform,
        },
    });
    const { registry, orchestrator } = (0, react_1.useMemo)(() => (0, field_system_1.getFieldSystem)(), []);
    const buildContext = (0, react_1.useCallback)(() => {
        var _a;
        return {
            dataModel,
            viewId,
            bizRequestConfig: dataModel.bizRequestConfig,
            lookupFieldConfig: (_a = dataModel.lookupFieldConfig) !== null && _a !== void 0 ? _a : undefined,
            eventBus: { emit: (event, payload) => stark_data_1.event.emit(event, payload) },
            cnAiListEventNames,
            services: {
                aiColumn: {
                    saveAiColumn,
                    savingAiColumn,
                    executingColumnTask,
                },
                lookup: (0, types_1.pickLookupCallbacks)(dataModel.lookupFieldConfig),
            },
        };
    }, [dataModel, viewId, cnAiListEventNames, saveAiColumn, savingAiColumn, executingColumnTask]);
    const selectorItems = (0, react_1.useMemo)(() => {
        let items = registry.getSelectorItems();
        if (!enableAiFields) {
            items = items.filter((item) => item.category !== 'ai' && item.category !== 'agent');
        }
        if (!enableLookup) {
            items = items.filter((item) => item.type !== 'lookup');
        }
        if (!enableFormula) {
            items = items.filter((item) => item.type !== 'formula');
        }
        return items;
    }, [registry, enableAiFields, enableLookup, enableFormula]);
    const resetSelection = (0, react_1.useCallback)(() => {
        setActiveDriverType(null);
        setSelectedFieldLabel('');
    }, []);
    const closeAll = (0, react_1.useCallback)(() => {
        setSelectorVisible(false);
        resetSelection();
    }, [resetSelection]);
    const handleFieldSelect = async (fieldType) => {
        const driver = registry.get(fieldType);
        if (!driver)
            return;
        const meta = driver.getMeta();
        const ui = driver.getUiContribution();
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.addField.selectField',
            name: i18n_1.default.get({ id: 'SelectField', dm: '选择字段' }),
            c6: fieldType,
        });
        if (ui.panelKind === 'inline' && ui.createPanel) {
            setActiveDriverType(fieldType);
            setSelectedFieldLabel(meta.label);
            setSelectorVisible(false);
        }
        else {
            const result = await orchestrator.createField(fieldType, {}, buildContext());
            if (result.success) {
                closeAll();
            }
        }
    };
    const handleDriverPanelSave = async (config) => {
        if (!activeDriverType)
            return;
        const ctx = buildContext();
        const result = await orchestrator.createField(activeDriverType, config, ctx);
        if (result.success) {
            closeAll();
        }
    };
    const handleDriverPanelCancel = () => {
        if (activeDriverType) {
            const driver = registry.get(activeDriverType);
            const meta = driver === null || driver === void 0 ? void 0 : driver.getMeta();
            if ((meta === null || meta === void 0 ? void 0 : meta.category) === 'ai' || (meta === null || meta === void 0 ? void 0 : meta.category) === 'agent') {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.addField.cancelAiField',
                    name: i18n_1.default.get({ id: 'UnaddAIField', dm: '取消添加AI字段' }),
                });
            }
            if ((meta === null || meta === void 0 ? void 0 : meta.type) === 'lookup') {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.addField.cancelLookupField',
                    name: i18n_1.default.get({ id: 'RemoveAddedCitationField', dm: '取消添加引用字段' }),
                });
            }
            if ((meta === null || meta === void 0 ? void 0 : meta.type) === 'formula') {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.addField.cancelFormulaField',
                    name: i18n_1.default.get({ id: 'CancelAddingFormulaField', dm: '取消添加公式字段' }),
                });
            }
        }
        closeAll();
    };
    const isActive = selectorVisible || activeDriverType !== null;
    const handlePopupOpenChange = (visible) => {
        if (!visible) {
            closeAll();
        }
    };
    const activeDriver = activeDriverType ? registry.get(activeDriverType) : null;
    const ActivePanel = (_c = activeDriver === null || activeDriver === void 0 ? void 0 : activeDriver.getUiContribution().createPanel) !== null && _c !== void 0 ? _c : null;
    const triggerButton = (react_1.default.createElement("div", { className: (0, classnames_1.default)('toolbar-add-btn', {
            'toolbar-add-btn-active': isActive,
        }), onClick: (e) => {
            e.stopPropagation();
            if (!isActive) {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.addField.open',
                    name: i18n_1.default.get({ id: 'AddField', dm: '添加字段' }),
                });
            }
            if (activeDriverType) {
                closeAll();
            }
            else {
                setSelectorVisible((visible) => {
                    const nextVisible = !visible;
                    if (nextVisible) {
                        (0, arms_hot_tag_log_1.armsHottagLog)({
                            hottag: 'cn-ai-table.addField.openSelector',
                            name: i18n_1.default.get({ id: 'OpenFieldChooser', dm: '打开字段选择器' }),
                        });
                    }
                    return nextVisible;
                });
            }
        }, style: { cursor: 'pointer' } },
        react_1.default.createElement(cn_ui_1.CnButton, { text: true },
            react_1.default.createElement(cn_ui_1.CnIcon, { type: "add", size: "medium", style: { color: '#fff' } }))));
    const tooltipTrigger = (react_1.default.createElement(cn_ui_1.CnTooltip, { v2: true, triggerType: "hover", align: "b", trigger: triggerButton, popupProps: {
            ...(isActive ? { visible: false } : {}),
            style: { zIndex: floating_layer_1.FLOATING_LAYER_Z_INDEX },
        } },
        react_1.default.createElement("span", { style: { whiteSpace: 'nowrap' } }, i18n_1.default.get({ id: 'AddField', dm: '添加字段' }))));
    return (react_1.default.createElement(cn_domain_popup_1.Popup, { visible: isActive, onVisibleChange: handlePopupOpenChange, container: floating_layer_1.getPopupContainer, trigger: tooltipTrigger, align: "bl", offset: 10 },
        selectorVisible ? (react_1.default.createElement(field_selector_1.FieldSelector, { enableAiFields: enableAiFields, items: selectorItems, onSelect: handleFieldSelect })) : null,
        ActivePanel && activeDriverType ? (react_1.default.createElement(ActivePanel, { fieldType: activeDriverType, fieldLabel: selectedFieldLabel, context: buildContext(), onSave: handleDriverPanelSave, onCancel: handleDriverPanelCancel })) : null));
}
