# app/models/inbound/semi.py
from app.extensions import db
import json


class StockSemi(db.Model):
    """
    半成品入库库存表
    """
    __tablename__ = 'stock_semi'

    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))
    production_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))

    # 数量
    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)

    # 状态与位置
    status = db.Column(db.String(50))
    warehouse_location = db.Column(db.String(100))

    # 半成品特有字段
    bom_code = db.Column('bom_id', db.String(100))
    bom_version = db.Column(db.String(50))
    work_order_code = db.Column('work_order_id', db.String(100))

    raw_material_cost = db.Column(db.Numeric(19, 4), default=0)
    manual_cost = db.Column(db.Numeric(19, 4), default=0)
    total_price = db.Column(db.Numeric(19, 4), default=0)

    production_manager = db.Column('producer_name', db.String(100))
    production_start_time = db.Column(db.DateTime)
    production_end_time = db.Column(db.DateTime)
    production_time_range = db.Column(db.String(255))

    quality_status = db.Column(db.String(50))

    # [修改] 质量报告 (存储 JSON 字符串: 图片列表 + 链接)
    quality_report_link = db.Column(db.Text)

    # [新增] 到货图片 (存储 JSON 字符串)
    arrival_photo = db.Column(db.Text)

    detail_link = db.Column(db.Text)
    remark = db.Column(db.Text)

    # [新增] 全局打印流水号
    global_print_id = db.Column(db.Integer)

    # 关系定义
    material = db.relationship('MaterialBase', back_populates='stock_semis')

    def to_dict(self):
        raw_val = float(self.raw_material_cost or 0)
        man_val = float(self.manual_cost or 0)
        unit_total = raw_val + man_val

        # 辅助解析函数：将数据库存储的 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.production_date.strftime('%Y-%m-%d') if self.production_date else '',
            'barcode': self.barcode,
            'serial_number': self.serial_number,
            'batch_number': self.batch_number,
            'warehouse_loc': self.warehouse_location,
            'status': self.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),

            'bom_code': self.bom_code,
            'bom_version': self.bom_version,
            'work_order_code': self.work_order_code,
            'raw_material_cost': raw_val,
            'manual_cost': man_val,
            'unit_total_cost': unit_total,
            'total_price': float(self.total_price or 0),

            'production_manager': self.production_manager,
            'production_time_range': self.production_time_range,
            'production_start_time': str(self.production_start_time) if self.production_start_time else '',
            'production_end_time': str(self.production_end_time) if self.production_end_time else '',

            'quality_status': self.quality_status,

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

            'detail_link': self.detail_link,
            'remark': self.remark,

            'global_print_id': self.global_print_id,
            'global_print_id_str': f"{self.global_print_id:010d}" if self.global_print_id else ""
        }