"""
资产相关数据模型
"""
from datetime import datetime, date
from sqlalchemy import Column, BigInteger, String, Integer, Text, ForeignKey, DateTime, Date, Numeric, Index
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import relationship
from app.db.base import Base


class Asset(Base):
    """资产表"""

    __tablename__ = "assets"

    id = Column(BigInteger, primary_key=True, index=True)
    asset_code = Column(String(50), unique=True, nullable=False, index=True, comment="资产编码")
    asset_name = Column(String(200), nullable=False, comment="资产名称")
    device_type_id = Column(BigInteger, ForeignKey("device_types.id"), nullable=False, comment="设备类型ID")
    brand_id = Column(BigInteger, ForeignKey("brands.id"), nullable=True, comment="品牌ID")
    model = Column(String(200), nullable=True, comment="规格型号")
    serial_number = Column(String(200), nullable=True, index=True, comment="序列号(SN)")
    supplier_id = Column(BigInteger, ForeignKey("suppliers.id"), nullable=True, comment="供应商ID")
    purchase_date = Column(Date, nullable=True, index=True, comment="采购日期")
    purchase_price = Column(Numeric(18, 2), nullable=True, comment="采购价格")
    warranty_period = Column(Integer, nullable=True, comment="保修期(月)")
    warranty_expire_date = Column(Date, nullable=True, comment="保修到期日期")
    organization_id = Column(BigInteger, ForeignKey("organizations.id"), nullable=False, comment="所属网点ID")
    location = Column(String(500), nullable=True, comment="存放位置")
    status = Column(String(20), default="pending", nullable=False, index=True, comment="状态")
    dynamic_attributes = Column(JSONB, default={}, comment="动态字段值")
    qr_code_url = Column(String(500), nullable=True, comment="二维码图片URL")
    remark = Column(Text, nullable=True, 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)

    # 关系
    device_type = relationship("DeviceType", back_populates="assets")
    brand = relationship("Brand", back_populates="assets")
    supplier = relationship("Supplier", back_populates="assets")
    organization = relationship("Organization")
    created_user = relationship("User", foreign_keys=[created_by])
    updated_user = relationship("User", foreign_keys=[updated_by])
    deleted_user = relationship("User", foreign_keys=[deleted_by])
    status_history = relationship("AssetStatusHistory", back_populates="asset", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<Asset(id={self.id}, asset_code={self.asset_code}, asset_name={self.asset_name})>"


class AssetStatusHistory(Base):
    """资产状态历史表"""

    __tablename__ = "asset_status_history"

    id = Column(BigInteger, primary_key=True, index=True)
    asset_id = Column(BigInteger, ForeignKey("assets.id", ondelete="CASCADE"), nullable=False, comment="资产ID")
    old_status = Column(String(20), nullable=True, comment="原状态")
    new_status = Column(String(20), nullable=False, index=True, comment="新状态")
    operation_type = Column(String(50), nullable=False, comment="操作类型")
    operator_id = Column(BigInteger, ForeignKey("users.id"), nullable=False, comment="操作人ID")
    operator_name = Column(String(100), nullable=True, comment="操作人姓名(冗余)")
    organization_id = Column(BigInteger, ForeignKey("organizations.id"), nullable=True, comment="相关网点ID")
    remark = Column(Text, nullable=True, comment="备注")
    extra_data = Column(JSONB, nullable=True, comment="额外数据")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)

    # 关系
    asset = relationship("Asset", back_populates="status_history")
    operator = relationship("User", foreign_keys=[operator_id])
    organization = relationship("Organization")

    # 索引
    __table_args__ = (
        Index("idx_asset_status_history_asset", "asset_id"),
        Index("idx_asset_status_history_time", "created_at"),
    )

    def __repr__(self):
        return f"<AssetStatusHistory(id={self.id}, asset_id={self.asset_id}, old_status={self.old_status}, new_status={self.new_status})>"
