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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
"""
文档管理组件
"""
import streamlit as st
from services import get_document_service, get_vector_store_service, get_cached_user_stats
from utils.config import config


def show_document_manager(user_id: int):
    """显示文档管理界面"""
    
    st.title("📁 知识库管理")
    
    # 显示 Embedding 模型加载状态
    _show_embedding_model_status()
    
    doc_service = get_document_service()
    
    # 显示统计信息
    _show_statistics(user_id, doc_service)
    
    st.markdown("---")
    
    # 文档上传区域
    _show_upload_section(user_id, doc_service)
    
    st.markdown("---")
    
    # 文档列表
    _show_document_list(user_id, doc_service)


def _show_embedding_model_status():
    """显示 Embedding 模型加载状态"""
    vector_service = get_vector_store_service()
    status = vector_service.get_embeddings_loading_status()
    
    if status['ready']:
        st.success(f"✅ Embedding 模型已就绪: {status['model_name']}")
    elif status['loading']:
        st.info(f"⏳ 正在后台加载 Embedding 模型: {status['model_name']},请稍候...")
        st.caption("💡 模型加载完成后即可使用向量检索功能")
    else:
        st.warning(f"⚠️ Embedding 模型未加载: {status['model_name']}")


@st.cache_data(ttl=120)  # 缓存120秒
def _get_cached_documents(user_id: int):
    """缓存文档列表"""
    doc_service = get_document_service()
    return doc_service.get_user_documents(user_id)


def _show_statistics(user_id: int, doc_service):
    """显示统计信息"""
    try:
        # 使用缓存的统计数据,避免频繁查询
        stats = get_cached_user_stats(user_id)
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("📄 文档数量", stats['document_count'])
        
        with col2:
            st.metric("🧩 向量块数", stats['vector_count'])
        
        with col3:
            st.metric("💾 存储空间", stats['storage_used_formatted'])
    except ConnectionError as e:
        # 数据库连接失败,显示友好的错误提示
        st.error("⚠️ 无法连接到数据库")
        error_msg = str(e)
        
        # 检查是否是 DNS 解析失败
        if "DNS 解析失败" in error_msg or "nodename nor servname" in error_msg:
            st.warning("""
            **网络连接问题**
            
            无法连接到 Supabase PostgreSQL 数据库。这可能是由于:
            - 网络连接不稳定
            - DNS 解析失败
            - 防火墙阻止了连接
            
            **解决方案:**
            1. 检查网络连接
            2. 确认 `DATABASE_URL` 配置正确
            3. 如果问题持续,可以暂时切换到本地模式:
               - 在 `.env` 文件中设置 `DATABASE_MODE=local`
               - 重启应用
            """)
        else:
            st.warning(f"数据库连接错误:{error_msg}")
        
        # 显示默认统计值
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("📄 文档数量", "N/A")
        with col2:
            st.metric("🧩 向量块数", "N/A")
        with col3:
            st.metric("💾 存储空间", "N/A")
    except Exception as e:
        st.error(f"获取统计信息失败: {str(e)}")
        # 显示默认统计值
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("📄 文档数量", "N/A")
        with col2:
            st.metric("🧩 向量块数", "N/A")
        with col3:
            st.metric("💾 存储空间", "N/A")


def _show_upload_section(user_id: int, doc_service):
    """显示上传区域"""
    st.subheader("📤 上传文档")
    
    # 使用 session_state 管理文件上传器的 key
    if 'uploader_key' not in st.session_state:
        st.session_state.uploader_key = 0
    
    # 动态获取最大文件大小(MB)
    max_size_mb = config.MAX_FILE_SIZE / (1024 * 1024)
    
    uploaded_file = st.file_uploader(
        "选择文件",
        type=['pdf', 'txt', 'md', 'docx'],
        help=f"支持 PDF、TXT、Markdown、Word 文档,最大 {max_size_mb:.0f}MB",
        key=f"file_uploader_{st.session_state.uploader_key}"
    )
    
    if uploaded_file:
        st.info(f"📄 已选择: {uploaded_file.name} ({uploaded_file.size // 1024} KB)")
        
        col1, col2 = st.columns([1, 4])
        
        with col1:
            if st.button("🚀 开始上传", use_container_width=True):
                with st.spinner("正在处理文档..."):
                    success, message = doc_service.upload_document(user_id, uploaded_file)
                    
                    if success:
                        st.success(f"✅ {message}")
                        # 精确清除文档相关缓存
                        get_cached_user_stats.clear()
                        _get_cached_documents.clear()
                        # 上传成功后,更新 key 以清空文件选择器
                        st.session_state.uploader_key += 1
                        st.rerun()
                    else:
                        st.error(f"❌ {message}")
        
        with col2:
            st.caption("上传后将自动解析、分块并生成向量索引")


