from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query, Request

from ...core.logger import AppLogger
from ...core.permissions import PERMISSION_EMPLOYEE_MANAGE, PERMISSION_EMPLOYEE_VIEW
from ...database.orm import UserORM
from ...services import EmployeeService, OperationLogService
from ..dependencies import get_employee_service, get_operation_log_service, require_permission
from ..request_meta import operation_request_meta
from ..schemas.employee import EmployeeListResponse, EmployeeNoResponse, EmployeeRequest, EmployeeResponse, EmployeeUpdateRequest

router = APIRouter(prefix="/api/employees", tags=["employees"])
logger = AppLogger.get_logger(__name__)


@router.get("/next-no", response_model=EmployeeNoResponse)
def preview_next_employee_no(
    http_request: Request,
    current_user: UserORM = Depends(require_permission(PERMISSION_EMPLOYEE_MANAGE)),
    service: EmployeeService = Depends(get_employee_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> EmployeeNoResponse:
    """预览下一个系统员工编号。"""
    employee_no = service.preview_next_employee_no()
    operation_logs.record(
        actor=current_user,
        module="system",
        action="employee.next_no",
        target_type="employee",
        target_id=employee_no,
        status="success",
        detail=f"预览员工编号 employee_no={employee_no}",
        **operation_request_meta(http_request),
    )
    return EmployeeNoResponse(employee_no=employee_no)


@router.get("", response_model=list[EmployeeResponse])
def list_employees(
    http_request: Request,
    keyword: str | None = Query(default=None, description="员工编号、姓名、部门、岗位等关键字"),
    employee_keyword: str | None = Query(default=None, description="员工信息关键字：编号、姓名、钉钉用户ID或手机号"),
    organization_keyword: str | None = Query(default=None, description="组织信息关键字：部门或岗位"),
    employment_status: str | None = Query(default=None, description="员工状态：active或inactive"),
    current_user: UserORM = Depends(require_permission(PERMISSION_EMPLOYEE_VIEW)),
    service: EmployeeService = Depends(get_employee_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> list[EmployeeResponse]:
    """查询员工档案。"""
    try:
        employees = service.list_employees(
            keyword=keyword,
            employee_keyword=employee_keyword,
            organization_keyword=organization_keyword,
            employment_status=employment_status,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="system",
        action="employee.list",
        target_type="employee",
        target_id="",
        status="success",
        detail=f"查询员工列表 count={len(employees)}",
        **operation_request_meta(http_request),
    )
    return [EmployeeResponse.from_orm_model(employee) for employee in employees]


@router.get("/page", response_model=EmployeeListResponse)
def list_employees_page(
    http_request: Request,
    page: int = Query(default=1, ge=1, description="页码，从1开始"),
    page_size: int = Query(default=10, ge=1, le=100, description="每页条数，最大100"),
    keyword: str | None = Query(default=None, description="员工编号、姓名、部门、岗位等关键字"),
    employee_keyword: str | None = Query(default=None, description="员工信息关键字：编号、姓名、钉钉用户ID或手机号"),
    organization_keyword: str | None = Query(default=None, description="组织信息关键字：部门或岗位"),
    employment_status: str | None = Query(default=None, description="员工状态：active或inactive"),
    current_user: UserORM = Depends(require_permission(PERMISSION_EMPLOYEE_VIEW)),
    service: EmployeeService = Depends(get_employee_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> EmployeeListResponse:
    """分页查询员工档案，员工维护页面使用。"""
    try:
        page_data = service.list_employees_page(
            page=page,
            page_size=page_size,
            keyword=keyword,
            employee_keyword=employee_keyword,
            organization_keyword=organization_keyword,
            employment_status=employment_status,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="system",
        action="employee.page",
        target_type="employee",
        target_id="",
        status="success",
        detail=f"分页查询员工列表 total={page_data.total} page={page_data.page} page_size={page_data.page_size}",
        **operation_request_meta(http_request),
    )
    return EmployeeListResponse.from_page(page_data)


@router.get("/{employee_id}", response_model=EmployeeResponse)
def get_employee(
    http_request: Request,
    employee_id: int,
    current_user: UserORM = Depends(require_permission(PERMISSION_EMPLOYEE_VIEW)),
    service: EmployeeService = Depends(get_employee_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> EmployeeResponse:
    """查询员工详情，供编辑时回填最新数据。"""
    try:
        employee = service.get_employee(employee_id)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="system",
        action="employee.detail",
        target_type="employee",
        target_id=str(employee.id),
        status="success",
        detail=f"查询员工详情 employee_no={employee.employee_no} name={employee.name}",
        **operation_request_meta(http_request),
    )
    return EmployeeResponse.from_orm_model(employee)


@router.post("", response_model=EmployeeResponse)
def create_employee(
    http_request: Request,
    request: EmployeeRequest,
    current_user: UserORM = Depends(require_permission(PERMISSION_EMPLOYEE_MANAGE)),
    service: EmployeeService = Depends(get_employee_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> EmployeeResponse:
    """新增员工档案。"""
    try:
        employee = service.create_employee(**request.model_dump())
    except ValueError as exc:
        operation_logs.record(
            actor=current_user,
            module="system",
            action="employee.create",
            target_type="employee",
            target_id=request.employee_no,
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("新增员工失败 employee_no=%s reason=%s", request.employee_no, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="system",
        action="employee.create",
        target_type="employee",
        target_id=str(employee.id),
        status="success",
        detail=f"新增员工成功 employee_no={employee.employee_no} name={employee.name}",
        **operation_request_meta(http_request),
    )
    return EmployeeResponse.from_orm_model(employee)


@router.patch("/{employee_id}", response_model=EmployeeResponse)
@router.put("/{employee_id}", response_model=EmployeeResponse)
def update_employee(
    http_request: Request,
    employee_id: int,
    request: EmployeeUpdateRequest,
    current_user: UserORM = Depends(require_permission(PERMISSION_EMPLOYEE_MANAGE)),
    service: EmployeeService = Depends(get_employee_service),
    operation_logs: OperationLogService = Depends(get_operation_log_service),
) -> EmployeeResponse:
    """更新员工档案。"""
    try:
        employee = service.update_employee(employee_id, **request.model_dump(exclude_unset=True))
    except ValueError as exc:
        operation_logs.record(
            actor=current_user,
            module="system",
            action="employee.update",
            target_type="employee",
            target_id=str(employee_id),
            status="failed",
            detail=str(exc),
            **operation_request_meta(http_request),
        )
        logger.error("更新员工失败 employee_id=%s reason=%s", employee_id, exc)
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    operation_logs.record(
        actor=current_user,
        module="system",
        action="employee.update",
        target_type="employee",
        target_id=str(employee.id),
        status="success",
        detail=f"更新员工成功 employee_no={employee.employee_no} name={employee.name}",
        **operation_request_meta(http_request),
    )
    return EmployeeResponse.from_orm_model(employee)
