from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import StreamingResponse
from ...core.database import get_db
from ...core.permission import get_current_user, is_admin_role
import io
import json

router = APIRouter()


@router.get("")
async def list_audit_logs(
    request: Request,
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    userId: str = Query(""),
    action: str = Query(""),
    targetType: str = Query(""),
    result: str = Query(""),
    startDate: str = Query(""),
    endDate: str = Query(""),
    export: str = Query(""),
    db=Depends(get_db),
):
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    conn, cur = db
    try:
        conditions = []
        params = []

        if userId:
            conditions.append("al.user_id = %s")
            params.append(userId)
        if action:
            conditions.append("al.action LIKE %s")
            params.append(f"%{action}%")
        if targetType:
            conditions.append("al.target_type = %s")
            params.append(targetType)
        if result:
            conditions.append("al.result = %s")
            params.append(result)
        if startDate:
            conditions.append("al.created_at >= %s")
            params.append(startDate)
        if endDate:
            conditions.append("al.created_at <= %s")
            params.append(f"{endDate} 23:59:59")

        where = f"WHERE {' AND '.join(conditions)}" if conditions else ""

        if export == "csv":
            await cur.execute(
                f"""SELECT al.*, u.real_name as user_real_name, u.username as user_username
                 FROM audit_logs al LEFT JOIN users u ON al.user_id = u.id
                 {where} ORDER BY al.created_at DESC""",
                params,
            )
            logs = [dict(r) for r in await cur.fetchall()]

            headers = ["ID", "用户ID", "用户名", "真实姓名", "操作类型", "对象类型", "对象ID", "详情", "IP地址", "结果", "操作时间"]
            csv_lines = [",".join(headers)]
            for log in logs:
                row = [
                    str(log.get("id", "")),
                    str(log.get("user_id", "")),
                    str(log.get("user_username") or log.get("username") or ""),
                    str(log.get("user_real_name") or ""),
                    str(log.get("action", "")),
                    str(log.get("target_type", "")),
                    str(log.get("target_id") or ""),
                    str((log.get("detail") or "").replace('"', '""')),
                    str(log.get("ip_address") or ""),
                    str(log.get("result", "")),
                    str(log.get("created_at", "")),
                ]
                csv_lines.append(",".join(f'"{c}"' for c in row))

            csv_content = "\n".join(csv_lines)
            return StreamingResponse(
                io.BytesIO(("\uFEFF" + csv_content).encode("utf-8")),
                media_type="text/csv; charset=utf-8",
                headers={"Content-Disposition": f"attachment; filename=audit_logs_{__import__('datetime').date.today().isoformat()}.csv"},
            )

        await cur.execute(f"SELECT COUNT(*) as total FROM audit_logs al {where}", params)
        total = dict(await cur.fetchone())["total"]

        offset = (page - 1) * pageSize
        await cur.execute(
            f"""SELECT al.*, u.real_name as user_real_name, u.username as user_username
             FROM audit_logs al LEFT JOIN users u ON al.user_id = u.id
             {where} ORDER BY al.created_at DESC LIMIT %s OFFSET %s""",
            params + [pageSize, offset],
        )
        logs = [dict(r) for r in await cur.fetchall()]

        return {
            "list": logs,
            "pagination": {"page": page, "pageSize": pageSize, "total": total, "totalPages": (total + pageSize - 1) // pageSize},
        }
    except Exception:
        return {"list": [], "pagination": {"page": page, "pageSize": pageSize, "total": 0, "totalPages": 0}}


@router.get("/{log_id}")
async def get_audit_log_detail(
    log_id: int,
    request: Request,
    db=Depends(get_db),
):
    """获取审计日志详情"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    conn, cur = db
    try:
        await cur.execute(
            """SELECT al.*, u.real_name as user_real_name, u.username as user_username,
                      u.email as user_email
               FROM audit_logs al 
               LEFT JOIN users u ON al.user_id = u.id
               WHERE al.id = %s""",
            (log_id,)
        )
        row = await cur.fetchone()
        
        if not row:
            return {"error": "日志不存在"}
        
        log = dict(row)
        
        # 尝试解析详情为JSON
        detail = log.get("detail", "")
        parsed_detail = None
        if detail:
            try:
                parsed_detail = json.loads(detail)
            except Exception:
                parsed_detail = detail
        
        return {
            "id": log.get("id"),
            "user_id": log.get("user_id"),
            "username": log.get("user_username") or log.get("username"),
            "real_name": log.get("user_real_name"),
            "email": log.get("user_email"),
            "action": log.get("action"),
            "target_type": log.get("target_type"),
            "target_id": log.get("target_id"),
            "detail": parsed_detail,
            "detail_raw": detail,
            "ip_address": log.get("ip_address"),
            "user_agent": log.get("user_agent"),
            "result": log.get("result"),
            "created_at": log.get("created_at").isoformat() if log.get("created_at") else None,
        }
    except Exception as e:
        return {"error": f"查询失败: {str(e)}"}


@router.get("/export")
async def export_audit_logs(
    request: Request,
    format: str = Query("csv"),
    startDate: str = Query(""),
    endDate: str = Query(""),
    userId: str = Query(""),
    action: str = Query(""),
    db=Depends(get_db),
):
    """导出审计日志"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    conn, cur = db
    try:
        conditions = []
        params = []

        if userId:
            conditions.append("al.user_id = %s")
            params.append(userId)
        if action:
            conditions.append("al.action LIKE %s")
            params.append(f"%{action}%")
        if startDate:
            conditions.append("al.created_at >= %s")
            params.append(startDate)
        if endDate:
            conditions.append("al.created_at <= %s")
            params.append(f"{endDate} 23:59:59")

        where = f"WHERE {' AND '.join(conditions)}" if conditions else ""

        await cur.execute(
            f"""SELECT al.*, u.real_name as user_real_name, u.username as user_username
             FROM audit_logs al LEFT JOIN users u ON al.user_id = u.id
             {where} ORDER BY al.created_at DESC""",
            params,
        )
        logs = [dict(r) for r in await cur.fetchall()]

        if format == "csv":
            headers = ["ID", "用户ID", "用户名", "真实姓名", "操作类型", "对象类型", "对象ID", "详情", "IP地址", "结果", "操作时间"]
            csv_lines = [",".join(headers)]
            for log in logs:
                row = [
                    str(log.get("id", "")),
                    str(log.get("user_id", "")),
                    str(log.get("user_username") or log.get("username") or ""),
                    str(log.get("user_real_name") or ""),
                    str(log.get("action", "")),
                    str(log.get("target_type", "")),
                    str(log.get("target_id") or ""),
                    str((log.get("detail") or "").replace('"', '""')),
                    str(log.get("ip_address") or ""),
                    str(log.get("result", "")),
                    str(log.get("created_at", "")),
                ]
                csv_lines.append(",".join(f'"{c}"' for c in row))

            csv_content = "\n".join(csv_lines)
            return StreamingResponse(
                io.BytesIO(("\uFEFF" + csv_content).encode("utf-8")),
                media_type="text/csv; charset=utf-8",
                headers={"Content-Disposition": f"attachment; filename=audit_logs_export_{__import__('datetime').date.today().isoformat()}.csv"},
            )
        else:
            # Excel格式（简化版，返回JSON数据）
            return {
                "data": logs,
                "total": len(logs),
                "format": format
            }
    except Exception as e:
        return {"error": f"导出失败: {str(e)}"}
