from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel, Field

from ...database.orm import EmployeeORM
from ...services import EmployeePage


class EmployeeRequest(BaseModel):
    """员工维护请求。"""

    employee_no: str = Field(default="", max_length=64)
    name: str = Field(..., min_length=1, max_length=128)
    dingtalk_user_id: str = Field(default="", max_length=128)
    department: str = Field(default="", max_length=128)
    position: str = Field(default="", max_length=128)
    phone: str = Field(default="", max_length=32)
    employment_status: str = Field(default="active", max_length=32)
    remark: str = ""


class EmployeeUpdateRequest(BaseModel):
    """员工编辑请求，员工编号由后端保留，不需要前端维护。"""

    employee_no: str = Field(default="", max_length=64)
    name: str | None = Field(default=None, min_length=1, max_length=128)
    dingtalk_user_id: str | None = Field(default=None, max_length=128)
    department: str | None = Field(default=None, max_length=128)
    position: str | None = Field(default=None, max_length=128)
    phone: str | None = Field(default=None, max_length=32)
    employment_status: str | None = Field(default=None, max_length=32)
    remark: str | None = None


class EmployeeResponse(BaseModel):
    """员工档案响应。"""

    id: int
    employee_no: str
    name: str
    dingtalk_user_id: str
    department: str
    position: str
    phone: str
    employment_status: str
    remark: str
    created_at: datetime
    updated_at: datetime

    @classmethod
    def from_orm_model(cls, employee: EmployeeORM) -> "EmployeeResponse":
        return cls(
            id=employee.id,
            employee_no=employee.employee_no,
            name=employee.name,
            dingtalk_user_id=employee.dingtalk_user_id,
            department=employee.department,
            position=employee.position,
            phone=employee.phone,
            employment_status=employee.employment_status,
            remark=employee.remark,
            created_at=employee.created_at,
            updated_at=employee.updated_at,
        )


class EmployeeNoResponse(BaseModel):
    """员工编号响应。"""

    employee_no: str


class EmployeeListResponse(BaseModel):
    """员工分页列表响应。"""

    items: list[EmployeeResponse]
    total: int
    page: int
    page_size: int

    @classmethod
    def from_page(cls, page: EmployeePage) -> "EmployeeListResponse":
        return cls(
            items=[EmployeeResponse.from_orm_model(employee) for employee in page.items],
            total=page.total,
            page=page.page,
            page_size=page.page_size,
        )
