"""
机构网点业务服务层
"""
from typing import List, Optional, Tuple
from sqlalchemy.orm import Session
from app.crud.organization import organization
from app.schemas.organization import OrganizationCreate, OrganizationUpdate
from app.core.exceptions import NotFoundException, AlreadyExistsException


class OrganizationService:
    """机构网点服务类"""

    def get_organization(self, db: Session, org_id: int):
        """
        获取机构详情

        Args:
            db: 数据库会话
            org_id: 机构ID

        Returns:
            机构对象

        Raises:
            NotFoundException: 机构不存在
        """
        obj = organization.get(db, org_id)
        if not obj:
            raise NotFoundException("机构")
        return obj

    def get_organizations(
        self,
        db: Session,
        skip: int = 0,
        limit: int = 20,
        org_type: Optional[str] = None,
        status: Optional[str] = None,
        keyword: Optional[str] = None
    ) -> Tuple[List, int]:
        """
        获取机构列表

        Args:
            db: 数据库会话
            skip: 跳过条数
            limit: 返回条数
            org_type: 机构类型
            status: 状态
            keyword: 搜索关键词

        Returns:
            (机构列表, 总数)
        """
        return organization.get_multi(
            db=db,
            skip=skip,
            limit=limit,
            org_type=org_type,
            status=status,
            keyword=keyword
        )

    def get_organization_tree(
        self,
        db: Session,
        status: Optional[str] = None
    ) -> List:
        """
        获取机构树

        Args:
            db: 数据库会话
            status: 状态筛选

        Returns:
            机构树列表
        """
        return organization.get_tree(db, status)

    def get_organization_children(
        self,
        db: Session,
        parent_id: int
    ) -> List:
        """
        获取直接子机构

        Args:
            db: 数据库会话
            parent_id: 父机构ID

        Returns:
            子机构列表

        Raises:
            NotFoundException: 父机构不存在
        """
        if parent_id > 0 and not organization.get(db, parent_id):
            raise NotFoundException("父机构")

        return organization.get_children(db, parent_id)

    def get_all_children(
        self,
        db: Session,
        parent_id: int
    ) -> List:
        """
        递归获取所有子机构

        Args:
            db: 数据库会话
            parent_id: 父机构ID

        Returns:
            所有子机构列表

        Raises:
            NotFoundException: 父机构不存在
        """
        if not organization.get(db, parent_id):
            raise NotFoundException("机构")

        return organization.get_all_children(db, parent_id)

    def get_parents(
        self,
        db: Session,
        child_id: int
    ) -> List:
        """
        递归获取所有父机构

        Args:
            db: 数据库会话
            child_id: 子机构ID

        Returns:
            所有父机构列表

        Raises:
            NotFoundException: 机构不存在
        """
        if not organization.get(db, child_id):
            raise NotFoundException("机构")

        return organization.get_parents(db, child_id)

    def create_organization(
        self,
        db: Session,
        obj_in: OrganizationCreate,
        creator_id: Optional[int] = None
    ):
        """
        创建机构

        Args:
            db: 数据库会话
            obj_in: 创建数据
            creator_id: 创建人ID

        Returns:
            创建的机构对象

        Raises:
            AlreadyExistsException: 机构代码已存在
            NotFoundException: 父机构不存在
        """
        try:
            return organization.create(db, obj_in, creator_id)
        except ValueError as e:
            if "不存在" in str(e):
                raise NotFoundException("父机构") from e
            raise AlreadyExistsException("机构") from e

    def update_organization(
        self,
        db: Session,
        org_id: int,
        obj_in: OrganizationUpdate,
        updater_id: Optional[int] = None
    ):
        """
        更新机构

        Args:
            db: 数据库会话
            org_id: 机构ID
            obj_in: 更新数据
            updater_id: 更新人ID

        Returns:
            更新后的机构对象

        Raises:
            NotFoundException: 机构不存在
        """
        db_obj = organization.get(db, org_id)
        if not db_obj:
            raise NotFoundException("机构")

        try:
            return organization.update(db, db_obj, obj_in, updater_id)
        except ValueError as e:
            if "不存在" in str(e):
                raise NotFoundException("父机构") from e
            raise

    def delete_organization(
        self,
        db: Session,
        org_id: int,
        deleter_id: Optional[int] = None
    ) -> bool:
        """
        删除机构

        Args:
            db: 数据库会话
            org_id: 机构ID
            deleter_id: 删除人ID

        Returns:
            是否删除成功

        Raises:
            NotFoundException: 机构不存在
            ValueError: 机构下存在子机构
        """
        if not organization.get(db, org_id):
            raise NotFoundException("机构")

        try:
            return organization.delete(db, org_id, deleter_id)
        except ValueError as e:
            if "子机构" in str(e):
                raise ValueError("该机构下存在子机构，无法删除") from e
            raise


# 创建全局实例
organization_service = OrganizationService()
