"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SmartFollowAgent = void 0;
const i18n_1 = __importDefault(require("../../../../../../locales/i18n.js"));
const react_1 = __importDefault(require("react"));
const mobx_react_lite_1 = require("mobx-react-lite");
const react_markdown_1 = __importDefault(require("react-markdown"));
const remark_gfm_1 = __importDefault(require("remark-gfm"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const mobx_react_simpler_1 = require("../../../../../../utils/mobx-react-simpler/index.js");
const cn_ai_chat_shell_1 = require("../../../../../../cn-ai-chat-shell");
const user_utils_1 = require("../../../../../../cn-ai-agent/utils/user-utils");
const use_smart_follow_detail_1 = require("../../../common/hooks/use-smart-follow-detail");
const smart_follow_chat_adapter_1 = require("../adapters/smart-follow-chat-adapter");
const env_1 = require("../../../../../../utils/env/index.js");
require("./smart-follow-agent.scss");
exports.SmartFollowAgent = (0, mobx_react_lite_1.observer)(({ viewId, onStandardModifiedChange }) => {
    var _a, _b, _c, _d, _e;
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const [messages, setMessages] = react_1.default.useState([]);
    const adapter = react_1.default.useMemo(() => (0, smart_follow_chat_adapter_1.createSmartFollowChatAdapter)(dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig), [dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig]);
    const adapterContext = react_1.default.useMemo(() => {
        var _a, _b;
        const tableId = (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId) !== null && _a !== void 0 ? _a : '';
        const rawCols = (_b = dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions) !== null && _b !== void 0 ? _b : [];
        const columnDefinitions = rawCols.map((col) => {
            var _a, _b, _c, _d, _e;
            return ({
                code: (_b = (_a = col.dataIndex) !== null && _a !== void 0 ? _a : col.code) !== null && _b !== void 0 ? _b : '',
                title: (_c = col.title) !== null && _c !== void 0 ? _c : '',
                type: (_e = (_d = col.format) !== null && _d !== void 0 ? _d : col.type) !== null && _e !== void 0 ? _e : 'string',
            });
        });
        return { tableId, columnDefinitions, userId: (0, user_utils_1.getAliWorkNo)() };
    }, [dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId, dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions]);
    const viewData = react_1.default.useMemo(() => { var _a; return (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.getViewData(viewId)) !== null && _a !== void 0 ? _a : []; }, [dataModel, viewId]);
    const firstRow = (_a = viewData[0]) !== null && _a !== void 0 ? _a : null;
    const firstRowId = firstRow
        ? String(dataModel.getRowKey(firstRow) || (firstRow === null || firstRow === void 0 ? void 0 : firstRow.id) || '')
        : undefined;
    const [previewActivated, setPreviewActivated] = react_1.default.useState(false);
    const { status: previewStatus, summary: previewSummary, refresh: refreshPreview, } = (0, use_smart_follow_detail_1.useSmartFollowDetail)({
        tableId: (_b = dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId) !== null && _b !== void 0 ? _b : '',
        recordId: firstRowId,
        recordData: firstRow,
        columnDefinitions: (_c = dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions) !== null && _c !== void 0 ? _c : [],
        conversationId: (_e = (_d = dataModel === null || dataModel === void 0 ? void 0 : dataModel.smartFollowState) === null || _d === void 0 ? void 0 : _d.conversationId) !== null && _e !== void 0 ? _e : null,
        viewData,
        enabled: previewActivated && !env_1.isEditor,
        bizRequestConfig: dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig,
    });
    const conversationRef = react_1.default.useRef(null);
    const handleEvent = react_1.default.useCallback((event) => {
        var _a;
        if (event.name === 'init_success' || event.name === 'submit_success') {
            const { conversationId, respMessageId } = ((_a = event.payload) !== null && _a !== void 0 ? _a : {});
            if (conversationId && respMessageId) {
                conversationRef.current = { conversationId, respMessageId };
            }
        }
    }, []);
    react_1.default.useEffect(() => {
        const hasModified = messages.some((m) => { var _a; return m.role === 'assistant' && ((_a = m.meta) === null || _a === void 0 ? void 0 : _a.standardModified) === true; });
        if (hasModified) {
            if (!previewActivated) {
                setPreviewActivated(true);
            }
            onStandardModifiedChange === null || onStandardModifiedChange === void 0 ? void 0 : onStandardModifiedChange(true);
        }
    }, [messages, previewActivated, onStandardModifiedChange]);
    const onRefreshPreview = react_1.default.useCallback((e) => {
        e.stopPropagation();
        refreshPreview();
    }, [refreshPreview]);
    const renderPreviewContent = () => {
        if (!firstRow) {
            return react_1.default.createElement(cn_ui_1.CnResult, { type: "empty", title: i18n_1.default.get({ id: 'NoData', dm: '暂无数据' }) });
        }
        if (previewStatus === 'idle') {
            return react_1.default.createElement(cn_ui_1.CnResult, { type: "empty" });
        }
        if (previewStatus === 'loading') {
            return (react_1.default.createElement("div", { className: "preview-loading" },
                react_1.default.createElement(cn_ui_1.CnLoading, { visible: true })));
        }
        if (previewStatus === 'error') {
            return (react_1.default.createElement("div", { className: "preview-error" },
                react_1.default.createElement(cn_ui_1.CnResult, { type: "error", title: previewSummary || i18n_1.default.get({ id: 'PreviewGenerationFailed', dm: '预览生成失败' }) })));
        }
        if (previewStatus === 'done' && !previewSummary) {
            return (react_1.default.createElement(cn_ui_1.CnResult, { type: "empty", title: i18n_1.default.get({ id: 'NoPreviewContent', dm: '暂无预览内容' }) }));
        }
        return (react_1.default.createElement("div", { className: "preview-content" },
            react_1.default.createElement(react_markdown_1.default, { remarkPlugins: [remark_gfm_1.default] }, previewSummary)));
    };
    const renderPreview = () => {
        return (react_1.default.createElement("div", { className: "smart-follow-agent-preview" },
            react_1.default.createElement("div", { className: "preview-header" },
                react_1.default.createElement("span", { className: "preview-title" }, i18n_1.default.get({ id: 'PreviewTest', dm: '预览测试' })),
                previewActivated && !env_1.isEditor && (react_1.default.createElement(cn_ui_1.CnButton, { size: "small", text: true, className: "refresh-btn", onClick: onRefreshPreview, loading: previewStatus === 'loading' }, i18n_1.default.get({ id: 'RefreshPreview', dm: '刷新预览' })))),
            renderPreviewContent()));
    };
    return (react_1.default.createElement("div", { className: "smart-follow-agent" },
        react_1.default.createElement("div", { className: "agent-container" },
            react_1.default.createElement("div", { className: "chat-section" },
                react_1.default.createElement(cn_ai_chat_shell_1.CnAiChatShell, { adapter: adapter, context: adapterContext, autoInit: !env_1.isEditor, initWhen: !!adapterContext.tableId, disableSenderBeforeInit: true, enableHistory: !env_1.isEditor, messages: messages, onMessagesChange: setMessages, onEvent: handleEvent, senderProps: {
                        placeholder: i18n_1.default.get({ id: 'TellMeWhatYouWantToDo', dm: '告诉我你想做什么' }),
                        allowRecord: true,
                        autoSize: { minRows: 1, maxRows: 8 },
                        disabled: env_1.isEditor,
                    } })),
            react_1.default.createElement("div", { className: "preview-section" }, renderPreview()))));
});
exports.default = exports.SmartFollowAgent;
