from fastapi import HTTPException from ..db import get_connection from ..utils.jwt_handler import verify_token from mysql.connector import IntegrityError def _verify_admin_permission(token: str): """公共权限验证方法""" try: payload = verify_token(token) username = payload["sub"] except ValueError as e: raise HTTPException(status_code=401, detail=str(e)) connection = get_connection() try: cursor = connection.cursor(dictionary=True) cursor.execute("SELECT user_type FROM users WHERE username = %s;", (username,)) admin_user = cursor.fetchone() if not admin_user or admin_user["user_type"] != "admin": raise HTTPException(status_code=403, detail="Permission denied") return username finally: cursor.close() connection.close() def create_game(token: str, game) -> dict: """ 服务层:创建游戏 """ # print(token) _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(status_code=500, detail="Database connection failed!") cursor = connection.cursor() try: cursor.execute( """ INSERT INTO games (game_name, game_type, description, min_players, max_players, duration, price, difficulty_level, is_available, quantity, long_description) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( game.game_name, game.game_type, game.description, game.min_players, game.max_players, game.duration, game.price, game.difficulty_level, game.is_available, game.quantity, game.long_description, ), ) connection.commit() return {"message": "游戏创建成功"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: cursor.close() connection.close() def delete_game(token: str, game_id: int) -> dict: """ 服务层:删除游戏 """ _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(status_code=500, detail="Database connection failed!") cursor = connection.cursor() try: cursor.execute("DELETE FROM games WHERE game_id = %s", (game_id,)) if cursor.rowcount == 0: raise HTTPException(status_code=404, detail="游戏不存在") connection.commit() return {"message": "删除成功"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: cursor.close() connection.close() def update_game(token: str, game_id: int, game) -> dict: """ 服务层:更新游戏信息 """ _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(status_code=500, detail="Database connection failed!") cursor = connection.cursor() try: cursor.execute( """ UPDATE games SET game_name=%s, game_type=%s, description=%s, min_players=%s, max_players=%s, duration=%s, price=%s, difficulty_level=%s , quantity=%s , is_available=%s , long_description=%s WHERE game_id=%s """, ( game.game_name, game.game_type, game.description, game.min_players, game.max_players, game.duration, game.price, game.difficulty_level, game.quantity, game.is_available, game.long_description, game_id, ), ) status = cursor.statusmessage if hasattr(cursor, "statusmessage") else "" print("数据库返回的日志:", "rowcount =", cursor.rowcount, status) if cursor.rowcount == 0: raise HTTPException(status_code=404, detail="游戏不存在") connection.commit() return {"message": "更新成功"} except Exception as e: print("数据库错误日志:", str(e)) raise HTTPException(status_code=500, detail=str(e)) finally: cursor.close() connection.close() def list_games_service(token: str): """ 服务层:获取所有游戏数据 """ print(token) _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(status_code=500, detail="Database connection failed!") cursor = connection.cursor(dictionary=True) try: cursor.execute("SELECT * FROM games") return cursor.fetchall() except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: cursor.close() connection.close() def set_the_game_photo(token: str, photo_url: str, game_id: int): """ 服务层:设置游戏图片 """ _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(status_code=500, detail="Database connection failed!") cursor = connection.cursor() try: cursor.execute( """ UPDATE games SET photo_url=%s WHERE game_id=%s """, ( photo_url, game_id, ), ) if cursor.rowcount == 0: raise HTTPException(status_code=404, detail="游戏不存在") connection.commit() return {"message": "图片设置成功"} except Exception as e: print("数据库错误日志:", str(e)) raise HTTPException(status_code=500, detail=str(e)) finally: cursor.close() connection.close() def create_tag_service(token: str, tag_name: str) -> dict: """创建标签服务""" _verify_admin_permission(token) connection = get_connection() cursor = connection.cursor() try: cursor.execute( "INSERT INTO tags (tag_name) VALUES (%s)", (tag_name,) ) connection.commit() return {"tag_id": cursor.lastrowid, "tag_name": tag_name} except IntegrityError: raise HTTPException(400, "标签已存在") finally: cursor.close() connection.close() def link_tag_to_games_service(token: str, tag_id: int, game_ids: list[int]) -> dict: """批量关联服务""" _verify_admin_permission(token) connection = get_connection() cursor = connection.cursor() try: # 检查标签存在 cursor.execute("SELECT 1 FROM tags WHERE tag_id = %s", (tag_id,)) if not cursor.fetchone(): raise HTTPException(404, "标签不存在") # 批量插入 values = [(game_id, tag_id) for game_id in game_ids] cursor.executemany( "INSERT IGNORE INTO game_tags (game_id, tag_id) VALUES (%s, %s)", values ) connection.commit() return {"linked_count": cursor.rowcount} finally: cursor.close() connection.close() def list_tags_service(token: str) -> list: """获取所有标签服务""" _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(500, "数据库连接失败") cursor = connection.cursor(dictionary=True) try: cursor.execute(""" SELECT t.tag_id, t.tag_name, COUNT(gt.game_id) AS game_count FROM tags t LEFT JOIN game_tags gt ON t.tag_id = gt.tag_id GROUP BY t.tag_id ORDER BY t.tag_id """) return cursor.fetchall() finally: cursor.close() connection.close() def get_game_tags_service(token: str, game_id: int) -> list: """获取游戏标签服务""" _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(500, "数据库连接失败") cursor = connection.cursor(dictionary=True) try: cursor.execute( """ SELECT t.tag_id, t.tag_name FROM game_tags gt JOIN tags t ON gt.tag_id = t.tag_id WHERE gt.game_id = %s """, (game_id,) ) return cursor.fetchall() finally: cursor.close() connection.close() def unlink_tag_from_game_service(token: str, tag_id: int, game_id: int) -> dict: """取消关联服务""" _verify_admin_permission(token) connection = get_connection() cursor = connection.cursor() print("tag_id:", tag_id, "game_id:", game_id) try: cursor.execute( "DELETE FROM game_tags WHERE tag_id = %s AND game_id = %s", (tag_id, game_id) ) connection.commit() return {"deleted": cursor.rowcount} finally: cursor.close() connection.close() def get_games_by_tag_service(token: str, tag_id: int) -> list: """获取标签关联游戏服务""" _verify_admin_permission(token) connection = get_connection() if not connection: raise HTTPException(500, "数据库连接失败") cursor = connection.cursor(dictionary=True) try: cursor.execute( """ SELECT g.game_id, g.game_name FROM game_tags gt JOIN games g ON gt.game_id = g.game_id WHERE gt.tag_id = %s """, (tag_id,) ) return cursor.fetchall() finally: cursor.close() connection.close() def delete_tag_service(token: str, tag_id: int) -> dict: _verify_admin_permission(token) connection = get_connection() try: with connection.cursor() as cursor: # 先删除关联关系 cursor.execute("DELETE FROM game_tags WHERE tag_id = %s", (tag_id,)) # 再删除标签 cursor.execute("DELETE FROM tags WHERE tag_id = %s", (tag_id,)) connection.commit() return {"deleted": cursor.rowcount} finally: connection.close()