from sqlalchemy import Column, Integer, String, Float, DateTime, Enum, Text, ForeignKey, func
from app.database import Base
import enum


class EquipmentStatus(str, enum.Enum):
    NORMAL = "normal"       # 正常
    FAULT = "fault"         # 故障
    MAINTENANCE = "maintenance"  # 检修
    STANDBY = "standby"     # 备用


class Equipment(Base):
    """设备台账"""
    __tablename__ = "equipments"

    id = Column(Integer, primary_key=True, index=True)
    code = Column(String(30), unique=True, nullable=False, index=True, comment="设备编号")
    name = Column(String(100), nullable=False, comment="设备名称")
    category = Column(String(30), comment="设备类别")
    model = Column(String(50), comment="型号规格")
    manufacturer = Column(String(100), comment="制造厂商")
    install_date = Column(DateTime, comment="投用日期")
    location = Column(String(50), comment="安装位置")
    status = Column(Enum(EquipmentStatus), default=EquipmentStatus.NORMAL)
    rated_power = Column(Float, comment="额定功率kW")
    remark = Column(Text)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())


class EquipmentMaintenance(Base):
    """设备维保记录"""
    __tablename__ = "equipment_maintenance"

    id = Column(Integer, primary_key=True, index=True)
    equipment_id = Column(Integer, ForeignKey("equipments.id"), nullable=False)
    equipment_code = Column(String(30), index=True)
    maintenance_type = Column(String(20), comment="类型: repair/planned/inspection")
    title = Column(String(200), nullable=False)
    description = Column(Text, comment="维保内容")
    start_time = Column(DateTime, nullable=False)
    end_time = Column(DateTime)
    duration = Column(Float, comment="工时h")
    cost = Column(Float, comment="费用元")
    spare_parts = Column(Text, comment="更换备件（JSON格式）")
    technician = Column(String(50), comment="执行人")
    approver = Column(String(50), comment="审核人")
    next_maintenance = Column(DateTime, comment="下次维保时间")
    result = Column(String(20), comment="结果: pass/fail/pending")
    remark = Column(Text)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
