"""
资产分配管理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.allocation import (
    AllocationOrderCreate,
    AllocationOrderUpdate,
    AllocationOrderApproval,
    AllocationOrderWithRelations,
    AllocationItemResponse,
    AllocationOrderQueryParams,
    AllocationOrderStatistics
)
from app.services.allocation_service import allocation_service

router = APIRouter()


@router.get("/", response_model=list)
def get_allocation_orders(
    skip: int = Query(0, ge=0, description="跳过条数"),
    limit: int = Query(20, ge=1, le=100, description="返回条数"),
    order_type: Optional[str] = Query(None, description="单据类型"),
    approval_status: Optional[str] = Query(None, description="审批状态"),
    execute_status: Optional[str] = Query(None, description="执行状态"),
    applicant_id: Optional[int] = Query(None, description="申请人ID"),
    target_organization_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）
    - **order_type**: 单据类型（allocation/transfer/recovery/maintenance/scrap）
    - **approval_status**: 审批状态（pending/approved/rejected/cancelled）
    - **execute_status**: 执行状态（pending/executing/completed/cancelled）
    - **applicant_id**: 申请人ID
    - **target_organization_id**: 目标网点ID
    - **keyword**: 搜索关键词（单号/标题）
    """
    items, total = allocation_service.get_orders(
        db=db,
        skip=skip,
        limit=limit,
        order_type=order_type,
        approval_status=approval_status,
        execute_status=execute_status,
        applicant_id=applicant_id,
        target_organization_id=target_organization_id,
        keyword=keyword
    )
    return items


@router.get("/statistics", response_model=AllocationOrderStatistics)
def get_allocation_statistics(
    applicant_id: Optional[int] = Query(None, description="申请人ID"),
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取分配单统计信息

    - **applicant_id**: 申请人ID（可选）

    返回分配单总数、待审批数、已审批数等统计信息
    """
    return allocation_service.get_statistics(db, applicant_id)


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

    - **order_id**: 分配单ID

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


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

    - **order_id**: 分配单ID

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


@router.post("/", response_model=dict, status_code=status.HTTP_201_CREATED)
def create_allocation_order(
    obj_in: AllocationOrderCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    创建分配单

    - **order_type**: 单据类型
      - allocation: 资产分配（从仓库分配给网点）
      - transfer: 资产调拨（网点间调拨）
      - recovery: 资产回收（从使用中回收）
      - maintenance: 维修分配
      - scrap: 报废分配
    - **title**: 标题
    - **source_organization_id**: 调出网点ID（可选，调拨时必填）
    - **target_organization_id**: 调入网点ID
    - **asset_ids**: 资产ID列表
    - **expect_execute_date**: 预计执行日期
    - **remark**: 备注
    """
    return allocation_service.create_order(
        db=db,
        obj_in=obj_in,
        applicant_id=current_user.id
    )


@router.put("/{order_id}", response_model=dict)
def update_allocation_order(
    order_id: int,
    obj_in: AllocationOrderUpdate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    更新分配单

    - **order_id**: 分配单ID
    - **title**: 标题
    - **expect_execute_date**: 预计执行日期
    - **remark**: 备注

    只有待审批状态的分配单可以更新
    """
    return allocation_service.update_order(
        db=db,
        order_id=order_id,
        obj_in=obj_in,
        updater_id=current_user.id
    )


@router.post("/{order_id}/approve", response_model=dict)
def approve_allocation_order(
    order_id: int,
    approval_in: AllocationOrderApproval,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    审批分配单

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

    审批通过后会自动执行资产分配逻辑
    """
    return allocation_service.approve_order(
        db=db,
        order_id=order_id,
        approval_in=approval_in,
        approver_id=current_user.id
    )


@router.post("/{order_id}/execute", response_model=dict)
def execute_allocation_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    执行分配单

    - **order_id**: 分配单ID

    手动执行已审批通过的分配单
    """
    return allocation_service.execute_order(
        db=db,
        order_id=order_id,
        executor_id=current_user.id
    )


@router.post("/{order_id}/cancel", status_code=status.HTTP_204_NO_CONTENT)
def cancel_allocation_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    取消分配单

    - **order_id**: 分配单ID

    取消分配单（已完成的无法取消）
    """
    allocation_service.cancel_order(db, order_id)
    return None


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

    - **order_id**: 分配单ID

    只能删除草稿、已拒绝或已取消的分配单
    """
    allocation_service.delete_order(db, order_id)
    return None
