#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
库区数据模型
支持密集库区和一般库区的管理
"""

from sqlalchemy import Column, String, Integer, Boolean, Text, DateTime, Enum
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.mysql import CHAR
from .base import BaseModel
import enum


class StorageAreaType(enum.Enum):
    """库区类型枚举"""
    GENERAL = "general"     # 一般库区
    DENSE = "dense"         # 密集库区


class StorageArea(BaseModel):
    """
    库区数据模型
    一个库区可以包含多个动作点
    """
    __tablename__ = 'vwed_storage_area'
    
    id = Column(CHAR(64), primary_key=True, comment='库区ID')
    area_name = Column(String(64), nullable=False, unique=True, comment='库区名称')
    area_type = Column(Enum(StorageAreaType), nullable=False, default=StorageAreaType.GENERAL, comment='库区类型')
    scene_id = Column(String(32), nullable=False, comment='场景ID')
    # 选择库位逻辑 （1 先进先出 2 先进后出 ）
    select_logic = Column(Integer, nullable=False, default=1, comment='选择库位逻辑 1 先进先出 2 先进后出 ')
    # 库区属性
    max_capacity = Column(Integer, nullable=False, default=0, comment='最大容量')
    current_usage = Column(Integer, nullable=False, default=0, comment='当前使用量')
    is_active = Column(Boolean, nullable=False, default=True, comment='是否激活')
    is_maintenance = Column(Boolean, nullable=False, default=False, comment='是否维护中')
    
    # 库区描述和配置
    description = Column(Text, comment='库区描述')
    tags = Column(String(255), comment='库区标签')
    
    # 关联关系
    operate_points = relationship(
        "OperatePoint", 
        back_populates="storage_area", 
        cascade="all, delete-orphan"
    )
    
    def __repr__(self):
        return f"<StorageArea(id={self.id}, area_name={self.area_name}, area_type={self.area_type})>"
    
    def get_available_capacity(self):
        """获取可用容量"""
        return self.max_capacity - self.current_usage
    
    def get_usage_rate(self):
        """获取使用率"""
        if self.max_capacity == 0:
            return 0.0
        return (self.current_usage / self.max_capacity) * 100.0
    
    def is_dense_area(self):
        """是否为密集库区"""
        return self.area_type == StorageAreaType.DENSE
    
    def is_general_area(self):
        """是否为一般库区"""
        return self.area_type == StorageAreaType.GENERAL 