import $i18n from '../../../../../../locales/i18n.js';
import React from 'react';
import { observer } from 'mobx-react-lite';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { CnButton, CnLoading, CnResult } from '@cainiaofe/cn-ui';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { CnAiChatShell } from '../../../../../../cn-ai-chat-shell';
import { getAliWorkNo } from '../../../../../../cn-ai-agent/utils/user-utils';
import { useSmartFollowDetail } from '../../../common/hooks/use-smart-follow-detail';
import { createSmartFollowChatAdapter, } from '../adapters/smart-follow-chat-adapter';
import { isEditor } from '../../../../../../utils/env/index.js';
import './smart-follow-agent.scss';
export const SmartFollowAgent = observer(({ viewId, onStandardModifiedChange }) => {
    var _a, _b, _c, _d, _e;
    const dataModel = useModel('dataModel');
    const [messages, setMessages] = React.useState([]);
    const adapter = React.useMemo(() => createSmartFollowChatAdapter(dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig), [dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig]);
    const adapterContext = React.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: getAliWorkNo() };
    }, [dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId, dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions]);
    const viewData = React.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.useState(false);
    const { status: previewStatus, summary: previewSummary, refresh: refreshPreview, } = 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 && !isEditor,
        bizRequestConfig: dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig,
    });
    const conversationRef = React.useRef(null);
    const handleEvent = React.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.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.useCallback((e) => {
        e.stopPropagation();
        refreshPreview();
    }, [refreshPreview]);
    const renderPreviewContent = () => {
        if (!firstRow) {
            return React.createElement(CnResult, { type: "empty", title: $i18n.get({ id: 'NoData', dm: '暂无数据' }) });
        }
        if (previewStatus === 'idle') {
            return React.createElement(CnResult, { type: "empty" });
        }
        if (previewStatus === 'loading') {
            return (React.createElement("div", { className: "preview-loading" },
                React.createElement(CnLoading, { visible: true })));
        }
        if (previewStatus === 'error') {
            return (React.createElement("div", { className: "preview-error" },
                React.createElement(CnResult, { type: "error", title: previewSummary || $i18n.get({ id: 'PreviewGenerationFailed', dm: '预览生成失败' }) })));
        }
        if (previewStatus === 'done' && !previewSummary) {
            return (React.createElement(CnResult, { type: "empty", title: $i18n.get({ id: 'NoPreviewContent', dm: '暂无预览内容' }) }));
        }
        return (React.createElement("div", { className: "preview-content" },
            React.createElement(ReactMarkdown, { remarkPlugins: [remarkGfm] }, previewSummary)));
    };
    const renderPreview = () => {
        return (React.createElement("div", { className: "smart-follow-agent-preview" },
            React.createElement("div", { className: "preview-header" },
                React.createElement("span", { className: "preview-title" }, $i18n.get({ id: 'PreviewTest', dm: '预览测试' })),
                previewActivated && !isEditor && (React.createElement(CnButton, { size: "small", text: true, className: "refresh-btn", onClick: onRefreshPreview, loading: previewStatus === 'loading' }, $i18n.get({ id: 'RefreshPreview', dm: '刷新预览' })))),
            renderPreviewContent()));
    };
    return (React.createElement("div", { className: "smart-follow-agent" },
        React.createElement("div", { className: "agent-container" },
            React.createElement("div", { className: "chat-section" },
                React.createElement(CnAiChatShell, { adapter: adapter, context: adapterContext, autoInit: !isEditor, initWhen: !!adapterContext.tableId, disableSenderBeforeInit: true, enableHistory: !isEditor, messages: messages, onMessagesChange: setMessages, onEvent: handleEvent, senderProps: {
                        placeholder: $i18n.get({ id: 'TellMeWhatYouWantToDo', dm: '告诉我你想做什么' }),
                        allowRecord: true,
                        autoSize: { minRows: 1, maxRows: 8 },
                        disabled: isEditor,
                    } })),
            React.createElement("div", { className: "preview-section" }, renderPreview()))));
});
export default SmartFollowAgent;
