"""
库存登记相关数据模型
"""
from datetime import datetime, date, timezone, timedelta
from sqlalchemy import Column, Integer, String, DateTime, Date, ForeignKey, Text, Boolean
from sqlalchemy.orm import relationship

from app.core.database import Base

# 北京时间（东八区 UTC+8）
BEIJING_TZ = timezone(timedelta(hours=8))


def beijing_now():
    """获取当前北京时间"""
    return datetime.now(BEIJING_TZ).replace(tzinfo=None)


class InventoryBatch(Base):
    """库存登记批次表 - 按天自动分批次"""
    __tablename__ = 'inventory_batches'

    id = Column(Integer, primary_key=True, autoincrement=True)
    batch_id = Column(String(36), unique=True, nullable=False, index=True)  # UUID
    batch_date = Column(Date, nullable=False, index=True)  # 批次日期
    status = Column(String(20), default='pending')  # pending/confirmed
    total_items = Column(Integer, default=0)  # 商品种类数
    total_quantity = Column(Integer, default=0)  # 总数量
    confirmed_at = Column(DateTime, nullable=True)  # 确认时间
    confirmed_by = Column(String(50), nullable=True)  # 确认人
    created_at = Column(DateTime, default=beijing_now)
    is_listed = Column(Boolean, default=False)  # 是否已上架
    listed_at = Column(DateTime, nullable=True)  # 上架时间

    # 关联登记记录
    registrations = relationship("InventoryRegistration", back_populates="batch")

    def to_dict(self):
        return {
            'id': self.id,
            'batch_id': self.batch_id,
            'batch_date': self.batch_date.isoformat() if self.batch_date else None,
            'status': self.status,
            'total_items': self.total_items,
            'total_quantity': self.total_quantity,
            'confirmed_at': self.confirmed_at.isoformat() if self.confirmed_at else None,
            'confirmed_by': self.confirmed_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'is_listed': self.is_listed,
            'listed_at': self.listed_at.isoformat() if self.listed_at else None
        }


class InventoryRegistration(Base):
    """库存登记记录表"""
    __tablename__ = 'inventory_registrations'

    id = Column(Integer, primary_key=True, autoincrement=True)
    batch_id = Column(String(36), ForeignKey('inventory_batches.batch_id'), nullable=False, index=True)

    # 扫码信息
    scanned_code = Column(String(100), nullable=True)  # 扫码值

    # 商品信息
    brand = Column(String(100), nullable=True)  # 品牌
    product_code = Column(String(100), nullable=True)  # 货号
    color = Column(String(100), nullable=True)  # 颜色
    size = Column(String(50), nullable=True)  # 尺码
    product_name = Column(String(500), nullable=True)  # 商品名称

    # 数量
    quantity = Column(Integer, default=1)  # 入库数量

    # 来源
    source_type = Column(String(20), default='scan')  # scan/search
    source_order_id = Column(Integer, nullable=True)  # 来源订单ID

    # 时间和操作员
    created_at = Column(DateTime, default=beijing_now)
    operator = Column(String(50), nullable=True)

    # 备注
    remark = Column(Text, nullable=True)

    # 关联批次
    batch = relationship("InventoryBatch", back_populates="registrations")

    def to_dict(self):
        return {
            'id': self.id,
            'batch_id': self.batch_id,
            'scanned_code': self.scanned_code,
            'brand': self.brand,
            'product_code': self.product_code,
            'color': self.color,
            'size': self.size,
            'product_name': self.product_name,
            'quantity': self.quantity,
            'source_type': self.source_type,
            'source_order_id': self.source_order_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'operator': self.operator,
            'remark': self.remark
        }
