"""
资产调拨管理API路由
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from app.core.deps import get_db, get_current_user
from app.schemas.transfer import (
    AssetTransferOrderCreate,
    AssetTransferOrderUpdate,
    AssetTransferOrderWithRelations,
    AssetTransferOrderQueryParams,
    AssetTransferStatistics
)
from app.services.transfer_service import transfer_service

router = APIRouter()


@router.get("/", response_model=list)
def get_transfer_orders(
    skip: int = Query(0, ge=0, description="跳过条数"),
    limit: int = Query(20, ge=1, le=100, description="返回条数"),
    transfer_type: Optional[str] = Query(None, description="调拨类型"),
    approval_status: Optional[str] = Query(None, description="审批状态"),
    execute_status: Optional[str] = Query(None, description="执行状态"),
    source_org_id: Optional[int] = Query(None, description="调出网点ID"),
    target_org_id: Optional[int] = Query(None, description="调入网点ID"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取调拨单列表

    - **skip**: 跳过条数
    - **limit**: 返回条数（最大100）
    - **transfer_type**: 调拨类型（internal=内部调拨/external=跨机构调拨）
    - **approval_status**: 审批状态（pending/approved/rejected/cancelled）
    - **execute_status**: 执行状态（pending/executing/completed/cancelled）
    - **source_org_id**: 调出网点ID
    - **target_org_id**: 调入网点ID
    - **keyword**: 搜索关键词（单号/标题）
    """
    items, total = transfer_service.get_orders(
        db=db,
        skip=skip,
        limit=limit,
        transfer_type=transfer_type,
        approval_status=approval_status,
        execute_status=execute_status,
        source_org_id=source_org_id,
        target_org_id=target_org_id,
        keyword=keyword
    )
    return items


@router.get("/statistics", response_model=AssetTransferStatistics)
def get_transfer_statistics(
    source_org_id: Optional[int] = Query(None, description="调出网点ID"),
    target_org_id: Optional[int] = Query(None, description="调入网点ID"),
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取调拨单统计信息

    - **source_org_id**: 调出网点ID（可选）
    - **target_org_id**: 调入网点ID（可选）

    返回调拨单总数、待审批数、已审批数等统计信息
    """
    return transfer_service.get_statistics(db, source_org_id, target_org_id)


@router.get("/{order_id}", response_model=dict)
def get_transfer_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取调拨单详情

    - **order_id**: 调拨单ID

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


@router.get("/{order_id}/items", response_model=list)
def get_transfer_order_items(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取调拨单明细列表

    - **order_id**: 调拨单ID

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


@router.post("/", response_model=dict, status_code=status.HTTP_201_CREATED)
def create_transfer_order(
    obj_in: AssetTransferOrderCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    创建调拨单

    - **source_org_id**: 调出网点ID
    - **target_org_id**: 调入网点ID
    - **transfer_type**: 调拨类型（internal=内部调拨/external=跨机构调拨）
    - **title**: 标题
    - **asset_ids**: 资产ID列表
    - **remark**: 备注

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


@router.put("/{order_id}", response_model=dict)
def update_transfer_order(
    order_id: int,
    obj_in: AssetTransferOrderUpdate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    更新调拨单

    - **order_id**: 调拨单ID
    - **title**: 标题
    - **remark**: 备注

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


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

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

    审批通过后可以开始执行调拨
    """
    return transfer_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_transfer_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    开始调拨

    - **order_id**: 调拨单ID

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


@router.post("/{order_id}/complete", response_model=dict)
def complete_transfer_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    完成调拨

    - **order_id**: 调拨单ID

    完成调拨单，自动更新资产机构和状态
    """
    return transfer_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_transfer_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    取消调拨单

    - **order_id**: 调拨单ID

    取消调拨单（已完成的无法取消）
    """
    transfer_service.cancel_order(db, order_id)
    return None


@router.delete("/{order_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_transfer_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    删除调拨单

    - **order_id**: 调拨单ID

    只能删除已拒绝或已取消的调拨单
    """
    transfer_service.delete_order(db, order_id)
    return None
