/**
 * FormulaFieldDriver —— 公式字段驱动
 *
 * 迁移自：
 * - add-field-button.tsx 中 handleFormulaConfigSave
 * - formula-engine.ts 中 computeFormulaColumn
 * - columnHeaderMenuUtils.ts 中 handleEditFormulaColumn / 公式删除分支
 *
 * 设计要点：
 * 1. 公式字段为同步计算字段（MaterializeMode = 'sync-compute'），
 *    persistMeta 直接写入本地 dataModel，无远程调用。
 * 2. materializeData 调用 computeFormulaColumn 在前端批量求值后写入 rawData。
 * 3. 公式字段全局仅注册一个实例（type = 'formula'），不像 AI 字段按子类型多实例。
 */
import $i18n from '../../../../locales/i18n.js';
import { armsHottagLog } from '../../../../utils/arms/arms-hot-tag-log.js';
import { FormulaFieldPanelAdapter } from './panels/formula-field-panel-adapter';
export class FormulaFieldDriver {
    getMeta() {
        return {
            type: 'formula',
            label: $i18n.get({ id: 'Formula', dm: '公式' }),
            category: 'regular',
            order: 100,
            icon: 'formula',
            iconType: 'custom-iconfont',
            materializeMode: 'sync-compute',
        };
    }
    getUiContribution() {
        const meta = this.getMeta();
        return {
            selectorItem: {
                type: meta.type,
                label: meta.label,
                icon: meta.icon,
                iconType: meta.iconType,
                color: undefined,
                category: meta.category,
                order: meta.order,
            },
            createPanel: FormulaFieldPanelAdapter,
            editPanel: FormulaFieldPanelAdapter,
            panelKind: 'inline',
        };
    }
    createDefaultConfig() {
        return {
            fieldName: '',
            expression: '',
            referencedFields: [],
            columnCode: '',
        };
    }
    validateConfig(config) {
        var _a, _b;
        if (!((_a = config.fieldName) === null || _a === void 0 ? void 0 : _a.trim())) {
            return {
                valid: false,
                error: $i18n.get({ id: 'PleaseEnterAFieldName', dm: '请输入字段名称' }),
            };
        }
        if (!((_b = config.expression) === null || _b === void 0 ? void 0 : _b.trim())) {
            return {
                valid: false,
                error: $i18n.get({ id: 'EnterFormula', dm: '请输入公式' }),
            };
        }
        return { valid: true };
    }
    /** 本地持久化：直接写入 dataModel 的 formulaConfig 分桶（无远程调用） */
    async persistMeta(config, ctx) {
        var _a, _b, _c, _d, _e;
        const columnCode = config.columnCode || `formula_column_${Date.now()}`;
        const formulaConfig = {
            fieldName: config.fieldName,
            expression: config.expression,
            referencedFields: config.referencedFields,
            columnCode,
            fieldType: 'formula',
        };
        ctx.dataModel.setCustomFieldFormulaConfig(columnCode, formulaConfig);
        armsHottagLog({
            hottag: 'cn-ai-table.formulaField.create',
            name: $i18n.get({ id: 'CreateFormulaField', dm: '创建公式字段' }),
            c6: columnCode,
            c7: String((_a = ctx.dataModel.tableId) !== null && _a !== void 0 ? _a : ''),
            c8: String((_c = (_b = config.referencedFields) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0),
            c9: String((_e = (_d = config.expression) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0),
        });
        return {
            id: columnCode,
            type: 'formula',
            name: config.fieldName,
            config: { ...formulaConfig },
            runtime: { mode: 'sync-compute' },
        };
    }
    /** 构建列定义（format = 'formula'），通过 dataModel.addColumn 注册 */
    buildColumnDef(record, ctx) {
        const colDef = {
            dataIndex: record.id,
            title: record.name,
            header: record.name,
            accessorKey: record.id,
            format: 'formula',
        };
        ctx.dataModel.addColumn(colDef);
        return colDef;
    }
    /** 将新列追加到当前视图的 columnOrder */
    attachToView(record, ctx) {
        const viewConfig = ctx.dataModel.getViewConfig(ctx.viewId);
        const currentColumnOrder = viewConfig.columnOrder || [];
        const nextColumnOrder = currentColumnOrder.includes(record.id)
            ? currentColumnOrder
            : [...currentColumnOrder, record.id];
        ctx.dataModel.setViewConfig(ctx.viewId, { columnOrder: nextColumnOrder }, true);
    }
    /**
     * 触发公式列同步求值。
     * 公式重算逻辑已下沉到 dataModel.setRawData 内部（基于 customFields.formulaConfig 全量重算），
     * 这里只需在 formulaConfig 已写入后用当前 rawData 触发一次写入即可。
     */
    async materializeData(_record, _config, ctx) {
        const { dataModel } = ctx;
        dataModel.setRawData(dataModel.rawData);
    }
    /**
     * 编辑公式字段时的更新逻辑。
     */
    async updateMeta(columnId, config, ctx) {
        var _a, _b, _c, _d, _e;
        const formulaConfig = {
            fieldName: config.fieldName,
            expression: config.expression,
            referencedFields: config.referencedFields,
            columnCode: config.columnCode || columnId,
            fieldType: 'formula',
        };
        ctx.dataModel.setCustomFieldFormulaConfig(columnId, formulaConfig);
        const colDefs = ctx.dataModel.columnDefinitions || [];
        const colIdx = colDefs.findIndex((c) => c.dataIndex === columnId);
        if (colIdx >= 0) {
            colDefs[colIdx] = { ...colDefs[colIdx], title: config.fieldName, header: config.fieldName };
            ctx.dataModel.setColumnDefinitions([...colDefs]);
        }
        ctx.dataModel.updateRemoteViews();
        armsHottagLog({
            hottag: 'cn-ai-table.formulaField.update',
            name: $i18n.get({ id: 'UpdateFormulaField', dm: '更新公式字段' }),
            c6: columnId,
            c7: String((_a = ctx.dataModel.tableId) !== null && _a !== void 0 ? _a : ''),
            c8: String((_c = (_b = config.referencedFields) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0),
            c9: String((_e = (_d = config.expression) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0),
        });
        return {
            id: columnId,
            type: 'formula',
            name: config.fieldName,
            config: { ...formulaConfig },
            runtime: { mode: 'sync-compute' },
        };
    }
    async remove(columnId, ctx) {
        var _a, _b, _c, _d, _e;
        const existing = (_b = (_a = ctx.dataModel).getCustomFieldFormulaConfig) === null || _b === void 0 ? void 0 : _b.call(_a, columnId);
        this.removeFieldFromDataModel(columnId, ctx);
        armsHottagLog({
            hottag: 'cn-ai-table.formulaField.delete',
            name: $i18n.get({ id: 'DeleteFormulaField', dm: '删除公式字段' }),
            c6: columnId,
            c7: String((_c = ctx.dataModel.tableId) !== null && _c !== void 0 ? _c : ''),
            c8: existing ? String((_e = (_d = existing.referencedFields) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0) : '',
        });
    }
    /** 从旧 formulaConfig 分桶恢复 FieldRecord，用于编辑面板回填 */
    hydrate(columnId, ctx) {
        var _a, _b;
        const formulaConfig = (_b = (_a = ctx.dataModel).getCustomFieldFormulaConfig) === null || _b === void 0 ? void 0 : _b.call(_a, columnId);
        if (!formulaConfig)
            return undefined;
        return {
            id: columnId,
            type: 'formula',
            name: formulaConfig.fieldName,
            config: formulaConfig,
            runtime: { mode: 'sync-compute' },
        };
    }
    /** 从 dataModel 中彻底清理该字段的所有痕迹（列定义、分桶、各视图配置） */
    removeFieldFromDataModel(columnId, ctx) {
        const { dataModel } = ctx;
        const newColumnDefinitions = dataModel.columnDefinitions.filter((col) => col.dataIndex !== columnId);
        dataModel.setColumnDefinitions(newColumnDefinitions);
        dataModel.removeCustomField(columnId);
        dataModel.viewConfigs.forEach((config, viewId) => {
            const currentColumnOrder = config.columnOrder || [];
            const currentHiddenColumns = config.hiddenColumns || [];
            dataModel.setViewConfig(viewId, {
                columnOrder: currentColumnOrder.filter((col) => col !== columnId),
                hiddenColumns: currentHiddenColumns.filter((col) => col !== columnId),
                filter: (config.filter || []).filter((rule) => rule.field !== columnId),
                sort: (config.sort || []).filter((rule) => rule.field !== columnId),
                group: (config.group || []).filter((rule) => rule.field !== columnId),
                colorFill: (config.colorFill || []).filter((rule) => rule.field !== columnId),
            });
        });
        dataModel.updateRemoteViews();
    }
}
