import logging

from rest_framework import status, views
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from api_v1 import serializers
from stock import services as stock_services

from .mixins import StockChangeViewMixin

logger = logging.getLogger(__name__)


class StockTransferView(StockChangeViewMixin, views.APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        if not self.check_employee_permission(request):
            return self.permission_error_response('无权限访问')

        serializer = serializers.StockTransferSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data

        merchant = request.user.employee.merchant
        operator = request.user.employee

        try:
            transfer_order = stock_services.create_transfer_order(
                merchant=merchant,
                created_by=request.user,
                operator=operator,
                from_warehouse_id=data['from_warehouse'],
                to_warehouse_id=data['to_warehouse'],
                items=data['products'],
                transfer_date=data.get('transfer_date'),
                remarks=data.get('remarks'),
                request_id=data.get('request_id') or None,
            )
        except ValueError as exc:
            return Response({'error': str(exc)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as exc:
            logger.error('创建调拨单失败: %s', exc, exc_info=True)
            return Response({'error': '创建调拨单失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        response_serializer = serializers.StockTransferResponseSerializer(transfer_order)
        return Response(response_serializer.data, status=status.HTTP_201_CREATED)
