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


class CoilStatus(str, enum.Enum):
    WAITING = "waiting"       # 等待入线
    ON_LINE = "on_line"       # 在线处理
    FINISHED = "finished"     # 处理完成
    ABNORMAL = "abnormal"     # 异常


class Coil(Base):
    """钢卷主档"""
    __tablename__ = "coils"

    id = Column(Integer, primary_key=True, index=True)
    coil_no = Column(String(30), unique=True, nullable=False, index=True, comment="卷号")
    order_no = Column(String(30), index=True, comment="订单号")
    steel_grade = Column(String(30), comment="钢种")
    spec_thickness = Column(Float, comment="规格厚度mm")
    spec_width = Column(Float, comment="规格宽度mm")
    target_thickness = Column(Float, comment="目标厚度mm")
    target_width = Column(Float, comment="目标宽度mm")
    gross_weight = Column(Float, comment="毛重kg")
    net_weight = Column(Float, comment="净重kg")
    inner_diameter = Column(Float, comment="内径mm")
    status = Column(Enum(CoilStatus), default=CoilStatus.WAITING)
    plan_id = Column(Integer, ForeignKey("production_plans.id"), nullable=True)
    remark = Column(Text)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())

    tracking = relationship("MaterialTracking", back_populates="coil")


class MaterialTracking(Base):
    """物料跟踪记录"""
    __tablename__ = "material_tracking"

    id = Column(Integer, primary_key=True, index=True)
    coil_id = Column(Integer, ForeignKey("coils.id"), nullable=False, index=True)
    coil_no = Column(String(30), nullable=False, index=True)
    position = Column(String(50), comment="当前位置/工位")
    event_type = Column(String(30), comment="事件类型: entry/exit/process/inspect")
    event_desc = Column(String(200), comment="事件描述")
    actual_thickness = Column(Float, comment="实测厚度")
    actual_width = Column(Float, comment="实测宽度")
    speed = Column(Float, comment="线速度m/min")
    tension = Column(Float, comment="张力N")
    operator = Column(String(50))
    event_time = Column(DateTime, nullable=False, index=True)
    created_at = Column(DateTime, server_default=func.now())

    coil = relationship("Coil", back_populates="tracking")
