From 54b7d9fc89c0dfc73fa4f00154c7733231449015 Mon Sep 17 00:00:00 2001 From: zzlgreat Date: Sun, 21 Dec 2025 23:40:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0Company=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E7=9A=84UI=E4=B8=BAFUI=E9=A3=8E=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.py | 238 ++++++++ src/mocks/handlers/event.js | 103 ++++ .../components/DynamicNews/DynamicNewsCard.js | 44 +- .../components/DynamicNews/EventScrollList.js | 277 +++++---- .../layouts/MainlineTimelineView.js | 537 ++++++++++++++++++ 5 files changed, 1042 insertions(+), 157 deletions(-) create mode 100644 src/views/Community/components/DynamicNews/layouts/MainlineTimelineView.js diff --git a/app.py b/app.py index d7b76b34..d51c5152 100755 --- a/app.py +++ b/app.py @@ -10992,6 +10992,244 @@ def get_hot_events(): return jsonify({'success': False, 'error': str(e)}), 500 +@app.route('/api/events/mainline', methods=['GET']) +def get_events_by_mainline(): + """ + 获取按主线(lv2概念)分组的事件列表 + + 逻辑: + 1. 根据筛选条件获取事件列表 + 2. 通过 related_concepts 表关联概念 + 3. 调用 concept-api/hierarchy 获取概念的 lv2 归属 + 4. 按 lv2 分组返回 + + 参数: + - recent_days: 近N天(默认7天) + - importance: 重要性筛选(S,A,B,C 或 all) + - limit: 每个主线最多返回多少事件(默认20) + + 返回: + { + "success": true, + "data": { + "mainlines": [ + { + "lv2_id": "L2_AI_INFRA", + "lv2_name": "AI基础设施 (算力/CPO/PCB)", + "lv1_name": "TMT (科技/媒体/通信)", + "event_count": 15, + "events": [...] + }, + ... + ], + "total_events": 100, + "ungrouped_count": 5 + } + } + """ + try: + import requests + from datetime import datetime, timedelta + from sqlalchemy.orm import joinedload + from sqlalchemy import exists + + # 获取请求参数 + recent_days = request.args.get('recent_days', 7, type=int) + importance = request.args.get('importance', 'all') + limit_per_mainline = request.args.get('limit', 20, type=int) + + # 计算日期范围 + since_date = datetime.now() - timedelta(days=recent_days) + + # ==================== 1. 获取概念层级映射 ==================== + # 调用 concept-api 获取层级结构 + concept_hierarchy_map = {} # { concept_name: { lv1, lv2, lv1_id, lv2_id } } + + try: + # 内部调用 concept-api + hierarchy_resp = requests.get( + 'http://127.0.0.1:6801/hierarchy', + timeout=5 + ) + if hierarchy_resp.status_code == 200: + hierarchy_data = hierarchy_resp.json() + hierarchy_list = hierarchy_data.get('hierarchy', []) + + # 构建概念名称 -> lv2 映射 + for lv1 in hierarchy_list: + lv1_name = lv1.get('name', '') + lv1_id = lv1.get('id', '') + + for lv2 in lv1.get('children', []): + lv2_name = lv2.get('name', '') + lv2_id = lv2.get('id', '') + + # lv2 直接包含 concepts + for concept in lv2.get('concepts', []): + concept_name = concept if isinstance(concept, str) else concept.get('name', '') + if concept_name: + concept_hierarchy_map[concept_name] = { + 'lv1': lv1_name, + 'lv1_id': lv1_id, + 'lv2': lv2_name, + 'lv2_id': lv2_id + } + + # lv3 children + for lv3 in lv2.get('children', []): + for concept in lv3.get('concepts', []): + concept_name = concept if isinstance(concept, str) else concept.get('name', '') + if concept_name: + concept_hierarchy_map[concept_name] = { + 'lv1': lv1_name, + 'lv1_id': lv1_id, + 'lv2': lv2_name, + 'lv2_id': lv2_id + } + + app.logger.info(f'[mainline] 加载概念层级映射: {len(concept_hierarchy_map)} 个概念') + except Exception as e: + app.logger.warning(f'[mainline] 获取概念层级失败: {e}') + + # ==================== 2. 查询事件及其关联概念 ==================== + query = Event.query.options(joinedload(Event.creator)) + + # 只返回有关联股票的事件 + query = query.filter( + exists().where(RelatedStock.event_id == Event.id) + ) + + # 状态筛选 + query = query.filter(Event.status == 'active') + + # 日期筛选 + query = query.filter(Event.created_at >= since_date) + + # 重要性筛选 + if importance != 'all': + if ',' in importance: + importance_list = [imp.strip() for imp in importance.split(',') if imp.strip()] + query = query.filter(Event.importance.in_(importance_list)) + else: + query = query.filter(Event.importance == importance) + + # 按时间倒序 + query = query.order_by(Event.created_at.desc()) + + # 获取事件(限制总数防止性能问题) + events = query.limit(500).all() + + app.logger.info(f'[mainline] 查询到 {len(events)} 个事件') + + # ==================== 3. 获取事件的关联概念 ==================== + event_ids = [e.id for e in events] + + # 批量查询 related_concepts + related_concepts_query = db.session.query( + RelatedConcept.event_id, + RelatedConcept.concept + ).filter(RelatedConcept.event_id.in_(event_ids)).all() + + # 构建 event_id -> concepts 映射 + event_concepts_map = {} # { event_id: [concept1, concept2, ...] } + for event_id, concept in related_concepts_query: + if event_id not in event_concepts_map: + event_concepts_map[event_id] = [] + event_concepts_map[event_id].append(concept) + + app.logger.info(f'[mainline] 查询到 {len(related_concepts_query)} 条概念关联') + + # ==================== 4. 按 lv2 分组事件 ==================== + mainline_groups = {} # { lv2_id: { info: {...}, events: [...] } } + ungrouped_events = [] + + def find_concept_hierarchy(concept_name): + """查找概念的层级信息(支持模糊匹配)""" + # 精确匹配 + if concept_name in concept_hierarchy_map: + return concept_hierarchy_map[concept_name] + + # 模糊匹配 + for key in concept_hierarchy_map: + if concept_name in key or key in concept_name: + return concept_hierarchy_map[key] + + return None + + for event in events: + concepts = event_concepts_map.get(event.id, []) + + # 找出该事件所属的所有 lv2 + event_lv2s = set() + for concept in concepts: + hierarchy = find_concept_hierarchy(concept) + if hierarchy: + event_lv2s.add((hierarchy['lv2_id'], hierarchy['lv2'], hierarchy['lv1'])) + + # 事件数据 + event_data = { + 'id': event.id, + 'title': event.title, + 'description': event.description, + 'importance': event.importance, + 'created_at': event.created_at.isoformat() if event.created_at else None, + 'related_avg_chg': event.related_avg_chg, + 'related_max_chg': event.related_max_chg, + 'expectation_surprise_score': event.expectation_surprise_score, + 'hot_score': event.hot_score, + 'related_concepts': [{'concept': c} for c in concepts], + 'creator': { + 'username': event.creator.username if event.creator else 'Anonymous' + } + } + + if event_lv2s: + # 添加到每个相关的 lv2 分组 + for lv2_id, lv2_name, lv1_name in event_lv2s: + if lv2_id not in mainline_groups: + mainline_groups[lv2_id] = { + 'lv2_id': lv2_id, + 'lv2_name': lv2_name, + 'lv1_name': lv1_name, + 'events': [] + } + mainline_groups[lv2_id]['events'].append(event_data) + else: + ungrouped_events.append(event_data) + + # ==================== 5. 整理返回数据 ==================== + mainlines = [] + for lv2_id, group in mainline_groups.items(): + # 按时间倒序,限制每组数量 + group['events'] = sorted( + group['events'], + key=lambda x: x['created_at'] or '', + reverse=True + )[:limit_per_mainline] + group['event_count'] = len(group['events']) + mainlines.append(group) + + # 按事件数量排序 + mainlines.sort(key=lambda x: x['event_count'], reverse=True) + + return jsonify({ + 'success': True, + 'data': { + 'mainlines': mainlines, + 'total_events': len(events), + 'mainline_count': len(mainlines), + 'ungrouped_count': len(ungrouped_events) + } + }) + + except Exception as e: + app.logger.error(f'[mainline] 错误: {e}', exc_info=True) + return jsonify({ + 'success': False, + 'error': str(e) + }), 500 + + @app.route('/api/events/keywords/popular', methods=['GET']) def get_popular_keywords(): """获取热门关键词""" diff --git a/src/mocks/handlers/event.js b/src/mocks/handlers/event.js index de4625c1..7306e04f 100644 --- a/src/mocks/handlers/event.js +++ b/src/mocks/handlers/event.js @@ -1585,4 +1585,107 @@ export const eventHandlers = [ ); } }), + + // ==================== 主线模式相关 ==================== + + // 获取按主线(lv2概念)分组的事件列表 + http.get('/api/events/mainline', async ({ request }) => { + await delay(500); + + const url = new URL(request.url); + const recentDays = parseInt(url.searchParams.get('recent_days') || '7', 10); + const importance = url.searchParams.get('importance') || 'all'; + const limitPerMainline = parseInt(url.searchParams.get('limit') || '20', 10); + + console.log('[Mock Event] 获取主线数据:', { recentDays, importance, limitPerMainline }); + + try { + // 生成 mock 事件数据 + const allEvents = generateDynamicNewsEvents(100); + + // 定义 lv2 主线分类 + const mainlineDefinitions = [ + { lv2_id: 'L2_AI_INFRA', lv2_name: 'AI基础设施 (算力/CPO/PCB)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['算力', 'AI', '人工智能', 'CPO', 'PCB', '光模块', '大模型', '智能体'] }, + { lv2_id: 'L2_SEMICONDUCTOR', lv2_name: '半导体 (设计/制造/封测)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['半导体', '芯片', '光刻', 'IC', '晶圆', '封装', '测试'] }, + { lv2_id: 'L2_ROBOT', lv2_name: '机器人 (人形机器人/工业机器人)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['机器人', '人形', '自动化', '工业机器人', '具身智能'] }, + { lv2_id: 'L2_CONSUMER_ELEC', lv2_name: '消费电子 (手机/XR/可穿戴)', lv1_name: 'TMT (科技/媒体/通信)', keywords: ['手机', 'XR', 'VR', 'AR', '可穿戴', '华为', '苹果', '消费电子'] }, + { lv2_id: 'L2_NEW_ENERGY', lv2_name: '新能源 (光伏/储能/电池)', lv1_name: '新能源与环保', keywords: ['光伏', '储能', '电池', '锂电', '新能源', '风电', '清洁能源'] }, + { lv2_id: 'L2_EV', lv2_name: '新能源汽车 (整车/零部件)', lv1_name: '新能源与环保', keywords: ['新能源汽车', '电动车', '智能驾驶', '汽车', '整车', '零部件'] }, + { lv2_id: 'L2_LOW_ALTITUDE', lv2_name: '低空经济 (无人机/eVTOL)', lv1_name: '先进制造', keywords: ['低空', '无人机', 'eVTOL', '飞行', '空域'] }, + { lv2_id: 'L2_MILITARY', lv2_name: '军工 (航空航天/国防)', lv1_name: '先进制造', keywords: ['军工', '国防', '航空', '航天', '卫星', '导弹'] }, + { lv2_id: 'L2_PHARMA', lv2_name: '医药医疗 (创新药/器械)', lv1_name: '医药健康', keywords: ['医药', '医疗', '创新药', '器械', '生物', 'CXO'] }, + { lv2_id: 'L2_FINANCE', lv2_name: '金融 (银行/券商/保险)', lv1_name: '金融', keywords: ['金融', '银行', '券商', '保险', '证券'] }, + ]; + + // 按主线分组事件 + const mainlineGroups = {}; + + allEvents.forEach(event => { + // 从事件的 keywords (related_concepts) 中查找匹配的主线 + const keywords = event.keywords || event.related_concepts || []; + const conceptNames = keywords.map(k => k.concept || k.name || k).join(' '); + const titleAndDesc = `${event.title || ''} ${event.description || ''}`; + const textToMatch = `${conceptNames} ${titleAndDesc}`.toLowerCase(); + + // 匹配主线 + mainlineDefinitions.forEach(mainline => { + const matched = mainline.keywords.some(kw => textToMatch.includes(kw.toLowerCase())); + if (matched) { + if (!mainlineGroups[mainline.lv2_id]) { + mainlineGroups[mainline.lv2_id] = { + lv2_id: mainline.lv2_id, + lv2_name: mainline.lv2_name, + lv1_name: mainline.lv1_name, + events: [] + }; + } + // 避免重复添加 + if (!mainlineGroups[mainline.lv2_id].events.find(e => e.id === event.id)) { + mainlineGroups[mainline.lv2_id].events.push(event); + } + } + }); + }); + + // 转换为数组,限制每组数量,按事件数量排序 + const mainlines = Object.values(mainlineGroups) + .map(group => ({ + ...group, + events: group.events.slice(0, limitPerMainline), + event_count: Math.min(group.events.length, limitPerMainline) + })) + .filter(group => group.event_count > 0) + .sort((a, b) => b.event_count - a.event_count); + + // 统计未分组的事件 + const groupedEventIds = new Set(); + mainlines.forEach(m => m.events.forEach(e => groupedEventIds.add(e.id))); + const ungroupedCount = allEvents.filter(e => !groupedEventIds.has(e.id)).length; + + console.log('[Mock Event] 主线数据生成完成:', { + mainlineCount: mainlines.length, + totalEvents: allEvents.length, + ungroupedCount + }); + + return HttpResponse.json({ + success: true, + data: { + mainlines, + total_events: allEvents.length, + mainline_count: mainlines.length, + ungrouped_count: ungroupedCount + } + }); + } catch (error) { + console.error('[Mock Event] 主线数据获取失败:', error); + return HttpResponse.json( + { + success: false, + error: error.message || '获取主线数据失败' + }, + { status: 500 } + ); + } + }), ]; diff --git a/src/views/Community/components/DynamicNews/DynamicNewsCard.js b/src/views/Community/components/DynamicNews/DynamicNewsCard.js index bdfb7edc..83344ccc 100644 --- a/src/views/Community/components/DynamicNews/DynamicNewsCard.js +++ b/src/views/Community/components/DynamicNews/DynamicNewsCard.js @@ -377,14 +377,18 @@ const [currentMode, setCurrentMode] = useState('vertical'); // 添加防抖:如果已经初始化,不再执行 if (hasInitialized.current) return; - // mainline 模式使用 four-row 的 API 模式(共用数据) - const apiMode = mode === DISPLAY_MODES.MAINLINE ? DISPLAY_MODES.FOUR_ROW : mode; + // ⚡ mainline 模式使用独立 API,不需要通过 Redux 获取数据 + if (mode === DISPLAY_MODES.MAINLINE) { + hasInitialized.current = true; + console.log('%c🚀 [初始加载] 主线模式 - 组件自己调用 /api/events/mainline', 'color: #10B981; font-weight: bold;'); + return; + } // ⚡ 始终获取最新数据,确保用户每次进入页面看到最新事件 hasInitialized.current = true; - console.log('%c🚀 [初始加载] 获取最新事件数据', 'color: #10B981; font-weight: bold;', { mode, apiMode, pageSize }); + console.log('%c🚀 [初始加载] 获取最新事件数据', 'color: #10B981; font-weight: bold;', { mode, pageSize }); dispatch(fetchDynamicNews({ - mode: apiMode, // 传递 API 模式(mainline 映射为 four-row) + mode, per_page: pageSize, pageSize: pageSize, // 传递 pageSize 确保索引计算一致 clearCache: true, @@ -412,14 +416,17 @@ const [currentMode, setCurrentMode] = useState('vertical'); return; } - // mainline 模式使用 four-row 的 API 模式(共用数据) - const apiMode = mode === DISPLAY_MODES.MAINLINE ? DISPLAY_MODES.FOUR_ROW : mode; + // ⚡ mainline 模式使用独立 API,筛选条件变化由 MainlineTimelineView 自己监听 + if (mode === DISPLAY_MODES.MAINLINE) { + console.log('%c🔍 [筛选] 主线模式 - 筛选条件变化由组件自己处理', 'color: #8B5CF6; font-weight: bold;', { filters }); + return; + } - console.log('%c🔍 [筛选] 筛选条件改变,重新请求数据', 'color: #8B5CF6; font-weight: bold;', { filters, mode, apiMode }); + console.log('%c🔍 [筛选] 筛选条件改变,重新请求数据', 'color: #8B5CF6; font-weight: bold;', { filters, mode }); // 筛选条件改变时,清空对应模式的缓存并从第1页开始加载 dispatch(fetchDynamicNews({ - mode: apiMode, // 传递 API 模式(mainline 映射为 four-row) + mode, per_page: pageSize, pageSize: pageSize, clearCache: true, // 清空缓存 @@ -442,6 +449,12 @@ const [currentMode, setCurrentMode] = useState('vertical'); // 监听模式切换 - 如果新模式数据为空,请求数据 useEffect(() => { + // ⚡ mainline 模式使用独立 API,不需要通过 Redux 加载数据 + if (mode === DISPLAY_MODES.MAINLINE) { + console.log('%c🔄 [模式切换] 主线模式 - 由 MainlineTimelineView 组件自己加载数据', 'color: #8B5CF6; font-weight: bold;'); + return; + } + const isDataEmpty = currentMode === 'vertical' ? Object.keys(allCachedEventsByPage || {}).length === 0 : (allCachedEvents?.length || 0) === 0; @@ -449,20 +462,16 @@ const [currentMode, setCurrentMode] = useState('vertical'); if (hasInitialized.current && isDataEmpty) { console.log(`%c🔄 [模式切换] ${mode} 模式数据为空,开始加载`, 'color: #8B5CF6; font-weight: bold;'); - // 🔧 根据 mode 直接计算 per_page,避免使用可能过时的 pageSize prop - // mainline 模式复用 four-row 的分页大小 - const modePageSize = (mode === DISPLAY_MODES.FOUR_ROW || mode === DISPLAY_MODES.MAINLINE) + // 🔧 根据 mode 直接计算 per_page + const modePageSize = mode === DISPLAY_MODES.FOUR_ROW ? PAGINATION_CONFIG.FOUR_ROW_PAGE_SIZE // 30 : PAGINATION_CONFIG.VERTICAL_PAGE_SIZE; // 10 - // mainline 模式使用 four-row 的 API 模式(共用数据) - const apiMode = mode === DISPLAY_MODES.MAINLINE ? DISPLAY_MODES.FOUR_ROW : mode; - - console.log(`%c 计算的 per_page: ${modePageSize}, apiMode: ${apiMode} (mode: ${mode})`, 'color: #8B5CF6;'); + console.log(`%c 计算的 per_page: ${modePageSize} (mode: ${mode})`, 'color: #8B5CF6;'); dispatch(fetchDynamicNews({ - mode: apiMode, // 使用映射后的 API 模式 - per_page: modePageSize, // 使用计算的值,不是 pageSize prop + mode, + per_page: modePageSize, pageSize: modePageSize, clearCache: true, ...filters, // 先展开筛选条件 @@ -662,6 +671,7 @@ const [currentMode, setCurrentMode] = useState('vertical'); { - const scrollContainerRef = useRef(null); +const EventScrollList = React.memo( + ({ + events, + displayEvents, + filters = {}, + loadNextPage, + loadPrevPage, + onFourRowEventClick, + selectedEvent, + onEventSelect, + borderColor, + currentPage, + totalPages, + onPageChange, + loading = false, + error, + mode = "vertical", + hasMore = true, + eventFollowStatus = {}, + onToggleFollow, + virtualizedGridRef, + }) => { + const scrollContainerRef = useRef(null); - // 所有 useColorModeValue 必须在组件顶层调用(不能在条件渲染中) - const timelineBg = useColorModeValue('gray.50', 'gray.700'); - const timelineBorderColor = useColorModeValue('gray.400', 'gray.500'); - const timelineTextColor = useColorModeValue('blue.600', 'blue.400'); + // 所有 useColorModeValue 必须在组件顶层调用(不能在条件渲染中) + const timelineBg = useColorModeValue("gray.50", "gray.700"); + const timelineBorderColor = useColorModeValue("gray.400", "gray.500"); + const timelineTextColor = useColorModeValue("blue.600", "blue.400"); - // 滚动条颜色 - const scrollbarTrackBg = useColorModeValue('#f1f1f1', '#2D3748'); - const scrollbarThumbBg = useColorModeValue('#888', '#4A5568'); - const scrollbarThumbHoverBg = useColorModeValue('#555', '#718096'); + // 滚动条颜色 + const scrollbarTrackBg = useColorModeValue("#f1f1f1", "#2D3748"); + const scrollbarThumbBg = useColorModeValue("#888", "#4A5568"); + const scrollbarThumbHoverBg = useColorModeValue("#555", "#718096"); - const getTimelineBoxStyle = () => { - return { - bg: timelineBg, - borderColor: timelineBorderColor, - borderWidth: '2px', - textColor: timelineTextColor, - boxShadow: 'sm', + const getTimelineBoxStyle = () => { + return { + bg: timelineBg, + borderColor: timelineBorderColor, + borderWidth: "2px", + textColor: timelineTextColor, + boxShadow: "sm", + }; }; - }; - // 重试函数 - const handleRetry = useCallback(() => { - if (onPageChange) { - onPageChange(currentPage); + // 重试函数 + const handleRetry = useCallback(() => { + if (onPageChange) { + onPageChange(currentPage); + } + }, [onPageChange, currentPage]); + + { + /* 事件卡片容器 */ } - }, [onPageChange, currentPage]); + return ( + + {/* 平铺网格模式 - 使用虚拟滚动 + 双向无限滚动 */} + - {/* 事件卡片容器 */} - return ( - - {/* 平铺网格模式 - 使用虚拟滚动 + 双向无限滚动 */} - + {/* 主线时间轴模式 - 按 lv2 概念分组,调用独立 API */} + - {/* 主线分组模式 - 按 lv2 概念分组 */} - - - {/* 纵向分栏模式 */} - - - ); -}); + {/* 纵向分栏模式 */} + + + ); + } +); export default EventScrollList; diff --git a/src/views/Community/components/DynamicNews/layouts/MainlineTimelineView.js b/src/views/Community/components/DynamicNews/layouts/MainlineTimelineView.js new file mode 100644 index 00000000..c820fce2 --- /dev/null +++ b/src/views/Community/components/DynamicNews/layouts/MainlineTimelineView.js @@ -0,0 +1,537 @@ +// src/views/Community/components/DynamicNews/layouts/MainlineTimelineView.js +// 主线时间轴布局组件 - 按 lv2 概念分组展示事件 + +import React, { + useState, + useEffect, + forwardRef, + useImperativeHandle, + useCallback, +} from "react"; +import { + Box, + VStack, + HStack, + Text, + Badge, + Flex, + Icon, + Collapse, + Spinner, + Center, + IconButton, + useColorModeValue, + Tooltip, + Grid, +} from "@chakra-ui/react"; +import { + ChevronDownIcon, + ChevronRightIcon, + RepeatIcon, + TimeIcon, +} from "@chakra-ui/icons"; +import { FiTrendingUp, FiClock, FiZap } from "react-icons/fi"; +import DynamicNewsEventCard from "../../EventCard/DynamicNewsEventCard"; +import { getApiBase } from "@utils/apiConfig"; + +/** + * 主线时间轴布局组件 + * + * 功能: + * 1. 调用 /api/events/mainline 获取预分组数据 + * 2. 按 lv2 概念分组展示,时间轴样式 + * 3. 不使用无限滚动,一次性加载全部数据 + */ +const MainlineTimelineViewComponent = forwardRef( + ( + { + display = "block", + filters = {}, + selectedEvent, + onEventSelect, + eventFollowStatus = {}, + onToggleFollow, + borderColor, + columnsPerRow = 3, + }, + ref + ) => { + // 状态 + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [mainlineData, setMainlineData] = useState(null); + const [expandedGroups, setExpandedGroups] = useState({}); + + // 主题颜色 + const bgColor = useColorModeValue("white", "gray.800"); + const headerBg = useColorModeValue("gray.50", "gray.700"); + const headerHoverBg = useColorModeValue("gray.100", "gray.600"); + const textColor = useColorModeValue("gray.700", "gray.200"); + const secondaryTextColor = useColorModeValue("gray.500", "gray.400"); + const timelineBorderColor = useColorModeValue("gray.200", "gray.600"); + const timelineLineColor = useColorModeValue("blue.200", "blue.600"); + const scrollbarTrackBg = useColorModeValue("#f1f1f1", "#2D3748"); + const scrollbarThumbBg = useColorModeValue("#888", "#4A5568"); + const scrollbarThumbHoverBg = useColorModeValue("#555", "#718096"); + + // 根据主线类型获取配色 + const getColorScheme = useCallback((lv2Name) => { + if (!lv2Name) return "gray"; + const name = lv2Name.toLowerCase(); + + if ( + name.includes("ai") || + name.includes("人工智能") || + name.includes("算力") || + name.includes("大模型") + ) + return "purple"; + if ( + name.includes("半导体") || + name.includes("芯片") || + name.includes("光刻") + ) + return "blue"; + if (name.includes("机器人") || name.includes("人形")) return "pink"; + if ( + name.includes("消费电子") || + name.includes("手机") || + name.includes("xr") + ) + return "cyan"; + if ( + name.includes("汽车") || + name.includes("驾驶") || + name.includes("新能源车") + ) + return "teal"; + if ( + name.includes("新能源") || + name.includes("电力") || + name.includes("光伏") || + name.includes("储能") + ) + return "green"; + if ( + name.includes("低空") || + name.includes("航天") || + name.includes("卫星") + ) + return "orange"; + if (name.includes("军工") || name.includes("国防")) return "red"; + if ( + name.includes("医药") || + name.includes("医疗") || + name.includes("生物") + ) + return "messenger"; + if ( + name.includes("消费") || + name.includes("食品") || + name.includes("白酒") + ) + return "yellow"; + if ( + name.includes("煤炭") || + name.includes("石油") || + name.includes("钢铁") + ) + return "blackAlpha"; + if ( + name.includes("金融") || + name.includes("银行") || + name.includes("券商") + ) + return "linkedin"; + return "gray"; + }, []); + + // 加载主线数据 + const fetchMainlineData = useCallback(async () => { + if (display === "none") return; + + setLoading(true); + setError(null); + + try { + const apiBase = getApiBase(); + const params = new URLSearchParams(); + + // 添加筛选参数 + if (filters.recent_days) + params.append("recent_days", filters.recent_days); + if (filters.importance && filters.importance !== "all") + params.append("importance", filters.importance); + + const url = `${apiBase}/api/events/mainline?${params.toString()}`; + console.log("[MainlineTimelineView] 🔄 请求主线数据:", url); + + const response = await fetch(url); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const result = await response.json(); + console.log("[MainlineTimelineView] 📦 响应数据:", { + success: result.success, + mainlineCount: result.data?.mainlines?.length, + totalEvents: result.data?.total_events, + }); + + if (result.success) { + setMainlineData(result.data); + + // 初始化展开状态(默认展开前5个) + const initialExpanded = {}; + result.data.mainlines?.slice(0, 5).forEach((mainline) => { + initialExpanded[mainline.lv2_id] = true; + }); + setExpandedGroups(initialExpanded); + } else { + throw new Error(result.error || "获取数据失败"); + } + } catch (err) { + console.error("[MainlineTimelineView] ❌ 请求失败:", err); + setError(err.message); + } finally { + setLoading(false); + } + }, [display, filters.recent_days, filters.importance]); + + // 初始加载 & 筛选变化时刷新 + useEffect(() => { + fetchMainlineData(); + }, [fetchMainlineData]); + + // 暴露方法给父组件 + useImperativeHandle( + ref, + () => ({ + refresh: fetchMainlineData, + getScrollPosition: () => null, // 不使用滚动位置判断 + }), + [fetchMainlineData] + ); + + // 切换分组展开/折叠 + const toggleGroup = useCallback((lv2Id) => { + setExpandedGroups((prev) => ({ + ...prev, + [lv2Id]: !prev[lv2Id], + })); + }, []); + + // 全部展开/折叠 + const toggleAll = useCallback( + (expand) => { + if (!mainlineData?.mainlines) return; + const newState = {}; + mainlineData.mainlines.forEach((mainline) => { + newState[mainline.lv2_id] = expand; + }); + setExpandedGroups(newState); + }, + [mainlineData] + ); + + // 渲染加载状态 + if (loading) { + return ( + +
+ + + 正在加载主线数据... + +
+
+ ); + } + + // 渲染错误状态 + if (error) { + return ( + +
+ + 加载失败: {error} + } + colorScheme="blue" + onClick={fetchMainlineData} + aria-label="重试" + /> + +
+
+ ); + } + + // 渲染空状态 + if (!mainlineData?.mainlines?.length) { + return ( + +
+ + + 暂无主线数据 + + 尝试调整筛选条件 + + +
+
+ ); + } + + const { + mainlines, + total_events, + mainline_count, + ungrouped_count, + } = mainlineData; + + return ( + + {/* 顶部统计信息 */} + + + + + + {mainline_count} 条主线 + + + + + + {total_events} 个事件 + + + {ungrouped_count > 0 && ( + + ({ungrouped_count} 个未归类) + + )} + + + + + } + size="sm" + variant="ghost" + onClick={() => toggleAll(true)} + aria-label="全部展开" + /> + + + } + size="sm" + variant="ghost" + onClick={() => toggleAll(false)} + aria-label="全部折叠" + /> + + + } + size="sm" + variant="ghost" + onClick={fetchMainlineData} + aria-label="刷新" + /> + + + + + {/* 主线列表 - 时间轴样式 */} + + {/* 时间轴垂直线 */} + + + + {mainlines.map((mainline, index) => { + const colorScheme = getColorScheme(mainline.lv2_name); + const isExpanded = expandedGroups[mainline.lv2_id]; + + return ( + + {/* 时间轴圆点 */} + + + {/* 分组头部 */} + toggleGroup(mainline.lv2_id)} + transition="all 0.2s" + boxShadow="sm" + > + + + + + + {mainline.lv2_name} + + + {mainline.event_count} 条 + + + + {mainline.lv1_name} + + + + + + + + #{index + 1} + + + + + {/* 分组内容 */} + + + + {mainline.events.map((event, eventIndex) => ( + + { + onEventSelect?.(clickedEvent); + }} + onTitleClick={(e) => { + e.preventDefault(); + e.stopPropagation(); + onEventSelect?.(event); + }} + onToggleFollow={() => onToggleFollow?.(event.id)} + borderColor={borderColor} + /> + + ))} + + + + + ); + })} + + + + ); + } +); + +MainlineTimelineViewComponent.displayName = "MainlineTimelineView"; + +const MainlineTimelineView = React.memo(MainlineTimelineViewComponent); + +export default MainlineTimelineView;