"""
资产调拨相关CRUD操作
"""
from typing import List, Optional, Tuple
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from app.models.transfer import AssetTransferOrder, AssetTransferItem
from app.models.asset import Asset
from app.schemas.transfer import AssetTransferOrderCreate, AssetTransferOrderUpdate


class AssetTransferOrderCRUD:
    """调拨单CRUD操作"""

    def get(self, db: Session, id: int) -> Optional[AssetTransferOrder]:
        """根据ID获取调拨单"""
        return db.query(AssetTransferOrder).filter(
            AssetTransferOrder.id == id
        ).first()

    def get_by_code(self, db: Session, order_code: str) -> Optional[AssetTransferOrder]:
        """根据单号获取调拨单"""
        return db.query(AssetTransferOrder).filter(
            AssetTransferOrder.order_code == order_code
        ).first()

    def get_multi(
        self,
        db: Session,
        skip: int = 0,
        limit: int = 20,
        transfer_type: Optional[str] = None,
        approval_status: Optional[str] = None,
        execute_status: Optional[str] = None,
        source_org_id: Optional[int] = None,
        target_org_id: Optional[int] = None,
        keyword: Optional[str] = None
    ) -> Tuple[List[AssetTransferOrder], int]:
        """获取调拨单列表"""
        query = db.query(AssetTransferOrder)

        # 筛选条件
        if transfer_type:
            query = query.filter(AssetTransferOrder.transfer_type == transfer_type)
        if approval_status:
            query = query.filter(AssetTransferOrder.approval_status == approval_status)
        if execute_status:
            query = query.filter(AssetTransferOrder.execute_status == execute_status)
        if source_org_id:
            query = query.filter(AssetTransferOrder.source_org_id == source_org_id)
        if target_org_id:
            query = query.filter(AssetTransferOrder.target_org_id == target_org_id)
        if keyword:
            query = query.filter(
                or_(
                    AssetTransferOrder.order_code.like(f"%{keyword}%"),
                    AssetTransferOrder.title.like(f"%{keyword}%")
                )
            )

        # 排序
        query = query.order_by(AssetTransferOrder.created_at.desc())

        # 总数
        total = query.count()

        # 分页
        items = query.offset(skip).limit(limit).all()

        return items, total

    def create(
        self,
        db: Session,
        obj_in: AssetTransferOrderCreate,
        order_code: str,
        apply_user_id: int
    ) -> AssetTransferOrder:
        """创建调拨单"""
        from datetime import datetime

        # 创建调拨单
        db_obj = AssetTransferOrder(
            order_code=order_code,
            source_org_id=obj_in.source_org_id,
            target_org_id=obj_in.target_org_id,
            transfer_type=obj_in.transfer_type,
            title=obj_in.title,
            asset_count=len(obj_in.asset_ids),
            apply_user_id=apply_user_id,
            apply_time=datetime.utcnow(),
            remark=obj_in.remark,
            approval_status="pending",
            execute_status="pending"
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)

        # 创建调拨单明细
        self._create_items(
            db=db,
            order_id=db_obj.id,
            asset_ids=obj_in.asset_ids,
            source_org_id=obj_in.source_org_id,
            target_org_id=obj_in.target_org_id
        )

        return db_obj

    def update(
        self,
        db: Session,
        db_obj: AssetTransferOrder,
        obj_in: AssetTransferOrderUpdate
    ) -> AssetTransferOrder:
        """更新调拨单"""
        update_data = obj_in.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_obj, field, value)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def approve(
        self,
        db: Session,
        db_obj: AssetTransferOrder,
        approval_status: str,
        approval_user_id: int,
        approval_remark: Optional[str] = None
    ) -> AssetTransferOrder:
        """审批调拨单"""
        from datetime import datetime

        db_obj.approval_status = approval_status
        db_obj.approval_user_id = approval_user_id
        db_obj.approval_time = datetime.utcnow()
        db_obj.approval_remark = approval_remark

        # 如果审批通过，自动设置为可执行状态
        if approval_status == "approved":
            db_obj.execute_status = "pending"
        elif approval_status == "rejected":
            db_obj.execute_status = "cancelled"

        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def start(
        self,
        db: Session,
        db_obj: AssetTransferOrder,
        execute_user_id: int
    ) -> AssetTransferOrder:
        """开始调拨"""
        from datetime import datetime

        db_obj.execute_status = "executing"
        db_obj.execute_user_id = execute_user_id
        db_obj.execute_time = datetime.utcnow()

        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def complete(
        self,
        db: Session,
        db_obj: AssetTransferOrder,
        execute_user_id: int
    ) -> AssetTransferOrder:
        """完成调拨"""
        from datetime import datetime

        db_obj.execute_status = "completed"
        db_obj.execute_user_id = execute_user_id
        db_obj.execute_time = datetime.utcnow()

        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def cancel(self, db: Session, db_obj: AssetTransferOrder) -> AssetTransferOrder:
        """取消调拨单"""
        db_obj.approval_status = "cancelled"
        db_obj.execute_status = "cancelled"
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def delete(self, db: Session, id: int) -> bool:
        """删除调拨单"""
        obj = self.get(db, id)
        if obj:
            db.delete(obj)
            db.commit()
            return True
        return False

    def get_statistics(
        self,
        db: Session,
        source_org_id: Optional[int] = None,
        target_org_id: Optional[int] = None
    ) -> dict:
        """获取调拨单统计信息"""
        query = db.query(AssetTransferOrder)

        if source_org_id:
            query = query.filter(AssetTransferOrder.source_org_id == source_org_id)
        if target_org_id:
            query = query.filter(AssetTransferOrder.target_org_id == target_org_id)

        total = query.count()
        pending = query.filter(AssetTransferOrder.approval_status == "pending").count()
        approved = query.filter(AssetTransferOrder.approval_status == "approved").count()
        rejected = query.filter(AssetTransferOrder.approval_status == "rejected").count()
        executing = query.filter(AssetTransferOrder.execute_status == "executing").count()
        completed = query.filter(AssetTransferOrder.execute_status == "completed").count()

        return {
            "total": total,
            "pending": pending,
            "approved": approved,
            "rejected": rejected,
            "executing": executing,
            "completed": completed
        }

    def _create_items(
        self,
        db: Session,
        order_id: int,
        asset_ids: List[int],
        source_org_id: int,
        target_org_id: int
    ):
        """创建调拨单明细"""
        # 查询资产信息
        assets = db.query(Asset).filter(Asset.id.in_(asset_ids)).all()

        for asset in assets:
            item = AssetTransferItem(
                order_id=order_id,
                asset_id=asset.id,
                asset_code=asset.asset_code,
                source_organization_id=source_org_id,
                target_organization_id=target_org_id,
                transfer_status="pending"
            )
            db.add(item)

        db.commit()


