from django.db import transaction

import sys
import os

# 将当前脚本所在目录(bin)添加到 Python 路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
from .services import AllocationService
from .exceptions import AllocationError
from .models import *

class LocationAllocation:
    """
    库位分配
     functions:
        process(container_code, start_point): 处理托盘分配
            params: container_code: 托盘编号
            params: start_point: 起始库位
            return: dict
        release(location_code): 释放库位
            params: location_code: 库位编号
            return: bool
    """
    def __init__(self):
        self.service = AllocationService

    def process(self, container_code, start_point='203'):
        try:
            with transaction.atomic():
                return self.service.allocate(container_code, start_point)
        except Exception as e:
            raise AllocationError(f"分配失败: {str(e)}")

    def release(self, location_code):
        try:
            location = LocationModel.objects.get(location_code=location_code)
            link = LocationContainerLink.objects.get(
                location=location, 
                is_active=True
            )
            link.is_active = False
            link.save()
            return True
        except Exception as e:
            raise AllocationError(f"释放失败: {str(e)}")