import $i18n from '../../../../../locales/i18n.js';
import React from 'react';
import classNames from 'classnames';
import { CnTab, CnTabItem, CnGrid, CnIcon } from '@cainiaofe/cn-ui';
import { DetailNavigation } from './detail-navigation';
import { getFieldComponentType, useFieldIcon } from '../../../utils/field-icon-utils';
import { useAiTableIcons } from '../../../hooks/use-ai-table-icons';
import { AiSummaryContent } from '../ai-summary/ai-summary-content';
import './detail-panel-summary-right.scss';
import dayjs from 'dayjs';
const { CnRow, CnCol } = CnGrid;
const stringifyFallback = (value) => {
    try {
        return JSON.stringify(value);
    }
    catch {
        return String(value);
    }
};
const normalizeDetailValue = (value) => {
    if (value === null || value === undefined || value === '') {
        return '- -';
    }
    if (React.isValidElement(value)) {
        return value;
    }
    if (Array.isArray(value)) {
        const hasNonRenderableItem = value.some((item) => {
            if (item === null || item === undefined)
                return false;
            if (React.isValidElement(item))
                return false;
            return !['string', 'number', 'boolean'].includes(typeof item);
        });
        return hasNonRenderableItem ? stringifyFallback(value) : value;
    }
    if (typeof value === 'object') {
        return stringifyFallback(value);
    }
    return value;
};
/**
 * 详情面板 — 摘要右分栏变体
 * 左侧：标题 + Tabs + 详情字段 + 底部导航
 * 右侧：直出 AI 摘要内容（无 AiSummary 外壳）
 */
export const DetailPanelSummaryRight = ({ title, titleIcon, summaryStatus, summary, gmtModified, onRefreshSummary, useMarkdown = true, showRefreshButton = true, detailColumns, detailItems, selectedRecord, selectedIndex, totalCount, onPrevious, onNext, renderOperateCell, className, fieldMap, }) => {
    const getIcon = useFieldIcon();
    const aiIcons = useAiTableIcons();
    const [activeTab, setActiveTab] = React.useState('basic-info');
    const [asideCollapsed, setAsideCollapsed] = React.useState(false);
    const handleTabChange = React.useCallback((key) => {
        if (key === 'basic-info' || key === 'operation-record') {
            setActiveTab(key);
        }
    }, []);
    React.useEffect(() => {
        setActiveTab('basic-info');
    }, [selectedRecord === null || selectedRecord === void 0 ? void 0 : selectedRecord.id, selectedIndex]);
    const toggleAside = React.useCallback(() => {
        setAsideCollapsed((prev) => !prev);
    }, []);
    // 格式化时间（gmtModified 为空时显示占位符）
    const formattedGmtModified = React.useMemo(() => {
        if (!gmtModified)
            return '-';
        return dayjs(gmtModified).format('YYYY-MM-DD HH:mm:ss');
    }, [gmtModified]);
    return (React.createElement("div", { className: classNames('detail-panel-summary-right', className, {
            'detail-panel-summary-right--collapsed': asideCollapsed,
        }) },
        React.createElement("div", { className: "detail-panel-summary-right__main" },
            React.createElement("div", { className: "detail-panel-summary-right__header" },
                React.createElement("div", { className: "detail-view-detail-title" },
                    React.createElement("span", { className: "detail-view-detail-title-text" }, title),
                    titleIcon && React.createElement("span", { className: "detail-view-detail-title-icon" }, titleIcon)),
                React.createElement("div", { className: "detail-panel-summary-right__toggle", onClick: toggleAside, role: "button", tabIndex: 0 },
                    React.createElement(CnIcon, { type: asideCollapsed ? 'arrow-left' : 'arrow-right', size: "small" }))),
            React.createElement("div", { className: "detail-panel-summary-right__tabs" },
                React.createElement(CnTab, { shape: "pure", activeKey: activeTab, defaultActiveKey: "basic-info", onChange: handleTabChange, style: { height: '100%' } },
                    React.createElement(CnTabItem, { key: "basic-info", title: $i18n.get({ id: 'BasicInformation', dm: '基本信息' }) },
                        React.createElement("div", { className: "detail-view-detail-items" }, detailColumns.length === 0 ? (React.createElement("div", { className: "detail-view-empty" }, $i18n.get({ id: 'NoFieldsToShow', dm: '暂无可展示字段' }))) : (detailItems.map((item) => {
                            let iconSrc;
                            if (item.column.isAiColumn) {
                                iconSrc = aiIcons.FIELD_AI;
                            }
                            else {
                                const componentType = getFieldComponentType(fieldMap, item.column.dataIndex, item.column.format);
                                iconSrc = getIcon(componentType);
                            }
                            return (React.createElement(CnRow, { className: "detail-view-detail-item", key: item.dataIndex, gutter: 0 },
                                React.createElement(CnCol, { span: 6, className: "detail-view-detail-item-label" },
                                    React.createElement("img", { className: "detail-view-detail-item-icon", src: iconSrc, alt: "" }),
                                    React.createElement("span", null, item.title)),
                                React.createElement(CnCol, { span: 18, className: "detail-view-detail-item-value" }, normalizeDetailValue(item.renderedValue))));
                        })))))),
            React.createElement(DetailNavigation, { selectedIndex: selectedIndex, totalCount: totalCount, onPrevious: onPrevious, onNext: onNext, renderOperateCell: renderOperateCell, selectedRecord: selectedRecord })),
        React.createElement("div", { className: classNames('detail-panel-summary-right__aside', {
                'detail-panel-summary-right__aside--collapsed': asideCollapsed,
            }) },
            React.createElement("div", { className: "summary-right-header" },
                React.createElement("div", { className: "summary-right-header-title" }, $i18n.get({ id: 'IntelligentAnalysis', dm: '智能分析' })),
                React.createElement("div", { className: "summary-right-header-time" },
                    $i18n.get({ id: 'LastUpdated', dm: '最近更新：' }),
                    formattedGmtModified)),
            React.createElement("div", { className: "summary-right-content" },
                React.createElement("div", { className: classNames('summary-right-content__body', {
                        'summary-right-content__body--error': summaryStatus === 'error',
                        'summary-right-content__body--loading': summaryStatus === 'loading',
                    }) },
                    React.createElement(AiSummaryContent, { status: summaryStatus, summary: summary, onRefresh: onRefreshSummary, useMarkdown: useMarkdown, showRefreshButton: showRefreshButton, typewriter: true }))))));
};
export default DetailPanelSummaryRight;
