"""
设备类型相关数据模型
"""
from datetime import datetime
from sqlalchemy import Column, BigInteger, String, Integer, Text, ForeignKey, DateTime, Index
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import relationship
from app.db.base import Base


class DeviceType(Base):
    """设备类型表"""

    __tablename__ = "device_types"

    id = Column(BigInteger, primary_key=True, index=True)
    type_code = Column(String(50), unique=True, nullable=False, index=True, comment="设备类型代码")
    type_name = Column(String(200), nullable=False, comment="设备类型名称")
    category = Column(String(50), nullable=True, comment="设备分类: IT设备, 办公设备, 生产设备等")
    description = Column(Text, nullable=True, comment="描述")
    icon = Column(String(100), nullable=True, comment="图标名称")
    status = Column(String(20), default="active", nullable=False, comment="状态: active, inactive")
    sort_order = Column(Integer, default=0, nullable=False, comment="排序")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    created_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    updated_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    deleted_at = Column(DateTime, nullable=True)
    deleted_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)

    # 关系
    created_user = relationship("User", foreign_keys=[created_by])
    updated_user = relationship("User", foreign_keys=[updated_by])
    deleted_user = relationship("User", foreign_keys=[deleted_by])
    fields = relationship("DeviceTypeField", back_populates="device_type", cascade="all, delete-orphan")
    assets = relationship("Asset", back_populates="device_type")

    def __repr__(self):
        return f"<DeviceType(id={self.id}, type_code={self.type_code}, type_name={self.type_name})>"


class DeviceTypeField(Base):
    """设备类型字段定义表（动态字段）"""

    __tablename__ = "device_type_fields"

    id = Column(BigInteger, primary_key=True, index=True)
    device_type_id = Column(BigInteger, ForeignKey("device_types.id", ondelete="CASCADE"), nullable=False)
    field_code = Column(String(50), nullable=False, comment="字段代码")
    field_name = Column(String(100), nullable=False, comment="字段名称")
    field_type = Column(String(20), nullable=False, comment="字段类型: text, number, date, select, multiselect, boolean, textarea")
    is_required = Column(BigInteger, default=False, nullable=False, comment="是否必填")
    default_value = Column(Text, nullable=True, comment="默认值")
    options = Column(JSONB, nullable=True, comment="select类型的选项: [{'label': '选项1', 'value': '1'}]")
    validation_rules = Column(JSONB, nullable=True, comment="验证规则: {'min': 0, 'max': 100, 'pattern': '^A-Z'}")
    placeholder = Column(String(200), nullable=True, comment="占位符")
    help_text = Column(Text, nullable=True, comment="帮助文本")
    sort_order = Column(Integer, default=0, nullable=False, comment="排序")
    status = Column(String(20), default="active", nullable=False, comment="状态: active, inactive")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    created_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    updated_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)
    deleted_at = Column(DateTime, nullable=True)
    deleted_by = Column(BigInteger, ForeignKey("users.id"), nullable=True)

    # 关系
    device_type = relationship("DeviceType", back_populates="fields")
    created_user = relationship("User", foreign_keys=[created_by])
    updated_user = relationship("User", foreign_keys=[updated_by])
    deleted_user = relationship("User", foreign_keys=[deleted_by])

    # 索引
    __table_args__ = (
        Index("idx_device_type_fields_type", "device_type_id"),
        Index("idx_device_type_fields_code", "field_code"),
    )

    def __repr__(self):
        return f"<DeviceTypeField(id={self.id}, field_code={self.field_code}, field_name={self.field_name})>"
