from app.extensions import db


class BomTable(db.Model):
    __tablename__ = 'bom_table'

    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('material_base.id'), nullable=False)
    child_id = db.Column(db.Integer, db.ForeignKey('material_base.id'), nullable=False)

    bom_no = db.Column(db.String(100), nullable=False, comment='BOM编号')
    version = db.Column(db.String(50), nullable=False, default='V1.0', comment='版本')

    dosage = db.Column(db.Numeric(19, 4), comment='个数')
    loss_rate = db.Column(db.Numeric(5, 2), comment='损耗率%', default=0, nullable=True)
    remark = db.Column(db.Text, comment='备注')

    # ★ 新增：启用状态
    is_enabled = db.Column(db.Boolean, default=True, comment='是否启用')

    # 约束: 保证同一版本下的父子对唯一，允许不同版本存在
    __table_args__ = (
        db.UniqueConstraint('bom_no', 'version', 'parent_id', 'child_id', name='uniq_bom_pair_in_version'),
    )

    # relationships
    parent = db.relationship('MaterialBase', foreign_keys=[parent_id], backref='bom_parents')
    child = db.relationship('MaterialBase', foreign_keys=[child_id], backref='bom_children')