from app.extensions import db, beijing_time  # .material -> .base refactor checked
from datetime import datetime


class StocktakeDraft(db.Model):
    """
    盘点草稿表
    临时工作台，盘点时使用，会话结束后清空
    """
    __tablename__ = 'stocktake_draft'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.String(100), default='admin')
    # 关联的库存UUID (sku/barcode)
    uuid = db.Column(db.String(100))
    # 实际盘点数量
    quantity = db.Column(db.Numeric(19, 4), default=1)
    scan_time = db.Column(db.DateTime, default=beijing_time)
    # 盘点会话标识 (用于区分不同批次的盘点)
    session_id = db.Column(db.String(100))
    # 关联的库存类型 (stock_buy/stock_semi/stock_product)
    source_table = db.Column(db.String(50))
    # 关联的库存ID
    stock_id = db.Column(db.Integer)
    # 账面库存数量 (记录盘点时的账面数量)
    stock_qty = db.Column(db.Numeric(19, 4), default=0)
    # 差异数量 (实盘 - 账面, 正=盘盈, 负=盘亏)
    diff_qty = db.Column(db.Numeric(19, 4), default=0)

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'uuid': self.uuid,
            'quantity': float(self.quantity or 1),
            'scan_time': self.scan_time.strftime('%Y-%m-%d %H:%M:%S') if self.scan_time else None,
            'session_id': self.session_id,
            'source_table': self.source_table,
            'stock_id': self.stock_id,
            'stock_qty': float(self.stock_qty or 0),
            'diff_qty': float(self.diff_qty or 0)
        }
