# 此文件备份了admin.py中的positions相关路由代码
# 这些路由已移至positions.py，为避免冲突，从admin.py中移除

@router.get("/positions")
async def list_positions(
    keyword: Optional[str] = Query(None, description="关键词"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    """
    获取岗位列表（stub 数据）

    返回结构兼容前端：data.list/total/page/pageSize
    """
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    try:
        items = _sample_positions()
        if keyword:
            kw = keyword.lower()
            items = [
                p for p in items if kw in (p.get("name", "") + p.get("description", "")).lower()
            ]

        total = len(items)
        start = (page - 1) * pageSize
        end = start + pageSize
        page_items = items[start:end]

        return ResponseModel(
            code=200,
            message="获取岗位列表成功",
            data={
                "list": page_items,
                "total": total,
                "page": page,
                "pageSize": pageSize,
            },
        )
    except Exception as exc:
        # 记录错误堆栈由全局异常中间件处理；此处返回统一结构
        return ResponseModel(code=500, message=f"服务器错误：{exc}")


@router.get("/positions/tree")
async def get_position_tree(
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    """
    获取岗位树（stub 数据）
    """
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    try:
        items = _sample_positions()
        id_to_node: Dict[int, Dict[str, Any]] = {}
        for p in items:
            node = {**p, "children": []}
            id_to_node[p["id"]] = node

        roots: List[Dict[str, Any]] = []
        for p in items:
            parent_id = p.get("parentId")
            if parent_id and parent_id in id_to_node:
                id_to_node[parent_id]["children"].append(id_to_node[p["id"]])
            else:
                roots.append(id_to_node[p["id"]])

        return ResponseModel(code=200, message="获取岗位树成功", data=roots)
    except Exception as exc:
        return ResponseModel(code=500, message=f"服务器错误：{exc}")


@router.get("/positions/{position_id}")
async def get_position_detail(
    position_id: int,
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    items = _sample_positions()
    for p in items:
        if p["id"] == position_id:
            return ResponseModel(code=200, message="获取岗位详情成功", data=p)
    return ResponseModel(code=404, message="岗位不存在")


@router.get("/positions/{position_id}/check-delete")
async def check_position_delete(
    position_id: int,
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    # stub：允许删除非根岗位
    deletable = position_id != 1
    reason = "根岗位不允许删除" if not deletable else ""
    return ResponseModel(code=200, message="检查成功", data={"deletable": deletable, "reason": reason})


@router.post("/positions")
async def create_position(
    payload: Dict[str, Any],
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    # stub：直接回显并附带一个伪ID
    payload = dict(payload)
    payload.setdefault("id", 999)
    payload.setdefault("createTime", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    return ResponseModel(code=200, message="创建岗位成功", data=payload)


@router.put("/positions/{position_id}")
async def update_position(
    position_id: int,
    payload: Dict[str, Any],
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    # stub：直接回显
    updated = {"id": position_id, **payload}
    return ResponseModel(code=200, message="更新岗位成功", data=updated)


@router.delete("/positions/{position_id}")
async def delete_position(
    position_id: int,
    current_user: User = Depends(get_current_user),
    _db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    not_admin = _ensure_admin(current_user)
    if not_admin:
        return not_admin

    # stub：直接返回成功
    return ResponseModel(code=200, message="删除岗位成功", data={"id": position_id})
