from fastapi import APIRouter, HTTPException, Query, Depends
from typing import Optional

from app.controllers.valuation import valuation_controller
from app.schemas.valuation import (
    ValuationAssessmentCreate,
    ValuationAssessmentUpdate,
    ValuationAssessmentOut,
    ValuationAssessmentList,
    ValuationAssessmentQuery,
    ValuationApprovalRequest,
    ValuationAdminNotesUpdate
)
from app.schemas.base import Success, SuccessExtra
from app.core.ctx import CTX_USER_ID

valuations_router = APIRouter(tags=["估值评估"])


@valuations_router.post("/", summary="创建估值评估")
async def create_valuation(data: ValuationAssessmentCreate):
    """创建新的估值评估记录"""
    try:
        result = await valuation_controller.create(data)
        return Success(data=result, msg="创建成功")
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"创建失败: {str(e)}")


@valuations_router.get("/statistics/overview", summary="获取统计信息")
async def get_statistics():
    """获取估值评估统计信息"""
    result = await valuation_controller.get_statistics()
    return Success(data=result, msg="获取统计信息成功")


@valuations_router.get("/{valuation_id}", summary="获取估值评估详情")
async def get_valuation(valuation_id: int):
    """根据ID获取估值评估详情"""
    result = await valuation_controller.get_by_id(valuation_id)
    if not result:
        raise HTTPException(status_code=404, detail="估值评估记录不存在")
    return Success(data=result, msg="获取成功")


@valuations_router.put("/{valuation_id}", summary="更新估值评估")
async def update_valuation(valuation_id: int, data: ValuationAssessmentUpdate):
    """更新估值评估记录"""
    result = await valuation_controller.update(valuation_id, data)
    if not result:
        raise HTTPException(status_code=404, detail="估值评估记录不存在")
    return Success(data=result, msg="更新成功")


@valuations_router.delete("/{valuation_id}", summary="删除估值评估")
async def delete_valuation(valuation_id: int):
    """软删除估值评估记录"""
    result = await valuation_controller.delete(valuation_id)
    if not result:
        raise HTTPException(status_code=404, detail="估值评估记录不存在")
    return Success(data={"deleted": True}, msg="删除成功")


@valuations_router.get("/", summary="获取估值评估列表")
async def get_valuations(
    asset_name: Optional[str] = Query(None, description="资产名称"),
    institution: Optional[str] = Query(None, description="所属机构"),
    industry: Optional[str] = Query(None, description="所属行业"),
    heritage_level: Optional[str] = Query(None, description="非遗等级"),
    status: Optional[str] = Query(None, description="评估状态"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量")
):
    """获取估值评估列表，支持筛选和分页"""
    query = ValuationAssessmentQuery(
        asset_name=asset_name,
        institution=institution,
        industry=industry,
        heritage_level=heritage_level,
        status=status,
        is_active=is_active,
        page=page,
        size=size
    )
    result = await valuation_controller.get_list(query)
    return SuccessExtra(
        data=result.items,
        total=result.total,
        page=result.page,
        size=result.size,
        pages=result.pages,
        msg="获取成功"
    )


@valuations_router.get("/search/keyword", summary="搜索估值评估")
async def search_valuations(
    keyword: str = Query(..., description="搜索关键词"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量")
):
    """根据关键词搜索估值评估记录"""
    result = await valuation_controller.search(keyword, page, size)
    return SuccessExtra(
        data=result.items,
        total=result.total,
        page=result.page,
        size=result.size,
        pages=result.pages,
        msg="搜索成功"
    )


# 批量操作接口
@valuations_router.post("/batch/delete", summary="批量删除估值评估")
async def batch_delete_valuations(valuation_ids: list[int]):
    """批量软删除估值评估记录"""
    success_count = 0
    failed_ids = []
    
    for valuation_id in valuation_ids:
        result = await valuation_controller.delete(valuation_id)
        if result:
            success_count += 1
        else:
            failed_ids.append(valuation_id)
    
    return Success(
        data={
            "success_count": success_count,
            "failed_ids": failed_ids,
            "total_count": len(valuation_ids)
        },
        msg=f"批量删除完成，成功删除 {success_count} 条记录"
    )


# 导出接口
@valuations_router.get("/export/excel", summary="导出估值评估数据")
async def export_valuations(
    asset_name: Optional[str] = Query(None, description="资产名称"),
    institution: Optional[str] = Query(None, description="所属机构"),
    industry: Optional[str] = Query(None, description="所属行业"),
    heritage_level: Optional[str] = Query(None, description="非遗等级")
):
    """导出估值评估数据为Excel文件"""
    # 这里可以实现Excel导出逻辑
    # 暂时返回提示信息
    return Success(data={"message": "导出功能待实现"}, msg="导出请求已接收")


# 审核管理接口
@valuations_router.post("/{valuation_id}/approve", summary="审核通过估值评估")
async def approve_valuation(valuation_id: int, data: ValuationApprovalRequest):
    """审核通过估值评估"""
    result = await valuation_controller.approve_valuation(valuation_id, data.admin_notes)
    if not result:
        raise HTTPException(status_code=404, detail="估值评估记录不存在")
    return Success(data=result, msg="审核通过成功")


@valuations_router.post("/{valuation_id}/reject", summary="审核拒绝估值评估")
async def reject_valuation(valuation_id: int, data: ValuationApprovalRequest):
    """审核拒绝估值评估"""
    result = await valuation_controller.reject_valuation(valuation_id, data.admin_notes)
    if not result:
        raise HTTPException(status_code=404, detail="估值评估记录不存在")
    return Success(data=result, msg="审核拒绝成功")


@valuations_router.put("/{valuation_id}/admin-notes", summary="更新管理员备注")
async def update_admin_notes(valuation_id: int, data: ValuationAdminNotesUpdate):
    """更新管理员备注"""
    result = await valuation_controller.update_admin_notes(valuation_id, data.admin_notes)
    if not result:
        raise HTTPException(status_code=404, detail="估值评估记录不存在")
    return Success(data=result, msg="管理员备注更新成功")