import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from datetime import datetime, timedelta

st.title("📊 Dashboard")
st.markdown("欢迎来到系统仪表板")

# 模拟数据
@st.cache_data
def load_dashboard_data():
    dates = pd.date_range(start=datetime.now() - timedelta(days=30), periods=30)
    data = {
        'date': dates,
        'users': np.random.randint(100, 1000, 30),
        'revenue': np.random.uniform(1000, 5000, 30),
        'errors': np.random.randint(0, 50, 30)
    }
    return pd.DataFrame(data)

# 加载数据
df = load_dashboard_data()

# 关键指标
col1, col2, col3, col4 = st.columns(4)

with col1:
    st.metric(
        label="总用户数",
        value=f"{df['users'].sum():,}",
        delta=f"{df['users'].iloc[-1] - df['users'].iloc[-2]:+d}"
    )

with col2:
    st.metric(
        label="总收入",
        value=f"${df['revenue'].sum():,.2f}",
        delta=f"${df['revenue'].iloc[-1] - df['revenue'].iloc[-2]:+.2f}"
    )

with col3:
    st.metric(
        label="平均错误数",
        value=f"{df['errors'].mean():.1f}",
        delta=f"{df['errors'].iloc[-1] - df['errors'].mean():.1f}"
    )

with col4:
    st.metric(
        label="系统状态",
        value="正常",
        delta="99.9% 正常运行时间"
    )

# 图表
st.subheader("📈 趋势分析")

tab1, tab2, tab3 = st.tabs(["用户趋势", "收入趋势", "错误趋势"])

with tab1:
    fig_users = px.line(df, x='date', y='users', title='用户数量趋势')
    st.plotly_chart(fig_users, use_container_width=True)

with tab2:
    fig_revenue = px.bar(df, x='date', y='revenue', title='收入趋势')
    st.plotly_chart(fig_revenue, use_container_width=True)

with tab3:
    fig_errors = px.scatter(df, x='date', y='errors', title='错误数量趋势')
    st.plotly_chart(fig_errors, use_container_width=True)

# 数据表格
st.subheader("📋 详细数据")
st.dataframe(df, use_container_width=True)