# app/models/base.py
from app.extensions import db

class MaterialBase(db.Model):
    """
    基础信息表模型
    对应数据库表: material_base
    """
    __tablename__ = 'material_base'

    # 1. 基础字段
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False, comment='名称')
    common_name = db.Column(db.String(255), comment='俗名')  # ✅ 新增字段
    category = db.Column(db.String(100), comment='类别')
    material_type = db.Column(db.String(100), comment='类型')
    spec_model = db.Column(db.String(255), comment='规格型号')
    unit = db.Column(db.String(50), comment='计量单位')

    # 可见等级
    visibility_level = db.Column(db.Integer, default=0, comment='信息可见等级')

    # 链接与图片
    manual_link = db.Column(db.Text, comment='通用说明书')
    product_image = db.Column(db.Text, comment='通用产品图')

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

    # ============================================================
    # 关联关系区域
    # ============================================================

    # 1. 关联采购库存 (StockBuy)
    stock_buys = db.relationship('StockBuy', back_populates='material', lazy='dynamic')

    # 2. 关联半成品库存 (StockSemi)
    stock_semis = db.relationship('StockSemi', back_populates='material', lazy='dynamic')

    # 3. 关联成品库存 (StockProduct)
    stock_products = db.relationship('StockProduct', back_populates='material', lazy='dynamic')

    def to_dict(self):
        """
        序列化方法
        """
        return {
            'id': self.id,
            'name': self.name,
            'commonName': self.common_name,   # ✅ 序列化新增字段
            'category': self.category,
            'type': self.material_type,       # 前端字段映射
            'spec': self.spec_model,          # 前端字段映射
            'unit': self.unit,
            'visibilityLevel': self.visibility_level,
            'generalManual': self.manual_link,
            'generalImage': self.product_image,
            'isEnabled': 1 if self.is_enabled else 0,
        }