from app.extensions import db
import json

class StockBuy(db.Model):
    """
    采购入库库存表
    对应数据库表: stock_buy
    """
    __tablename__ = 'stock_buy'

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

    # 身份标识
    sku = db.Column(db.String(100))
    in_date = db.Column(db.DateTime)
    barcode = db.Column(db.String(100))
    serial_number = db.Column(db.String(100))
    batch_number = db.Column(db.String(100))

    # 状态
    status = db.Column(db.String(50), default='在库')
    inspection_status = db.Column(db.String(50))
    warehouse_location = db.Column(db.String(100))

    # 数量
    in_quantity = db.Column(db.Numeric(19, 4), default=0)
    stock_quantity = db.Column(db.Numeric(19, 4), default=0)
    available_quantity = db.Column(db.Numeric(19, 4), default=0)

    # 财务与商务
    unit_price = db.Column(db.Numeric(19, 4), default=0)
    total_price = db.Column(db.Numeric(19, 4), default=0)
    currency = db.Column(db.String(20), default='CNY')
    exchange_rate = db.Column(db.Numeric(15, 6), default=1.0)

    supplier_name = db.Column(db.String(255))
    buyer_name = db.Column(db.String(100))  # 对应 SQL: buyer_name
    buyer_email = db.Column(db.String(100))  # 对应 SQL: buyer_email
    original_link = db.Column(db.Text)  # 对应 SQL: original_link
    detail_link = db.Column(db.Text)

    # 图片字段 (存储 JSON 字符串)
    arrival_photo = db.Column(db.Text)
    # [新增] 检测报告图片路径 (存储 JSON 字符串)
    inspection_report = db.Column(db.Text)

    # [新增] 全局打印流水号 (用于跨表连续编号，对应 Sequence: global_print_seq)
    global_print_id = db.Column(db.Integer)

    # 关系定义
    # 注意：这里使用字符串 'MaterialBase' 引用，避免了直接 import 导致的潜在循环依赖
    material = db.relationship('MaterialBase', back_populates='stock_buys')

    def to_dict(self):
        # 辅助解析函数：将数据库存储的 JSON 字符串转为 List
        def parse_img_list(json_str):
            if not json_str:
                return []
            try:
                # 兼容旧数据：如果不是 JSON 格式（比如是单个 URL），则包装成 list
                if not json_str.startswith('['):
                    return [json_str]
                return json.loads(json_str)
            except:
                return []

        return {
            'id': self.id,
            'base_id': self.base_id,
            'material_name': self.material.name if self.material else '',
            'spec_model': self.material.spec_model if self.material else '',
            'category': self.material.category if self.material else '',
            'unit': self.material.unit if self.material else '',
            'material_type': self.material.material_type if self.material else '',

            'sku': self.sku,
            'inbound_date': self.in_date.strftime('%Y-%m-%d') if self.in_date else '',
            'barcode': self.barcode,
            'serial_number': self.serial_number,
            'batch_number': self.batch_number,
            'warehouse_loc': self.warehouse_location,
            'status': self.status,
            'inspection_status': self.inspection_status,

            'in_quantity': float(self.in_quantity or 0),
            'qty_inbound': float(self.in_quantity or 0),
            'stock_quantity': float(self.stock_quantity or 0),
            'qty_stock': float(self.stock_quantity or 0),
            'available_quantity': float(self.available_quantity or 0),
            'qty_available': float(self.available_quantity or 0),

            'unit_price': float(self.unit_price or 0),
            'total_price': float(self.total_price or 0),
            'currency': self.currency,
            'exchange_rate': float(self.exchange_rate or 1.0),

            'supplier_name': self.supplier_name,
            'purchaser': self.buyer_name,
            'purchaser_email': self.buyer_email,
            'source_link': self.original_link,
            'detail_link': self.detail_link,

            # [修改] 解析为数组返回给前端
            'arrival_photo': parse_img_list(self.arrival_photo),
            'inspection_report': parse_img_list(self.inspection_report),

            # [新增] 返回全局打印ID及其格式化字符串
            'global_print_id': self.global_print_id,
            'global_print_id_str': f"{self.global_print_id:010d}" if self.global_print_id else ""
        }