"""
数据库模型基类
"""
import sys
import os

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../..'))

from sqlalchemy import Column, String, DateTime, Boolean, func
from sqlalchemy.dialects.mysql import CHAR
from app.base import Base
from datetime import datetime
import uuid


class BaseModel(Base):
    """数据库模型基类"""
    __abstract__ = True
    
    id = Column(CHAR(36), primary_key=True, default=lambda: str(uuid.uuid4()), comment="主键ID")
    created_by = Column(CHAR(36), nullable=True, comment="创建人")
    created_time = Column(DateTime, default=func.now(), comment="创建时间，默认当前时间")
    updated_by = Column(CHAR(36), nullable=True, comment="修改人")
    updated_time = Column(DateTime, default=func.now(), onupdate=func.now(), comment="修改时间，默认当前时间")
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
        }
    
    def update_from_dict(self, data: dict):
        """从字典更新属性"""
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)