# inventory-backend/app/models/inbound/service.py
from app.extensions import db, beijing_time
from datetime import datetime


class StockService(db.Model):
    """
    服务权益库存表
    对应数据库表: stock_service
    说明：服务权益通常为虚拟资产，不进行具体的库存数量(actual_quantity)管理
    """
    __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 = db.Column(db.String(100), unique=True, nullable=False)

    # 扩展字段 (对应您的数据库建表脚本)
    service_category = db.Column(db.String(100), comment='服务类别')
    provider_name = db.Column(db.String(255), nullable=False, default='')
    contract_id = db.Column(db.String(100), comment='合同号')
    contact_person = db.Column(db.String(100), comment='联系人')

    # 价格相关
    cost_price = db.Column(db.Numeric(19, 4), default=0)
    sale_price = db.Column(db.Numeric(19, 4), nullable=False, default=0)

    # 描述与状态
    description = db.Column(db.Text, default='')
    valid_period = db.Column(db.String(100), comment='有效期')
    status = db.Column(db.String(20), default='active')

    # 时间与系统字段
    created_at = db.Column(db.DateTime, default=beijing_time, nullable=False)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time)
    is_deleted = db.Column(db.Boolean, default=False)

    # ==========================================================================
    # 关联关系设置
    # MaterialBase 中定义了 back_populates='stock_services'
    # 因此这里必须定义 base 属性指向 'stock_services'
    # ==========================================================================
    base = db.relationship('MaterialBase', back_populates='stock_services')

    def to_dict(self):
        """序列化为字典"""
        return {
            'id': self.id,
            'base_id': self.base_id,
            'sku': self.sku,
            'service_category': self.service_category,
            'provider_name': self.provider_name,
            'contract_id': self.contract_id,
            'contact_person': self.contact_person,
            'sale_price': float(self.sale_price) if self.sale_price is not None else 0,
            'cost_price': float(self.cost_price) if self.cost_price is not None else 0,
            'description': self.description,
            'valid_period': self.valid_period,
            'status': self.status,
            '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,

            # 关联的基础信息 (Flattened)
            'material_name': self.base.name if self.base else None,
            'spec_model': self.base.spec_model if self.base else None,
            'unit': self.base.unit if self.base else None,
            'category': self.base.category if self.base else None,
            'material_type': self.base.material_type if self.base else None,
        }