"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SmartFollowView = void 0;
const i18n_1 = __importDefault(require("../../../../../locales/i18n.js"));
const react_1 = __importStar(require("react"));
const mobx_react_lite_1 = require("mobx-react-lite");
const mobx_react_simpler_1 = require("../../../../../utils/mobx-react-simpler/index.js");
const task_detail_view_1 = require("../../common/task-detail-view");
const icons_1 = require("../../icons");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const ai_smart_follow_service_1 = require("../../../../../cn-ai-table/view/services/ai-smart-follow-service");
const env_1 = require("../../../../../utils/env/index.js");
const stark_data_1 = require("@ice/stark-data");
const cn_ai_list_event_context_1 = require("../../../../../cn-ai-agent/context/cn-ai-list-event-context");
require("./smart-follow-view.scss");
const init_page_view_1 = require("./components/init-page-view");
const smart_follow_agent_1 = require("./components/smart-follow-agent");
exports.SmartFollowView = (0, mobx_react_lite_1.observer)(({ viewId, enableSmartFollow = true }) => {
    var _a;
    const cnAiListEventNames = (0, cn_ai_list_event_context_1.useCnAiListEventNames)();
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const [selectedMode, setSelectedMode] = (0, react_1.useState)(null);
    const [agentVisible, setAgentVisible] = (0, react_1.useState)(false);
    const [standardChecking, setStandardChecking] = (0, react_1.useState)(() => !env_1.isEditor);
    const [hasStandardConfig, setHasStandardConfig] = (0, react_1.useState)(false);
    const [isStandardModified, setIsStandardModified] = (0, react_1.useState)(false);
    const isRerunningRef = (0, react_1.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;
    (0, react_1.useEffect)(() => {
        if (env_1.isEditor) {
            setStandardChecking(false);
            return;
        }
        if (!tableId)
            return;
        let cancelled = false;
        const checkStandard = async () => {
            setStandardChecking(true);
            try {
                const res = await (0, ai_smart_follow_service_1.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]);
    (0, react_1.useEffect)(() => {
        const handler = () => setAgentVisible(true);
        stark_data_1.event.on(cnAiListEventNames.OPEN_SMART_FOLLOW_ASSISTANT, handler);
        return () => {
            stark_data_1.event.off(cnAiListEventNames.OPEN_SMART_FOLLOW_ASSISTANT, handler);
        };
    }, [cnAiListEventNames]);
    const filteredViewData = (0, react_1.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_1.default.createElement("span", { className: "detail-view-detail-title-icon" },
        react_1.default.createElement(icons_1.SvgIcon, { name: "smartUpdate" }),
        react_1.default.createElement("span", null, i18n_1.default.get({ id: 'SmartInASingle', dm: '智能跟单中' }))));
    const handleSelectMode = (mode) => {
        if (mode === 'general') {
            setAgentVisible(true);
        }
        else {
            setSelectedMode(mode);
        }
    };
    const handleStandardModifiedChange = (0, react_1.useCallback)((changed) => {
        setIsStandardModified(changed);
    }, []);
    const handleAgentOk = (0, react_1.useCallback)(async () => {
        var _a;
        if (env_1.isEditor) {
            setAgentVisible(false);
            setIsStandardModified(false);
            return;
        }
        if (isRerunningRef.current)
            return;
        isRerunningRef.current = true;
        try {
            setAgentVisible(false);
            setIsStandardModified(false);
            const { refresh } = dataModel.smartFollowState;
            if (!refresh) {
                cn_ui_1.CnMessage.warning(i18n_1.default.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 });
            cn_ui_1.CnMessage.success(i18n_1.default.get({
                id: 'TheCurrentDocumentaryCriteriaHav_1769742177',
                dm: '当前跟单标准已发生变化，正在重新分析数据中。',
            }));
            if (tableId) {
                const res = await (0, ai_smart_follow_service_1.queryFollowOrderStandard)({ tableId }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig);
                const hasConfig = !!(res && res.trim());
                setHasStandardConfig(hasConfig);
            }
        }
        catch (error) {
            cn_ui_1.CnMessage.error((error === null || error === void 0 ? void 0 : error.message) ||
                i18n_1.default.get({
                    id: 'SmartDocumentaryRerunFailedPleas_753163449',
                    dm: '智能跟单重跑失败，请稍后重试',
                }));
        }
        finally {
            isRerunningRef.current = false;
        }
    }, [dataModel, tableId]);
    if (standardChecking) {
        return (react_1.default.createElement("div", { className: "smart-follow-view-placeholder" },
            react_1.default.createElement(cn_ui_1.CnLoading, { visible: true })));
    }
    if (selectedMode === 'digitalEmployee') {
        return (react_1.default.createElement("div", { className: "smart-follow-view-placeholder" }, i18n_1.default.get({
            id: 'DigitalEmployeeModelUnderConstru_177646633',
            dm: '数字员工模式（建设中）',
        })));
    }
    if (hasStandardConfig) {
        return (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(task_detail_view_1.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_1.default.get({
                    id: 'IntelligentDocumentaryTaskProces_1907394148',
                    dm: '智能跟单任务处理中...',
                }), summaryEnabled: enableSmartFollow && detailSummaryEnabled, conversationId: conversationId }),
            react_1.default.createElement(cn_ui_1.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_1.default.get({ id: 'GenericSmartModeInitialization', dm: '通用智能模式初始化' }) },
                react_1.default.createElement(smart_follow_agent_1.SmartFollowAgent, { viewId: viewId, onStandardModifiedChange: handleStandardModifiedChange }))));
    }
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(init_page_view_1.InitPageView, { onSelectMode: handleSelectMode }),
        react_1.default.createElement(cn_ui_1.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_1.default.get({ id: 'GenericSmartModeInitialization', dm: '通用智能模式初始化' }) },
            react_1.default.createElement(smart_follow_agent_1.SmartFollowAgent, { viewId: viewId, onStandardModifiedChange: handleStandardModifiedChange }))));
});
exports.default = exports.SmartFollowView;
