import $i18n from '../../../../../locales/i18n.js';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useModel } from '../../../../../utils/mobx-react-simpler/index.js';
import { TaskDetailView } from '../../common/task-detail-view';
import { SvgIcon } from '../../icons';
import { CnDialog, CnLoading, CnMessage } from '@cainiaofe/cn-ui';
import { queryFollowOrderStandard } from '../../../../../cn-ai-table/view/services/ai-smart-follow-service';
import { isEditor } from '../../../../../utils/env/index.js';
import { event as eventBus } from '@ice/stark-data';
import { useCnAiListEventNames } from '../../../../../cn-ai-agent/context/cn-ai-list-event-context';
import './smart-follow-view.scss';
import { InitPageView } from './components/init-page-view';
import { SmartFollowAgent } from './components/smart-follow-agent';
export const SmartFollowView = observer(({ viewId, enableSmartFollow = true }) => {
    var _a;
    const cnAiListEventNames = useCnAiListEventNames();
    const dataModel = useModel('dataModel');
    const [selectedMode, setSelectedMode] = useState(null);
    const [agentVisible, setAgentVisible] = useState(false);
    const [standardChecking, setStandardChecking] = useState(() => !isEditor);
    const [hasStandardConfig, setHasStandardConfig] = useState(false);
    const [isStandardModified, setIsStandardModified] = useState(false);
    const isRerunningRef = useRef(false);
    const tableId = (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId) !== null && _a !== void 0 ? _a : '';
    const viewData = dataModel.getViewData(viewId);
    const { loading: smartFollowLoading, needAttentionRowIds, runningTasks, conversationId, } = dataModel.smartFollowState;
    useEffect(() => {
        if (isEditor) {
            setStandardChecking(false);
            return;
        }
        if (!tableId)
            return;
        let cancelled = false;
        const checkStandard = async () => {
            setStandardChecking(true);
            try {
                const res = await queryFollowOrderStandard({ tableId }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig);
                if (cancelled)
                    return;
                const hasConfig = !!(res && res.trim());
                setHasStandardConfig(hasConfig);
            }
            catch {
                if (cancelled)
                    return;
                setHasStandardConfig(false);
            }
            finally {
                if (!cancelled) {
                    setStandardChecking(false);
                }
            }
        };
        checkStandard();
        return () => {
            cancelled = true;
        };
    }, [tableId]);
    useEffect(() => {
        const handler = () => setAgentVisible(true);
        eventBus.on(cnAiListEventNames.OPEN_SMART_FOLLOW_ASSISTANT, handler);
        return () => {
            eventBus.off(cnAiListEventNames.OPEN_SMART_FOLLOW_ASSISTANT, handler);
        };
    }, [cnAiListEventNames]);
    const filteredViewData = useMemo(() => {
        if (!needAttentionRowIds || needAttentionRowIds.length === 0) {
            return [];
        }
        const needAttentionSet = new Set(needAttentionRowIds.map(String));
        return viewData.filter((row) => needAttentionSet.has(String(dataModel.getRowKey(row))));
    }, [viewData, needAttentionRowIds, dataModel]);
    const showLoading = smartFollowLoading || (runningTasks && runningTasks.length > 0);
    const detailSummaryEnabled = !showLoading;
    const titleIcon = (React.createElement("span", { className: "detail-view-detail-title-icon" },
        React.createElement(SvgIcon, { name: "smartUpdate" }),
        React.createElement("span", null, $i18n.get({ id: 'SmartInASingle', dm: '智能跟单中' }))));
    const handleSelectMode = (mode) => {
        if (mode === 'general') {
            setAgentVisible(true);
        }
        else {
            setSelectedMode(mode);
        }
    };
    const handleStandardModifiedChange = useCallback((changed) => {
        setIsStandardModified(changed);
    }, []);
    const handleAgentOk = useCallback(async () => {
        var _a;
        if (isEditor) {
            setAgentVisible(false);
            setIsStandardModified(false);
            return;
        }
        if (isRerunningRef.current)
            return;
        isRerunningRef.current = true;
        try {
            setAgentVisible(false);
            setIsStandardModified(false);
            const { refresh } = dataModel.smartFollowState;
            if (!refresh) {
                CnMessage.warning($i18n.get({
                    id: 'TheCurrentTaskEngineIsNotReadyPl_1676983818',
                    dm: '当前任务引擎未就绪，请返回表格视图后重试',
                }));
                return;
            }
            (_a = dataModel.setSmartFollowState) === null || _a === void 0 ? void 0 : _a.call(dataModel, {
                loading: true,
                needAttentionRowIds: [],
                runningTasks: [],
                conversationId: null,
                refresh,
            });
            refresh({ forcePrompt: true, resetConversation: true });
            CnMessage.success($i18n.get({
                id: 'TheCurrentDocumentaryCriteriaHav_1769742177',
                dm: '当前跟单标准已发生变化，正在重新分析数据中。',
            }));
            if (tableId) {
                const res = await queryFollowOrderStandard({ tableId }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig);
                const hasConfig = !!(res && res.trim());
                setHasStandardConfig(hasConfig);
            }
        }
        catch (error) {
            CnMessage.error((error === null || error === void 0 ? void 0 : error.message) ||
                $i18n.get({
                    id: 'SmartDocumentaryRerunFailedPleas_753163449',
                    dm: '智能跟单重跑失败，请稍后重试',
                }));
        }
        finally {
            isRerunningRef.current = false;
        }
    }, [dataModel, tableId]);
    if (standardChecking) {
        return (React.createElement("div", { className: "smart-follow-view-placeholder" },
            React.createElement(CnLoading, { visible: true })));
    }
    if (selectedMode === 'digitalEmployee') {
        return (React.createElement("div", { className: "smart-follow-view-placeholder" }, $i18n.get({
            id: 'DigitalEmployeeModelUnderConstru_177646633',
            dm: '数字员工模式（建设中）',
        })));
    }
    if (hasStandardConfig) {
        return (React.createElement(React.Fragment, null,
            React.createElement(TaskDetailView, { viewId: viewId, viewData: filteredViewData, summaryMode: "smartFollowDetail", detailLayoutVariant: "summaryRightSplit", maxFields: 5, cardListClassName: "smart-follow-card-list", contentClassName: "smart-follow-view-content", containerClassName: "smart-follow-view-container", titleIcon: titleIcon, showRefreshButton: false, loading: showLoading, loadingTip: $i18n.get({
                    id: 'IntelligentDocumentaryTaskProces_1907394148',
                    dm: '智能跟单任务处理中...',
                }), summaryEnabled: enableSmartFollow && detailSummaryEnabled, conversationId: conversationId }),
            React.createElement(CnDialog, { size: "large", cache: true, visible: agentVisible, className: "smart-follow-agent-dialog", onClose: () => setAgentVisible(false), onCancel: () => setAgentVisible(false), onOk: isStandardModified ? handleAgentOk : () => setAgentVisible(false), okProps: {
                    visible: isStandardModified,
                }, title: $i18n.get({ id: 'GenericSmartModeInitialization', dm: '通用智能模式初始化' }) },
                React.createElement(SmartFollowAgent, { viewId: viewId, onStandardModifiedChange: handleStandardModifiedChange }))));
    }
    return (React.createElement(React.Fragment, null,
        React.createElement(InitPageView, { onSelectMode: handleSelectMode }),
        React.createElement(CnDialog, { size: "large", visible: agentVisible, cache: true, className: "smart-follow-agent-dialog", onClose: () => setAgentVisible(false), onCancel: () => setAgentVisible(false), onOk: isStandardModified ? handleAgentOk : () => setAgentVisible(false), okProps: {
                visible: isStandardModified,
            }, title: $i18n.get({ id: 'GenericSmartModeInitialization', dm: '通用智能模式初始化' }) },
            React.createElement(SmartFollowAgent, { viewId: viewId, onStandardModifiedChange: handleStandardModifiedChange }))));
});
export default SmartFollowView;