class AssetTransferItemCRUD:
    """调拨单明细CRUD操作"""

    def get_by_order(self, db: Session, order_id: int) -> List[AssetTransferItem]:
        """根据调拨单ID获取明细列表"""
        return db.query(AssetTransferItem).filter(
            AssetTransferItem.order_id == order_id
        ).order_by(AssetTransferItem.id).all()

    def get_multi(
        self,
        db: Session,
        skip: int = 0,
        limit: int = 20,
        order_id: Optional[int] = None,
        transfer_status: Optional[str] = None
    ) -> Tuple[List[AssetTransferItem], int]:
        """获取明细列表"""
        query = db.query(AssetTransferItem)

        if order_id:
            query = query.filter(AssetTransferItem.order_id == order_id)
        if transfer_status:
            query = query.filter(AssetTransferItem.transfer_status == transfer_status)

        total = query.count()
        items = query.offset(skip).limit(limit).all()

        return items, total

    def update_transfer_status(
        self,
        db: Session,
        item_id: int,
        transfer_status: str
    ) -> AssetTransferItem:
        """更新明细调拨状态"""
        item = db.query(AssetTransferItem).filter(
            AssetTransferItem.id == item_id
        ).first()

        if item:
            item.transfer_status = transfer_status
            db.add(item)
            db.commit()
            db.refresh(item)

        return item

    def batch_update_transfer_status(
        self,
        db: Session,
        order_id: int,
        transfer_status: str
    ):
        """批量更新明细调拨状态"""
        items = db.query(AssetTransferItem).filter(
            and_(
                AssetTransferItem.order_id == order_id,
                AssetTransferItem.transfer_status == "pending"
            )
        ).all()

        for item in items:
            item.transfer_status = transfer_status
            db.add(item)

        db.commit()


# 创建全局实例
transfer_order = AssetTransferOrderCRUD()
transfer_item = AssetTransferItemCRUD()
