"""
统计分析API路由
"""
from typing import Optional, Dict, Any
from datetime import date
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.deps import get_db, get_current_user
from app.services.statistics_service import statistics_service

router = APIRouter()


@router.get("/overview", response_model=Dict[str, Any])
async def get_statistics_overview(
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取总览统计

    - **organization_id**: 网点ID筛选

    返回资产总数、总价值、各状态数量、采购统计、网点数等概览信息
    """
    return await statistics_service.get_overview(db, organization_id=organization_id)


@router.get("/assets/purchase", response_model=Dict[str, Any])
async def get_purchase_statistics(
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取采购统计

    - **start_date**: 开始日期
    - **end_date**: 结束日期
    - **organization_id**: 网点ID筛选

    返回采购数量、采购金额、月度趋势、供应商分布等统计信息
    """
    return await statistics_service.get_purchase_statistics(
        db,
        start_date=start_date,
        end_date=end_date,
        organization_id=organization_id
    )


@router.get("/assets/depreciation", response_model=Dict[str, Any])
async def get_depreciation_statistics(
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取折旧统计

    - **organization_id**: 网点ID筛选

    返回折旧金额、折旧率、分类折旧等统计信息
    """
    return await statistics_service.get_depreciation_statistics(db, organization_id=organization_id)


@router.get("/assets/value", response_model=Dict[str, Any])
async def get_value_statistics(
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取价值统计

    - **organization_id**: 网点ID筛选

    返回资产总价值、净值、折旧、分类价值、网点价值、高价值资产等统计信息
    """
    return await statistics_service.get_value_statistics(db, organization_id=organization_id)


@router.get("/assets/trend", response_model=Dict[str, Any])
async def get_trend_analysis(
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取趋势分析

    - **start_date**: 开始日期
    - **end_date**: 结束日期
    - **organization_id**: 网点ID筛选

    返回资产数量趋势、价值趋势、采购趋势、维修趋势、调拨趋势等分析数据
    """
    return await statistics_service.get_trend_analysis(
        db,
        start_date=start_date,
        end_date=end_date,
        organization_id=organization_id
    )


@router.get("/maintenance/summary", response_model=Dict[str, Any])
async def get_maintenance_summary(
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取维修汇总

    - **start_date**: 开始日期
    - **end_date**: 结束日期
    - **organization_id**: 网点ID筛选

    返回维修次数、维修费用、状态分布等统计信息
    """
    return await statistics_service.get_maintenance_statistics(
        db,
        start_date=start_date,
        end_date=end_date,
        organization_id=organization_id
    )


@router.get("/allocation/summary", response_model=Dict[str, Any])
async def get_allocation_summary(
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    organization_id: Optional[int] = Query(None, description="网点ID筛选"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取分配汇总

    - **start_date**: 开始日期
    - **end_date**: 结束日期
    - **organization_id**: 网点ID筛选

    返回分配次数、状态分布、网点分配统计等信息
    """
    return await statistics_service.get_allocation_statistics(
        db,
        start_date=start_date,
        end_date=end_date,
        organization_id=organization_id
    )


@router.post("/export")
async def export_statistics(
    report_type: str = Query(..., description="报表类型"),
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    organization_id: Optional[int] = Query(None, description="网点ID"),
    format: str = Query("xlsx", description="导出格式"),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    导出统计报表

    - **report_type**: 报表类型（overview/purchase/depreciation/value/trend/maintenance/allocation）
    - **start_date**: 开始日期
    - **end_date**: 结束日期
    - **organization_id**: 网点ID
    - **format**: 导出格式（xlsx/csv/pdf）

    返回导出文件信息
    """
    # 根据报表类型获取数据
    if report_type == "overview":
        data = await statistics_service.get_overview(db, organization_id)
    elif report_type == "purchase":
        data = await statistics_service.get_purchase_statistics(db, start_date, end_date, organization_id)
    elif report_type == "depreciation":
        data = await statistics_service.get_depreciation_statistics(db, organization_id)
    elif report_type == "value":
        data = await statistics_service.get_value_statistics(db, organization_id)
    elif report_type == "trend":
        data = await statistics_service.get_trend_analysis(db, start_date, end_date, organization_id)
    elif report_type == "maintenance":
        data = await statistics_service.get_maintenance_statistics(db, start_date, end_date, organization_id)
    elif report_type == "allocation":
        data = await statistics_service.get_allocation_statistics(db, start_date, end_date, organization_id)
    else:
        raise ValueError(f"不支持的报表类型: {report_type}")

    # TODO: 实现导出逻辑
    # 1. 生成Excel/CSV/PDF文件
    # 2. 保存到文件系统
    # 3. 返回文件URL

    return {
        "message": "导出功能待实现",
        "data": data,
        "report_type": report_type,
        "format": format
    }
