import streamlit as st
import pandas as pd
import time
from datetime import datetime, timedelta
import random

st.title("🔍 Search Tool")
st.markdown("全局搜索工具")

# 模拟搜索数据
@st.cache_data
def load_search_data():
    categories = ["用户", "订单", "产品", "日志", "文档"]
    data = []
    
    for i in range(200):
        data.append({
            'id': f"ITEM-{3000 + i}",
            'title': f"项目 {i+1}: {random.choice(['用户管理', '订单处理', '产品信息', '系统日志', '帮助文档'])}",
            'category': random.choice(categories),
            'content': f"这是项目 {i+1} 的详细内容描述，包含相关信息和数据...",
            'created_date': datetime.now() - timedelta(days=random.randint(1, 365)),
            'tags': random.sample(['重要', '紧急', '已完成', '进行中', '待审核'], k=random.randint(1, 3))
        })
    
    return pd.DataFrame(data)

# 加载数据
search_df = load_search_data()

# 搜索界面
st.subheader("🔍 搜索查询")

# 搜索选项
col1, col2 = st.columns([3, 1])

with col1:
    search_query = st.text_input(
        "搜索内容",
        placeholder="输入关键词进行搜索...",
        help="支持标题、内容、标签搜索"
    )

with col2:
    search_button = st.button("🔍 搜索", type="primary")

# 高级搜索选项
with st.expander("🔧 高级搜索选项"):
    col1, col2, col3 = st.columns(3)
    
    with col1:
        selected_categories = st.multiselect(
            "类别筛选",
            options=search_df['category'].unique(),
            default=search_df['category'].unique()
        )
    
    with col2:
        date_range = st.date_input(
            "时间范围",
            value=(datetime.now() - timedelta(days=30), datetime.now()),
            max_value=datetime.now()
        )
    
    with col3:
        available_tags = ['重要', '紧急', '已完成', '进行中', '待审核']
        selected_tags = st.multiselect(
            "标签筛选",
            options=available_tags
        )

# 执行搜索
if search_query or search_button:
    with st.spinner("搜索中..."):
        time.sleep(0.5)  # 模拟搜索延迟
        
        # 过滤数据
        filtered_df = search_df[search_df['category'].isin(selected_categories)]
        
        # 时间范围筛选
        if len(date_range) == 2:
            start_date, end_date = date_range
            filtered_df = filtered_df[
                (filtered_df['created_date'].dt.date >= start_date) &
                (filtered_df['created_date'].dt.date <= end_date)
            ]
        
        # 标签筛选
        if selected_tags:
            filtered_df = filtered_df[
                filtered_df['tags'].apply(lambda x: any(tag in x for tag in selected_tags))
            ]
        
        # 关键词搜索
        if search_query:
            mask = (
                filtered_df['title'].str.contains(search_query, case=False, na=False) |
                filtered_df['content'].str.contains(search_query, case=False, na=False) |
                filtered_df['tags'].astype(str).str.contains(search_query, case=False, na=False)
            )
            filtered_df = filtered_df[mask]
        
        # 显示搜索结果
        st.subheader(f"📋 搜索结果 ({len(filtered_df)} 项)")
        
        if len(filtered_df) > 0:
            # 结果统计
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("总结果数", len(filtered_df))
            with col2:
                category_counts = filtered_df['category'].value_counts()
                st.metric("主要类别", category_counts.index[0] if len(category_counts) > 0 else "无")
            with col3:
                recent_count = len(filtered_df[filtered_df['created_date'] >= datetime.now() - timedelta(days=7)])
                st.metric("最近7天", recent_count)
            
            # 排序选项
            sort_option = st.selectbox(
                "排序方式",
                ["相关性", "时间（最新）", "时间（最旧）", "标题（A-Z）"]
            )
            
            if sort_option == "时间（最新）":
                filtered_df = filtered_df.sort_values('created_date', ascending=False)
            elif sort_option == "时间（最旧）":
                filtered_df = filtered_df.sort_values('created_date', ascending=True)
            elif sort_option == "标题（A-Z）":
                filtered_df = filtered_df.sort_values('title')
            
            # 分页显示
            items_per_page = st.selectbox("每页显示", [10, 20, 50], index=1)
            total_pages = (len(filtered_df) - 1) // items_per_page + 1
            
            if total_pages > 1:
                page = st.selectbox("选择页面", range(1, total_pages + 1))
                start_idx = (page - 1) * items_per_page
                end_idx = start_idx + items_per_page
                display_df = filtered_df.iloc[start_idx:end_idx]
            else:
                display_df = filtered_df
            
            # 显示结果
            for idx, row in display_df.iterrows():
                with st.container():
                    st.markdown(f"### {row['title']}")
                    
                    col1, col2 = st.columns([3, 1])
                    with col1:
                        st.write(f"**类别:** {row['category']}")
                        st.write(f"**内容预览:** {row['content'][:100]}...")
                        
                        # 显示标签
                        if row['tags']:
                            tags_html = " ".join([f"<span style='background-color: #e0e0e0; padding: 2px 6px; border-radius: 10px; font-size: 12px;'>{tag}</span>" for tag in row['tags']])
                            st.markdown(tags_html, unsafe_allow_html=True)
                    
                    with col2:
                        st.write(f"**ID:** {row['id']}")
                        st.write(f"**创建时间:** {row['created_date'].strftime('%Y-%m-%d')}")
                        if st.button("查看详情", key=f"view_{row['id']}"):
                            st.session_state[f"selected_item_{row['id']}"] = True
                    
                    # 详情展示
                    if st.session_state.get(f"selected_item_{row['id']}", False):
                        with st.expander(f"详情: {row['title']}", expanded=True):
                            st.write(f"**完整内容:** {row['content']}")
                            st.write(f"**所有标签:** {', '.join(row['tags'])}")
                            if st.button("收起详情", key=f"hide_{row['id']}"):
                                st.session_state[f"selected_item_{row['id']}"] = False
                                st.rerun()
                    
                    st.divider()
                    
        else:
            st.warning("没有找到匹配的结果，请尝试其他搜索条件。")
            
            # 搜索建议
            st.subheader("💡 搜索建议")
            st.markdown("""
            - 尝试使用更简单的关键词
            - 检查拼写是否正确  
            - 尝试使用同义词
            - 扩大时间范围
            - 取消一些筛选条件
            """)

else:
    # 显示搜索提示
    st.info("👆 在上方输入关键词开始搜索")
    
    # 热门搜索词
    st.subheader("🔥 热门搜索")
    popular_searches = ["用户管理", "订单处理", "系统日志", "产品信息", "帮助文档"]
    
    cols = st.columns(len(popular_searches))
    for i, term in enumerate(popular_searches):
        with cols[i]:
            if st.button(f"#{term}", key=f"popular_{i}"):
                st.session_state.search_query = term
                st.rerun()