from app.extensions import db
from datetime import datetime


class TransOutbound(db.Model):
    __tablename__ = 'trans_outbound'

    id = db.Column(db.Integer, primary_key=True)
    # 修改：不再唯一，因为批量出库时多个商品共用一个单号
    outbound_no = db.Column(db.String(100), nullable=False)

    # 关联源库存信息
    sku = db.Column(db.String(100))
    source_table = db.Column(db.String(50))  # 'stock_buy', 'stock_product', 'stock_semi'
    stock_id = db.Column(db.Integer)  # 对应源表的主键ID
    barcode = db.Column(db.String(100))  # 实际扫码内容

    # 业务信息
    outbound_type = db.Column(db.String(50), default='SALES')  # SALES(销售), USE(领用), TRANSFER(调拨)
    quantity = db.Column(db.Numeric(19, 4), nullable=False)

    # [新增] 出库时的单价，用于计算金额
    unit_price = db.Column(db.Numeric(19, 2), default=0)

    # 签字与追溯
    consumer_name = db.Column(db.String(100))  # 领用人/客户
    signature_path = db.Column(db.Text)  # 电子签名图片路径
    outbound_time = db.Column(db.DateTime, default=datetime.now)
    operator_name = db.Column(db.String(100))  # 操作员

    remark = db.Column(db.Text)

    def to_dict(self):
        return {
            'id': self.id,
            'outbound_no': self.outbound_no,
            'sku': self.sku,
            'source_table': self.source_table,
            'outbound_type': self.outbound_type,
            'quantity': float(self.quantity) if self.quantity else 0,
            'unit_price': float(self.unit_price) if self.unit_price else 0,
            'consumer_name': self.consumer_name,
            'signature_path': self.signature_path,
            'outbound_time': self.outbound_time.strftime('%Y-%m-%d %H:%M:%S') if self.outbound_time else None,
            'operator_name': self.operator_name,
            'remark': self.remark
        }