from sqlmodel import SQLModel, Field
from typing import Optional
from datetime import datetime

from common.biz_exception import BizException


class TimestampMixin(SQLModel):
    create_time: Optional[datetime] = Field(default_factory=datetime.now)
    update_time: Optional[datetime] = Field(default_factory=datetime.now)

    class Config:
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S')
        }


# 自定义函数将字符串转换为 datetime
def parse_datetime(date_str: str):
    try:
        if date_str:
            # 尝试解析前端传来的字符串格式时间
            return datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
        else:
            return None
    except ValueError:
        raise BizException(message=f"Incorrect datetime format, should be YYYY-MM-DD HH:MM:SS")