def _show_document_list(user_id: int, doc_service):
    """显示文档列表"""
    # 使用更紧凑的标题样式
    st.markdown("<h3 style='margin: 4px 0 6px 0; font-size: 1.1rem;'>📋 我的文档</h3>", unsafe_allow_html=True)
    
    # 获取文档列表(使用缓存)
    try:
        documents = _get_cached_documents(user_id)
    except ConnectionError as e:
        st.error("⚠️ 无法连接到数据库,无法加载文档列表")
        error_msg = str(e)
        if "DNS 解析失败" in error_msg or "nodename nor servname" in error_msg:
            st.warning("""
            **网络连接问题**
            
            无法连接到 Supabase PostgreSQL 数据库。请检查网络连接或切换到本地模式。
            """)
        else:
            st.warning(f"数据库连接错误:{error_msg}")
        documents = []
    except Exception as e:
        st.error(f"获取文档列表失败: {str(e)}")
        documents = []
    
    if not documents:
        st.info("暂无文档。请上传文档以开始使用智能问答功能。")
        return
    
    # 搜索功能
    search_query = st.text_input("🔍 搜索文档", placeholder="输入文件名关键词...")
    
    if search_query:
        documents = [doc for doc in documents if search_query.lower() in doc['original_filename'].lower()]
    
    # 排序选项
    sort_by = st.selectbox(
        "排序方式",
        ["上传时间(最新)", "上传时间(最早)", "文件大小(大到小)", "文件大小(小到大)"],
        label_visibility="collapsed"
    )
    
    if "最新" in sort_by:
        documents = sorted(documents, key=lambda x: x['upload_at'], reverse=True)
    elif "最早" in sort_by:
        documents = sorted(documents, key=lambda x: x['upload_at'])
    elif "大到小" in sort_by:
        documents = sorted(documents, key=lambda x: x['file_size'], reverse=True)
    elif "小到大" in sort_by:
        documents = sorted(documents, key=lambda x: x['file_size'])
    
    st.caption(f"共 {len(documents)} 个文档")
    
    # 显示文档卡片
    for doc in documents:
        _show_document_card(user_id, doc, doc_service)


def _show_document_card(user_id: int, doc: dict, doc_service):
    """显示单个文档卡片"""
    
    # 使用两列布局:文档信息 + 操作菜单
    col1, col2 = st.columns([10, 1])
    
    with col1:
        # 文件图标和名称 - 使用更紧凑的样式
        icon = _get_file_icon(doc['file_type'])
        st.markdown(f"<p style='margin: 2px 0; font-size: 0.95rem;'><strong>{icon} {doc['original_filename']}</strong></p>", unsafe_allow_html=True)
        
        # 文件信息
        info_parts = []
        info_parts.append(f"📏 {doc['file_size_formatted']}")
        
        if doc.get('page_count'):
            info_parts.append(f"📄 {doc['page_count']} 页")
        
        info_parts.append(f"🧩 {doc['chunk_count']} 块")
        info_parts.append(f"🕐 {doc['upload_at'][:16]}")
        
        st.markdown(f"<p style='margin: 2px 0; font-size: 0.85rem; opacity: 0.7;'>{' • '.join(info_parts)}</p>", unsafe_allow_html=True)
    
    with col2:
        # 三点菜单
        with st.popover("⋮", use_container_width=True):
            st.markdown(f"**操作菜单**")
            st.caption(doc['original_filename'])
            st.markdown("---")
            
            # 预览按钮
            if st.button("👁️ 预览文档", key=f"preview_{doc['doc_id']}", use_container_width=True):
                _show_document_preview(user_id, doc['doc_id'], doc['original_filename'], doc_service)
            
            # 删除按钮
            if st.button("🗑️ 删除文档", key=f"delete_{doc['doc_id']}", use_container_width=True):
                _confirm_delete_document(user_id, doc['doc_id'], doc['original_filename'], doc_service)
    
    # 使用更紧凑的分隔线
    st.markdown("<hr style='margin: 5px 0; border: none; border-top: 1px solid var(--border); opacity: 0.3;'>", unsafe_allow_html=True)


def _get_file_icon(file_type: str) -> str:
    """获取文件类型图标"""
    icons = {
        '.pdf': '📕',
        '.txt': '📄',
        '.md': '📝',
        '.docx': '📘'
    }
    return icons.get(file_type, '📄')


