"""
资产回收管理API路由
"""
from typing import Optional, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel
from app.core.deps import get_sync_db, get_current_user
from app.schemas.recovery import (
    AssetRecoveryOrderCreate,
    AssetRecoveryOrderUpdate,
    AssetRecoveryOrderWithRelations,
    AssetRecoveryOrderQueryParams,
    AssetRecoveryStatistics
)
from app.services.recovery_service import recovery_service

router = APIRouter()


class ApprovalPayload(BaseModel):
    approved: bool
    comment: Optional[str] = None


@router.get("/", response_model=Dict[str, Any])
def get_recovery_orders(
    skip: int = Query(0, ge=0, description="跳过条数"),
    limit: int = Query(20, ge=1, le=100, description="返回条数"),
    recovery_type: Optional[str] = Query(None, description="回收类型"),
    approval_status: Optional[str] = Query(None, description="审批状态"),
    execute_status: Optional[str] = Query(None, description="执行状态"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    获取回收单列表

    - **skip**: 跳过条数
    - **limit**: 返回条数（最大100）
    - **recovery_type**: 回收类型（user=使用人回收/org=机构回收/scrap=报废回收）
    - **approval_status**: 审批状态（pending/approved/rejected/cancelled）
    - **execute_status**: 执行状态（pending/executing/completed/cancelled）
    - **keyword**: 搜索关键词（单号/标题）
    """
    items, total = recovery_service.get_orders(
        db=db,
        skip=skip,
        limit=limit,
        recovery_type=recovery_type,
        approval_status=approval_status,
        execute_status=execute_status,
        keyword=keyword
    )
    return {"items": items, "total": total}


@router.get("/statistics", response_model=AssetRecoveryStatistics)
def get_recovery_statistics(
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    获取回收单统计信息

    返回回收单总数、待审批数、已审批数等统计信息
    """
    return recovery_service.get_statistics(db)


@router.get("/{order_id}", response_model=dict)
async def get_recovery_order(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    获取回收单详情

    - **order_id**: 回收单ID

    返回回收单详情及其关联信息（包含明细列表）
    """
    return await recovery_service.get_order(db, order_id)


@router.get("/{order_id}/items", response_model=list)
def get_recovery_order_items(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    获取回收单明细列表

    - **order_id**: 回收单ID

    返回该回收单的所有资产明细
    """
    return recovery_service.get_order_items(db, order_id)


@router.post("/", response_model=dict, status_code=status.HTTP_201_CREATED)
async def create_recovery_order(
    obj_in: AssetRecoveryOrderCreate,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    创建回收单

    - **recovery_type**: 回收类型
      - user: 使用人回收（从使用人处回收）
      - org: 机构回收（从机构回收）
      - scrap: 报废回收（报废资产回收）
    - **title**: 标题
    - **asset_ids**: 资产ID列表
    - **remark**: 备注

    创建后状态为待审批，需要审批后才能执行
    """
    return await recovery_service.create_order(
        db=db,
        obj_in=obj_in,
        apply_user_id=current_user.id
    )


@router.put("/{order_id}", response_model=dict)
def update_recovery_order(
    order_id: int,
    obj_in: AssetRecoveryOrderUpdate,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    更新回收单

    - **order_id**: 回收单ID
    - **title**: 标题
    - **remark**: 备注

    只有待审批状态的回收单可以更新
    """
    return recovery_service.update_order(
        db=db,
        order_id=order_id,
        obj_in=obj_in
    )


@router.post("/{order_id}/approve", response_model=dict)
def approve_recovery_order(
    order_id: int,
    approval_status: Optional[str] = Query(None, description="审批状态(approved/rejected)"),
    approval_remark: Optional[str] = Query(None, description="审批备注"),
    payload: Optional[ApprovalPayload] = None,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    审批回收单

    - **order_id**: 回收单ID
    - **approval_status**: 审批状态（approved/rejected）
    - **approval_remark**: 审批备注

    审批通过后可以开始执行回收
    """
    if approval_status is None and payload is not None:
        approval_status = "approved" if payload.approved else "rejected"
    if approval_remark is None and payload is not None and payload.comment:
        approval_remark = payload.comment
    if approval_status is None:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="缺少审批状态")

    return recovery_service.approve_order(
        db=db,
        order_id=order_id,
        approval_status=approval_status,
        approval_user_id=current_user.id,
        approval_remark=approval_remark
    )


@router.post("/{order_id}/start", response_model=dict)
def start_recovery_order(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    开始回收

    - **order_id**: 回收单ID

    开始执行已审批通过的回收单
    """
    return recovery_service.start_order(
        db=db,
        order_id=order_id,
        execute_user_id=current_user.id
    )


@router.post("/{order_id}/complete", response_model=dict)
async def complete_recovery_order(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    完成回收

    - **order_id**: 回收单ID

    完成回收单，自动更新资产状态为库存中或报废
    """
    return await recovery_service.complete_order(
        db=db,
        order_id=order_id,
        execute_user_id=current_user.id
    )


@router.post("/{order_id}/execute", response_model=dict)
async def execute_recovery_order(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    执行回收（兼容前端）
    """
    return await recovery_service.complete_order(
        db=db,
        order_id=order_id,
        execute_user_id=current_user.id
    )


@router.post("/{order_id}/cancel", status_code=status.HTTP_204_NO_CONTENT)
def cancel_recovery_order(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    取消回收单

    - **order_id**: 回收单ID

    取消回收单（已完成的无法取消）
    """
    recovery_service.cancel_order(db, order_id)
    return None


@router.delete("/{order_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_recovery_order(
    order_id: int,
    db: Session = Depends(get_sync_db),
    current_user = Depends(get_current_user)
):
    """
    删除回收单

    - **order_id**: 回收单ID

    只能删除已拒绝或已取消的回收单
    """
    recovery_service.delete_order(db, order_id)
    return None
