import $i18n from '../../locales/i18n.js';
import React from 'react';
import { event as eventBus } from '@ice/stark-data';
import { buildCnAiListEventNames, EVENT_NAMES, normalizeCnAiListInstanceKey, } from '../../cn-ai-agent/constants/event-constants.js';
import { createFieldMapSetter } from './setter/create-field-map-setter.js';
import { CnAiTable } from '../../components';
import { getId } from '../../utils/index.js';
import { isBirda, isBirdaEdit } from '../../utils/env/index.js';
import { setLowcodeConfig } from '../../hooks/index.js';
import { useSchemaUpdate } from './hooks/use-schema-update.js';
import './cn-ai-table-plugin.scss';
/**
 * 内部包装：事件、`fieldMap`、`remote` / 分页等；视图数据由表格内 {@link useViewsConfigs}（低码 getTableView / URL / 开放平台）统一获取。
 */
const CnAiTableWithViews = ({ InnerProps, fieldMapData }) => {
    // 从 aiConfig 中获取配置
    const aiConfig = (InnerProps === null || InnerProps === void 0 ? void 0 : InnerProps.aiConfig) || {};
    // 表格唯一ID：使用公共方法，鸟搭用 modelCode，专业版用配置 id 或 pageId
    const tableId = (aiConfig === null || aiConfig === void 0 ? void 0 : aiConfig.id) || getId(aiConfig === null || aiConfig === void 0 ? void 0 : aiConfig.id);
    console.log('innerProps', InnerProps, 'fieldMapData', fieldMapData, 'tableId', tableId);
    const listEventNames = React.useMemo(() => buildCnAiListEventNames(normalizeCnAiListInstanceKey(String(tableId !== null && tableId !== void 0 ? tableId : ''))), [tableId]);
    React.useEffect(() => {
        if (tableId != null && String(tableId).trim() !== '') {
            const payload = { tableId: String(tableId).trim() };
            eventBus.emit(listEventNames.TABLE_ID_RESOLVED, payload);
            // 页面级未配 aiConfig.id 时，Agent 页先落在默认命名空间；表格在「真实」实例 id 上发事件，
            // 须同步一份到默认频道，否则页面收不到 TABLE_ID_RESOLVED、不能与筛选条共频道。
            if (listEventNames.TABLE_ID_RESOLVED !== EVENT_NAMES.TABLE_ID_RESOLVED) {
                eventBus.emit(EVENT_NAMES.TABLE_ID_RESOLVED, payload);
            }
        }
    }, [tableId, listEventNames]);
    // 获取分页配置
    const aiTablePageSetting = (aiConfig === null || aiConfig === void 0 ? void 0 : aiConfig.aiTablePageSetting) || {};
    const pageSizeList = (aiTablePageSetting === null || aiTablePageSetting === void 0 ? void 0 : aiTablePageSetting.pageSizeList) || [100, 500, 1000];
    const defaultPageSize = (aiTablePageSetting === null || aiTablePageSetting === void 0 ? void 0 : aiTablePageSetting.defaultPageSize) || 1000;
    // 使用自定义 Hook 处理 schema 更新事件
    useSchemaUpdate(fieldMapData, tableId);
    const rawRecordOperationRequestConfig = aiConfig === null || aiConfig === void 0 ? void 0 : aiConfig.recordOperationRequestConfig;
    const normalizeConfig = (config) => config && { requestConfig: config.requestConfig || config };
    const recordOperationRequestConfig = rawRecordOperationRequestConfig
        ? {
            getOne: normalizeConfig(rawRecordOperationRequestConfig.getOne),
            create: normalizeConfig(rawRecordOperationRequestConfig.create),
            update: normalizeConfig(rawRecordOperationRequestConfig.update),
        }
        : rawRecordOperationRequestConfig;
    // 是否支持批量编辑：根据 _nd_edit_params 是否为空判断，非空则支持
    // const ndEditParams = InnerProps?._nd_edit_params;
    // const supportBatchEdit = isObject(ndEditParams);
    const supportBatchEdit = false;
    return (React.createElement(CnAiTable, { ...InnerProps, id: tableId, enabledFieldTypes: ['ai', 'formula'], viewTypes: {
            smartFollow: true,
        }, fieldMap: {
            type: 'static',
            data: fieldMapData,
        }, rawData: {
            type: 'remote',
            // 专业版场景（!isBirda()）不限制 pageSize，使用用户设置的 pageSize
            // 鸟搭场景保持原有逻辑，使用 pageSize: 100 作为初始值
            requestConfig: isBirda()
                ? { ...InnerProps.remote, data: { currentPage: 1, pageSize: 100 } }
                : InnerProps.remote,
        }, recordOperationRequestConfig: recordOperationRequestConfig, defaultPageSize: defaultPageSize, pageSizeList: pageSizeList, supportBatchEdit: supportBatchEdit }));
};
/**
 * 源码组件插件代码
 * @param props
 * @param context
 */
