import $i18n from '../../../../../../../locales/i18n.js';
/**
 * 字段创建相关逻辑 Hook
 * 处理字段创建、任务请求构建等逻辑
 */
import React, { useCallback } from 'react';
import { parsePromptVariables, buildPromptParamsWithExtractor } from '../utils/prompt-utils';
import { isAiField, isAgentField } from '../utils/field-utils';
import { AI_FIELD_ICON_URL, AGENT_FIELD_ICON_URL } from '../constants';
/**
 * 字段创建相关逻辑 Hook
 */
export function useFieldCreation({ dataModel, viewId, }) {
    /**
     * 创建字段
     */
    const createField = 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 (isAiField(fieldType)) {
            headerContent = (React.createElement("span", { style: { display: 'flex', alignItems: 'center', gap: '6px' } },
                React.createElement("img", { src: AI_FIELD_ICON_URL, alt: $i18n.get({ id: 'AIField', dm: 'AI字段' }), style: { width: '16px', height: '16px' } }),
                newFieldLabel));
        }
        else if (isAgentField(fieldType)) {
            headerContent = (React.createElement("span", { style: { display: 'flex', alignItems: 'center', gap: '6px' } },
                React.createElement("img", { src: AGENT_FIELD_ICON_URL, alt: $i18n.get({ id: 'AgentField', dm: 'Agent字段' }), style: { width: '16px', height: '16px' } }),
                newFieldLabel));
        }
        // 添加新列定义
        const isAiOrAgentField = isAiField(fieldType) || 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 = useCallback((columnCode, targetRows, config) => {
        const variables = 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: 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,
    };
}
