"""
执法人员列表 API — 个人中心 → 执法人员管理 + 案件表单模糊搜索
"""
from fastapi import APIRouter, Depends, Request, Query
from ...core.database import get_db
from ...core.permission import require_login
from ...utils.request_utils import safe_json

router = APIRouter()


@router.get("/officers")
async def list_officers(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """获取执法人员列表"""
    user_id = user.get("userId", "1")
    conn, cur = db

    await cur.execute(
        """SELECT id, name, badge_number, sort_order, created_at
           FROM law_enforcement_officers
           WHERE user_id = %s AND is_active = 1
           ORDER BY sort_order, id""",
        (user_id,),
    )
    rows = await cur.fetchall()
    return {"success": True, "data": [dict(r) for r in rows]}


@router.get("/officers/search")
async def search_officers(
    q: str = Query("", description="搜索关键词（姓名模糊匹配）"),
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """模糊搜索执法人员（案件表单使用），返回姓名+证号"""
    user_id = user.get("userId", "1")
    conn, cur = db

    if not q or not q.strip():
        return {"success": True, "data": []}

    await cur.execute(
        """SELECT id, name, badge_number
           FROM law_enforcement_officers
           WHERE user_id = %s AND is_active = 1 AND name LIKE %s
           ORDER BY name, id
           LIMIT 20""",
        (user_id, f"%{q.strip()}%"),
    )
    rows = await cur.fetchall()
    return {"success": True, "data": [dict(r) for r in rows]}


@router.post("/officers")
async def add_officer(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """添加执法人员"""
    user_id = user.get("userId", "1")
    conn, cur = db
    body = await safe_json(request)

    name = (body.get("name") or "").strip()
    badge_number = (body.get("badge_number") or "").strip()

    if not name:
        return {"success": False, "error": "姓名不能为空"}
    if not badge_number:
        return {"success": False, "error": "执法证号不能为空"}

    await cur.execute(
        """INSERT INTO law_enforcement_officers (user_id, name, badge_number)
           VALUES (%s, %s, %s)""",
        (user_id, name, badge_number),
    )
    return {"success": True, "message": "添加成功", "data": {"id": cur.lastrowid, "name": name, "badge_number": badge_number}}


@router.put("/officers/{officer_id}")
async def update_officer(
    officer_id: int,
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """编辑执法人员"""
    user_id = user.get("userId", "1")
    conn, cur = db
    body = await safe_json(request)

    name = (body.get("name") or "").strip()
    badge_number = (body.get("badge_number") or "").strip()

    if not name:
        return {"success": False, "error": "姓名不能为空"}
    if not badge_number:
        return {"success": False, "error": "执法证号不能为空"}

    await cur.execute(
        """UPDATE law_enforcement_officers
           SET name = %s, badge_number = %s, updated_at = NOW()
           WHERE id = %s AND user_id = %s AND is_active = 1""",
        (name, badge_number, officer_id, user_id),
    )
    if cur.rowcount == 0:
        return {"success": False, "error": "记录不存在或无权编辑"}
    return {"success": True, "message": "更新成功"}


@router.delete("/officers/{officer_id}")
async def delete_officer(
    officer_id: int,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """删除执法人员（软删除）"""
    user_id = user.get("userId", "1")
    conn, cur = db

    await cur.execute(
        """UPDATE law_enforcement_officers
           SET is_active = 0, updated_at = NOW()
           WHERE id = %s AND user_id = %s AND is_active = 1""",
        (officer_id, user_id),
    )
    if cur.rowcount == 0:
        return {"success": False, "error": "记录不存在或无权删除"}
    return {"success": True, "message": "已删除"}