export const SourceCode = (props, context) => {
    var _a;
    const result = {
        props,
        context,
    };
    if ((_a = props === null || props === void 0 ? void 0 : props.aiConfig) === null || _a === void 0 ? void 0 : _a.enableAITable) {
        result.render = (InnerProps) => {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
            let fieldMapData;
            if (isBirda()) {
                const { _nd_edit_config } = InnerProps || {};
                const lowcodeConfig = (_e = (_d = (_c = (_b = (_a = _nd_edit_config === null || _nd_edit_config === void 0 ? void 0 : _nd_edit_config[0]) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.options) === null || _e === void 0 ? void 0 : _e.config;
                const validLowcodeConfig = lowcodeConfig === null || lowcodeConfig === void 0 ? void 0 : lowcodeConfig.filter((item) => {
                    if (item.componentName === 'CnArrayTableIndex') {
                        return false;
                    }
                    if (item.hidden === true) {
                        return false;
                    }
                    return true;
                });
                // 检查 makeNormalFormSchema 方法是否存在
                const makeNormalFormSchema = (_g = (_f = window === null || window === void 0 ? void 0 : window.cnLowCodeUtils) === null || _f === void 0 ? void 0 : _f.util) === null || _g === void 0 ? void 0 : _g.makeNormalFormSchema;
                if (typeof makeNormalFormSchema === 'function') {
                    const formilySchema = makeNormalFormSchema(validLowcodeConfig);
                    fieldMapData = (_j = (_h = formilySchema === null || formilySchema === void 0 ? void 0 : formilySchema.properties) === null || _h === void 0 ? void 0 : _h.root_CnFormGrid) === null || _j === void 0 ? void 0 : _j.properties;
                }
                else {
                    // 如果方法不存在，尝试从 validLowcodeConfig 中提取字段映射
                    console.warn('makeNormalFormSchema is not available, trying to extract fieldMap from config');
                    // 降级方案：尝试从配置中构建字段映射
                    if (Array.isArray(validLowcodeConfig)) {
                        const extractedFieldMap = {};
                        validLowcodeConfig.forEach((item) => {
                            if (item.dataIndex) {
                                extractedFieldMap[item.dataIndex] = item;
                            }
                        });
                        fieldMapData = extractedFieldMap;
                    }
                    else {
                        fieldMapData = undefined;
                    }
                }
            }
            else {
                const { fieldMap } = InnerProps.aiConfig;
                // 检查 makeNormalFormSchema 方法是否存在
                const makeNormalFormSchema = (_l = (_k = window === null || window === void 0 ? void 0 : window.cnLowCodeUtils) === null || _k === void 0 ? void 0 : _k.util) === null || _l === void 0 ? void 0 : _l.makeNormalFormSchema;
                if (typeof makeNormalFormSchema === 'function') {
                    const formilySchema = makeNormalFormSchema(fieldMap);
                    fieldMapData = (_o = (_m = formilySchema === null || formilySchema === void 0 ? void 0 : formilySchema.properties) === null || _m === void 0 ? void 0 : _m.root_CnFormGrid) === null || _o === void 0 ? void 0 : _o.properties;
                }
                else {
                    // 如果方法不存在，使用 fieldMap 直接作为 fieldMapData
                    console.warn('makeNormalFormSchema is not available, using fieldMap directly');
                    fieldMapData = fieldMap;
                }
            }
            // 鸟搭场景：补充系统字段到 fieldMapData（系统字段不在低码配置中，但需要 fieldMap 支持填色等能力）
            if (isBirda() && fieldMapData && InnerProps.columns) {
                const SYSTEM_FIELD_SCHEMA = {
                    user: {
                        component: 'EmployeeSelect',
                        props: {
                            enableCacheRequest: true,
                            mode: 'single',
                            serviceType: 'cainiao',
                            typeList: ['REGULAR', 'OUTSOURCING', 'CASUAL', 'PARTNER'],
                            useDetailValue: true,
                        },
                    },
                    date: {
                        component: 'DatePicker',
                        props: {},
                    },
                };
                InnerProps.columns.forEach((col) => {
                    if (col.dataIndex && !col.hidden && !fieldMapData[col.dataIndex]) {
                        const schema = SYSTEM_FIELD_SCHEMA[col.format];
                        if (schema) {
                            fieldMapData[col.dataIndex] = {
                                title: col.title,
                                'x-component': schema.component,
                                'x-decorator': 'CnFormItem',
                                'x-component-props': schema.props,
                            };
                        }
                    }
                });
            }
            console.log('CnAiTableWithViews-2', fieldMapData);
            // 设置低码配置，供内部组件通过 useLowcodeConfig 获取 TODO: 后续优化低代码配置的数据轮转
            setLowcodeConfig({
                ...InnerProps,
            });
            // 将 fieldMapData 传递给组件，由组件内部处理 schema 更新事件
            return React.createElement(CnAiTableWithViews, { InnerProps: InnerProps, fieldMapData: fieldMapData || {} });
        };
    }
    return result;
};
/**
 * 生成记录操作的默认请求配置
 * @param operation 操作类型：'getOne' | 'create' | 'update'
 * @returns 默认的请求配置对象
 */
const getDefaultRecordOperationConfig = (operation) => {
    // 获取编辑态下当前页面的 appCode 和 datasetCode
    const { appCode, model } = window.__page__;
    const { modelCode: datasetCode } = model || {};
    if (!datasetCode) {
        return null;
    }
    return {
        url: `/cone/${appCode}/smartapi/runtime/${datasetCode}/${operation}`,
        method: 'POST',
        serviceType: 'http',
    };
};
/**
 * 低码组件配置项扩展部分
 */
export const LowCode = {
    getPrototypeList: () => {
        var _a, _b;
        const DisplayPosition = (_b = (_a = window === null || window === void 0 ? void 0 : window.cnLowCodeUtils) === null || _a === void 0 ? void 0 : _a.enumMap) === null || _b === void 0 ? void 0 : _b.DisplayPosition;
        return [
            {
                name: 'aiConfig',
                title: $i18n.get({ id: 'AIListConfiguration', dm: 'AI列表配置' }),
                display: 'plain',
                setter: () => {
                    var _a, _b, _c;
                    return {
                        componentName: 'ObjectSetter',
                        props: {
                            config: {
                                items: [
                                    {
                                        name: 'enableAITable',
                                        title: $i18n.get({ id: 'OpenTheAIList', dm: '开启AI列表' }),
                                        display: 'inline',
                                        defaultValue: (prop) => { var _a, _b; return (_b = (_a = prop === null || prop === void 0 ? void 0 : prop.getPropValue) === null || _a === void 0 ? void 0 : _a.call(prop, 'enableAITable')) !== null && _b !== void 0 ? _b : false; },
                                        setter: 'BoolSetter',
                                    },
                                    {
                                        name: 'id',
                                        title: $i18n.get({ id: 'UniqueTableID', dm: '表格唯一ID' }),
                                        display: 'inline',
                                        tip: $i18n.get({ id: 'ForSavingViews', dm: '用于保存视图' }),
                                        setter: 'StringSetter',
                                        defaultValue: (prop) => { var _a; return getId((_a = prop === null || prop === void 0 ? void 0 : prop.getPropValue) === null || _a === void 0 ? void 0 : _a.call(prop, 'id')); },
                                        condition: (prop) => {
                                            var _a, _b;
                                            return (_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'enableAITable');
                                        },
                                    },
                                    {
                                        name: 'fieldMap',
                                        title: $i18n.get({ id: 'FieldMapping', dm: '字段映射' }),
                                        display: 'accordion',
                                        onecodeDisplay: 'visible',
                                        condition: (prop) => {
                                            var _a, _b;
                                            return (_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'enableAITable');
                                        },
                                        initialValue: [
                                            (_c = (_b = (_a = window === null || window === void 0 ? void 0 : window.cnLowCodeUtils) === null || _a === void 0 ? void 0 : _a.filterItem) === null || _b === void 0 ? void 0 : _b.getItemInitialValue) === null || _c === void 0 ? void 0 : _c.call(_b, {
                                                position: DisplayPosition === null || DisplayPosition === void 0 ? void 0 : DisplayPosition.filter,
                                            }),
                                        ].filter(Boolean),
                                        setter: createFieldMapSetter(),
                                    },
                                    {
                                        name: 'recordOperationRequestConfig',
                                        title: $i18n.get({
                                            id: 'RecordOperationRequestConfigurat_1367716067',
                                            dm: '记录操作请求配置',
                                        }),
                                        display: 'plain',
                                        condition: (prop) => {
                                            var _a, _b;
                                            // 只在鸟搭编辑态下显示
                                            return isBirdaEdit && ((_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'enableAITable'));
                                        },
                                        setter: () => {
                                            return {
                                                componentName: 'ObjectSetter',
                                                props: {
                                                    config: {
                                                        items: [
                                                            {
                                                                name: 'getOne',
                                                                title: $i18n.get({ id: 'GetASingleRecord', dm: '获取单条记录' }),
                                                                display: 'block',
                                                                defaultValue: () => getDefaultRecordOperationConfig('getOne'),
                                                                setter: {
                                                                    componentName: 'ServiceChoiceSetter',
                                                                    props: {
                                                                        buttonText: $i18n.get({
                                                                            id: 'SelectRequestAPI',
                                                                            dm: '选择请求API',
                                                                        }),
                                                                    },
                                                                },
                                                            },
                                                            {
                                                                name: 'create',
                                                                title: $i18n.get({ id: 'CreateRecord', dm: '创建记录' }),
                                                                display: 'block',
                                                                defaultValue: () => getDefaultRecordOperationConfig('create'),
                                                                setter: {
                                                                    componentName: 'ServiceChoiceSetter',
                                                                    props: {
                                                                        buttonText: $i18n.get({
                                                                            id: 'SelectRequestAPI',
                                                                            dm: '选择请求API',
                                                                        }),
                                                                    },
                                                                },
                                                            },
                                                            {
                                                                name: 'update',
                                                                title: $i18n.get({ id: 'UpdateLog', dm: '更新记录' }),
                                                                display: 'block',
                                                                defaultValue: () => getDefaultRecordOperationConfig('update'),
                                                                setter: {
                                                                    componentName: 'ServiceChoiceSetter',
                                                                    props: {
                                                                        buttonText: $i18n.get({
                                                                            id: 'SelectRequestAPI',
                                                                            dm: '选择请求API',
                                                                        }),
                                                                    },
                                                                },
                                                            },
                                                        ],
                                                    },
                                                },
                                            };
                                        },
                                    },
                                    {
                                        name: 'aiTablePageSetting',
                                        display: 'inline',
                                        title: $i18n.get({ id: 'AIListPagingSettings', dm: 'AI列表分页设置' }),
                                        condition: (prop) => {
                                            var _a, _b;
                                            return (_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'enableAITable');
                                        },
                                        extraProps: {
                                            defaultCollapsed: true,
                                        },
                                        setter: {
                                            componentName: 'ObjectSetter',
                                            props: {
                                                config: {
                                                    items: [
                                                        {
                                                            name: 'paging',
                                                            title: $i18n.get({ id: 'Open', dm: '是否开启' }),
                                                            display: 'inline',
                                                            defaultValue: true,
                                                            setter: 'BoolSetter',
                                                            condition: (prop) => {
                                                                var _a, _b;
                                                                // 只在鸟搭编辑态下显示
                                                                return isBirdaEdit && ((_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'enableAITable'));
                                                            },
                                                        },
                                                        {
                                                            name: 'pageSizeList',
                                                            title: $i18n.get({ id: 'DisplayOptionsPerPage', dm: '每页显示选项' }),
                                                            display: 'none',
                                                            defaultValue: [500, 1000, 5000, 10000],
                                                            condition(prop) {
                                                                var _a, _b;
                                                                return (_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'paging');
                                                            },
                                                            setter: 'JsonSetter',
                                                        },
                                                        {
                                                            name: 'defaultPageSize',
                                                            title: $i18n.get({ id: 'DefaultDisplayPerPage', dm: '默认每页展示' }),
                                                            display: 'inline',
                                                            // 不预填 1000，由运行时在未配置时兜底
                                                            defaultValue: (prop) => { var _a; return (_a = prop === null || prop === void 0 ? void 0 : prop.getPropValue) === null || _a === void 0 ? void 0 : _a.call(prop, 'defaultPageSize'); },
                                                            condition(prop) {
                                                                var _a, _b;
                                                                return (_b = (_a = prop === null || prop === void 0 ? void 0 : prop.parent) === null || _a === void 0 ? void 0 : _a.getPropValue) === null || _b === void 0 ? void 0 : _b.call(_a, 'paging');
                                                            },
                                                            setter: 'NumberSetter',
                                                        },
                                                    ],
                                                },
                                            },
                                        },
                                    },
                                ],
                            },
                        },
                    };
                },
            },
        ];
    },
};
