from app import db
from datetime import datetime


class StockService(db.Model):
    """
    服务权益库存表
    对应数据库表: stock_service
    """
    __tablename__ = 'stock_service'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 关联基础物料信息
    base_id = db.Column(db.Integer, db.ForeignKey('material_base.id'), nullable=False)
    # 系统生成的SKU，格式 SRV-YYYYMMDD-XXXX
    sku = db.Column(db.String(64), unique=True, nullable=False)
    # 售价
    sale_price = db.Column(db.Numeric(10, 2), nullable=False)
    # 服务商名称
    provider_name = db.Column(db.String(255), nullable=False, default='')
    # 服务详情/简介
    description = db.Column(db.Text, default='')
    # 创建时间与更新时间
    created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    # 软删除标志
    is_deleted = db.Column(db.Boolean, default=False, nullable=False)

    # 关系（可选）
    material_base = db.relationship('MaterialBase', backref='service_stocks', lazy='joined')

    def to_dict(self):
        """转为字典，用于 API 响应"""
        return {
            'id': self.id,
            'base_id': self.base_id,
            'sku': self.sku,
            'sale_price': float(self.sale_price) if self.sale_price is not None else 0,
            'provider_name': self.provider_name,
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
            'material_name': self.material_base.name if self.material_base else None,
            'spec_model': self.material_base.spec_model if self.material_base else None,
            'unit': self.material_base.unit if self.material_base else None,
        }