def _show_document_preview(user_id: int, doc_id: str, filename: str, doc_service):
    """显示文档预览对话框"""
    
    @st.dialog(f"📄 {filename}", width="large")
    def preview_dialog():
        # 获取文档信息
        from database import DocumentDAO
        from utils.db_error_handler import safe_db_operation, show_db_error_ui
        
        doc_dao = DocumentDAO()
        try:
            doc = safe_db_operation(
                lambda: doc_dao.get_document(doc_id),
                default_value=None,
                error_context="获取文档信息"
            )
            if doc:
                preview_content = doc_service.get_document_preview(user_id, doc_id, max_length=2000)
            else:
                preview_content = "文档不存在"
        except Exception as e:
            show_db_error_ui(e, "获取文档预览")
            preview_content = "无法加载文档预览"
        
        if preview_content:
            # 格式化文件大小
            def format_file_size(size_bytes):
                if size_bytes < 1024:
                    return f"{size_bytes} B"
                elif size_bytes < 1024 * 1024:
                    return f"{size_bytes / 1024:.1f} KB"
                else:
                    return f"{size_bytes / (1024 * 1024):.1f} MB"
            
            # 文档信息栏
            col1, col2, col3 = st.columns(3)
            with col1:
                file_size_str = format_file_size(doc.file_size) if doc else "未知"
                st.metric("📏 文件大小", file_size_str)
            with col2:
                st.metric("📝 字数", f"{len(preview_content):,}")
            with col3:
                file_type = doc.file_type if doc else ""
                type_name = {"pdf": "PDF", ".pdf": "PDF", ".docx": "Word", ".txt": "文本", ".md": "Markdown"}.get(file_type, file_type)
                st.metric("📑 类型", type_name)
            
            st.markdown("---")
            
            # 文档内容显示区域 - 使用美化的样式
            st.markdown("""
                <div style="
                    background: linear-gradient(to bottom, var(--bg-card), var(--bg-secondary));
                    border: 1px solid var(--border);
                    border-radius: 12px;
                    padding: 24px;
                    margin: 16px 0;
                    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
                    max-height: 500px;
                    overflow-y: auto;
                ">
                    <pre style="
                        font-family: 'SF Mono', 'Consolas', 'Monaco', monospace;
                        font-size: 14px;
                        line-height: 1.8;
                        color: var(--text-primary);
                        white-space: pre-wrap;
                        word-wrap: break-word;
                        margin: 0;
                    ">{}</pre>
                </div>
            """.format(preview_content.replace("<", "&lt;").replace(">", "&gt;")), unsafe_allow_html=True)
            
            # 操作按钮
            col1, col2 = st.columns(2)
            with col1:
                if st.button("📋 复制内容", use_container_width=True, type="secondary"):
                    # Streamlit 不支持直接复制到剪贴板,显示提示
                    st.toast("💡 请手动选择文本进行复制", icon="ℹ️")
            with col2:
                if st.button("✅ 关闭", use_container_width=True, type="primary"):
                    st.rerun()
        else:
            st.error("❌ 无法加载文档预览")
            if st.button("关闭", use_container_width=True):
                st.rerun()
    
    preview_dialog()


def _confirm_delete_document(user_id: int, doc_id: str, filename: str, doc_service):
    """确认删除文档"""
    
    @st.dialog("⚠️ 确认删除", width="medium")
    def delete_dialog():
        # 使用美化的警告框
        st.markdown(f"""
            <div style="
                background: linear-gradient(135deg, rgba(239, 83, 80, 0.1), rgba(229, 57, 53, 0.05));
                border: 2px solid #EF5350;
                border-radius: 12px;
                padding: 20px;
                margin: 16px 0;
            ">
                <div style="
                    font-size: 16px;
                    font-weight: 600;
                    color: var(--text-primary);
                    margin-bottom: 12px;
                ">
                    确定要删除文档「{filename}」吗?
                </div>
                <div style="
                    font-size: 14px;
                    color: var(--text-secondary);
                    line-height: 1.8;
                ">
                    此操作将同时删除:<br>
                    • 文档文件<br>
                    • 所有文本块<br>
                    • 向量索引<br><br>
                    <strong style="color: #EF5350;">⚠️ 此操作不可恢复!</strong>
                </div>
            </div>
        """, unsafe_allow_html=True)
        
        st.markdown("<br>", unsafe_allow_html=True)
        
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("↩️ 取消", use_container_width=True, type="secondary"):
                st.rerun()
        
        with col2:
            if st.button("🗑️ 确认删除", use_container_width=True, type="primary"):
                with st.spinner("正在删除..."):
                    success, message = doc_service.delete_document(user_id, doc_id)
                    
                    if success:
                        st.success(message)
                        # 精确清除文档相关缓存
                        get_cached_user_stats.clear()
                        _get_cached_documents.clear()
                        st.rerun()
                    else:
                        st.error(message)
    
    delete_dialog()