"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.useFieldCreation = useFieldCreation;
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
/**
 * 字段创建相关逻辑 Hook
 * 处理字段创建、任务请求构建等逻辑
 */
const react_1 = __importStar(require("react"));
const prompt_utils_1 = require("../utils/prompt-utils");
const field_utils_1 = require("../utils/field-utils");
const constants_1 = require("../constants");
/**
 * 字段创建相关逻辑 Hook
 */
function useFieldCreation({ dataModel, viewId, }) {
    /**
     * 创建字段
     */
    const createField = (0, react_1.useCallback)(({ fieldType, fieldLabel, config }) => {
        // 对于 AI 字段，使用 columnCode 作为字段 ID，确保与服务端一致
        // 对于普通字段，生成一个唯一 ID
        const newFieldId = (config === null || config === void 0 ? void 0 : config.columnCode) || `field_${fieldType}_${Date.now()}`;
        const newFieldLabel = (config === null || config === void 0 ? void 0 : config.fieldName) || fieldLabel;
        // 根据字段类型选择对应的图标
        let headerContent = newFieldLabel;
        if ((0, field_utils_1.isAiField)(fieldType)) {
            headerContent = (react_1.default.createElement("span", { style: { display: 'flex', alignItems: 'center', gap: '6px' } },
                react_1.default.createElement("img", { src: constants_1.AI_FIELD_ICON_URL, alt: i18n_1.default.get({ id: 'AIField', dm: 'AI字段' }), style: { width: '16px', height: '16px' } }),
                newFieldLabel));
        }
        else if ((0, field_utils_1.isAgentField)(fieldType)) {
            headerContent = (react_1.default.createElement("span", { style: { display: 'flex', alignItems: 'center', gap: '6px' } },
                react_1.default.createElement("img", { src: constants_1.AGENT_FIELD_ICON_URL, alt: i18n_1.default.get({ id: 'AgentField', dm: 'Agent字段' }), style: { width: '16px', height: '16px' } }),
                newFieldLabel));
        }
        // 添加新列定义
        const isAiOrAgentField = (0, field_utils_1.isAiField)(fieldType) || (0, field_utils_1.isAgentField)(fieldType);
        const newColumn = {
            dataIndex: newFieldId,
            title: newFieldLabel,
            header: headerContent,
            accessorKey: newFieldId,
            ...(isAiOrAgentField && { isAiColumn: true, format: 'ai-generate' }),
            ...(config && { aiConfig: config }),
        };
        dataModel.addColumn(newColumn);
        // 如果是 AI 字段，保存配置到表级 customFields.aiConfig 中
        if (config && isAiOrAgentField) {
            dataModel.setCustomFieldAiConfig(newFieldId, {
                fieldName: config.fieldName,
                aiTaskType: config.aiTaskType,
                targetInfo: config.targetInfo,
                content: config.content,
                model: config.model,
                autoUpdate: config.autoUpdate,
                allowEmptyField: config.allowEmptyField,
                fieldDescription: config.fieldDescription,
                columnCode: config.columnCode || newFieldId,
                fieldType,
            });
        }
        // 获取当前视图配置
        const viewConfig = dataModel.getViewConfig(viewId);
        const currentColumnOrder = viewConfig.columnOrder || [];
        // 更新视图配置（更新 columnOrder）
        // 传入 shouldPersist = true 以立即保存到远程服务器
        dataModel.setViewConfig(viewId, {
            columnOrder: [...currentColumnOrder, newFieldId],
        }, true);
        // 为所有数据行添加新字段的空值
        const newData = dataModel.rawData.map((row) => ({
            ...row,
            [newFieldId]: '',
        }));
        dataModel.setRawData(newData);
    }, [dataModel, viewId]);
    /**
     * 构建任务请求参数
     */
    const buildTaskRequests = (0, react_1.useCallback)((columnCode, targetRows, config) => {
        const variables = (0, prompt_utils_1.parsePromptVariables)(config.targetInfo);
        const allColumns = dataModel.columnDefinitions || [];
        const processedColumnMap = dataModel.processedColumnMap || new Map();
        const requests = [];
        let skippedCount = 0;
        targetRows.forEach((row, rowIndex) => {
            const rowKey = dataModel.getRowKeyStrict(row);
            if (rowKey == null) {
                skippedCount += 1;
                return;
            }
            requests.push({
                columnCode,
                rowId: String(rowKey),
                promptParams: (0, prompt_utils_1.buildPromptParamsWithExtractor)(row, variables, allColumns, processedColumnMap, rowIndex),
            });
        });
        // if (process.env.NODE_ENV !== 'production' && skippedCount > 0) {
        //   // eslint-disable-next-line no-console
        //   console.warn(
        //     `[cn-ai-table] useFieldCreation.buildTaskRequests: ${skippedCount} row(s) skipped because primaryKey value is missing.`,
        //   );
        // }
        return requests;
    }, [dataModel]);
    return {
        createField,
        buildTaskRequests,
    };
}
