from pydantic import Field, BaseModel,field_validator
from fastapi import HTTPException
from ..common.datetime import get_current_date
from typing import List, Optional, Literal
from ..common.validators import DateStr
from ..common.base import BaseResponseWithID
from ..common.enums import ApprovalStatus
from datetime import datetime

class ContractSettlementDetailResponse(BaseResponseWithID):
    """
    合同结算明细返回模型
    """
    project_id: str = Field(..., description="所属项目ID", examples=["project123"])
    parent_id: str = Field(..., description="所属合同结算ID", examples=["settlement789"])
    date: DateStr = Field(..., description="结算日期", examples=["2024-05-31"])
    quantity: float = Field(..., description="合同金额", examples=[0])
    remark: Optional[str] = Field(None, description="填报备注", examples=[""])
    is_complete: Optional[bool] = Field(None, description="是否完成", examples=[False])
    write_off_rate: Optional[float] = Field(None, description="核销率", examples=[0.0])
    change_count: int = Field(0, description="变更次数", examples=[0])
    status: Optional[int] = Field(None, description="进度状态", examples=[0])
    rate: Optional[float] = Field(None, description="实际完成率", examples=[0.0])

class ContractSettlementDetailCreate(BaseModel):
    """
    合同结算明细创建模型
    CONTRACT_SETTLEMENT_DETAIL = "contract_settlement.detail"
    """
    project_id: str = Field(..., description="所属项目ID", examples=["project123"])
    parent_id: str = Field(..., description="所属合同结算ID", examples=["settlement789"])
    date: DateStr = Field(..., description="结算日期", examples=["2024-05-31"])
    quantity: float = Field(..., description="合同金额", examples=[0])
    remark: Optional[str] = Field(None, description="填报备注", examples=[""])
    is_complete: bool = Field(False, description="是否完成", examples=[False])
    write_off_rate: Optional[float] = Field(None, description="核销率", examples=[0.0])
    confirmation_time: str | None = Field(None, description="确认时间", examples=["2025-12-17 11:13:49"])
    approval_time: str | None = Field(None, description="审批时间", examples=["2025-12-17 11:13:49"])
    approval_status: ApprovalStatus = Field("registered", description="审批状态", examples=["registered"])

    @field_validator("approval_status")
    def validate_approval_status(cls, v):
        """验证审批字段"""
        try:
            return ApprovalStatus(v)  # 尝试转换
        except ValueError:
            raise HTTPException(400, f"审批状态 '{v}' 无效")

    @field_validator("confirmation_time", "approval_time")
    def validate_time(cls, v):
        """验证时间"""
        if v is None:
            return v
        try:
            datetime.strptime(v, "%Y-%m-%d %H:%M:%S")
        except ValueError:
            raise HTTPException(detail=f'{v}时间格式错误，应为：2025-12-17 11:13:49', status_code=400)
        return v

    @field_validator("quantity")
    def validate_quantity(cls, v):
        """验证实际完成量累计必须为非负数"""
        if v <  0:
            raise HTTPException(status_code=400, detail='合同金额不能小于0')
        return v

    @field_validator("date")
    def validate_date(cls, v):
        if v > get_current_date():
            raise HTTPException(detail='结算日期不能大于今天', status_code=400)
        return v

class ContractSettlementDetailUpdate(BaseModel):
    """
    合同结算明细更新模型
    CONTRACT_SETTLEMENT_DETAIL = "contract_settlement.detail"
    """
    id: str = Field(..., description="合同明细ID")
    date: DateStr | None = Field(None, description="结算日期", examples=["2024-05-31"])
    quantity: float | None = Field(None, description="合同金额", examples=[0])
    remark: str | None = Field(None, description="填报备注", examples=[""])
    is_complete: bool | None = Field(None, description="是否完成", examples=[False])
    write_off_rate: float | None = Field(None, description="核销率", examples=[0.0])
    confirmation_time: str | None = Field(None, description="确认时间", examples=["2025-12-17 11:13:49"])
    approval_time: str | None = Field(None, description="审批时间", examples=["2025-12-17 11:13:49"])
    approval_status: ApprovalStatus | None = Field("registered", description="审批状态", examples=["registered"])

    @field_validator("approval_status")
    def validate_approval_status(cls, v):
        """验证审批字段"""
        if v is None:
            return v
        try:
            return ApprovalStatus(v)  # 尝试转换
        except ValueError:
            raise HTTPException(400, f"审批状态 '{v}' 无效")

    @field_validator("confirmation_time", "approval_time")
    def validate_time(cls, v):
        """验证时间"""
        if v is None:
            return v

        try:
            datetime.strptime(v, "%Y-%m-%d %H:%M:%S")
        except ValueError:
            raise HTTPException(detail=f'{v}时间格式错误，应为：2025-12-17 11:13:49', status_code=400)
        return v

    @field_validator("quantity")
    def validate_quantity(cls, v):
        """验证实际完成量累计必须为非负数"""
        if v is None:
            return None
        if v < 0:
            raise HTTPException(status_code=400, detail='合同金额不能小于0')
        return v

    @field_validator("date")
    def validate_date(cls, v):
        if v is None:
            return None
        if v > get_current_date():
            raise HTTPException(detail='结算日期不能大于今天', status_code=400)
        return v

class ContractSettlementDetailBulkUpdate(BaseModel):
    detail_list: List[ContractSettlementDetailUpdate]