"""
库存变动记录详情查询视图
"""

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

from stock import models as stock_models
from drf_spectacular.utils import extend_schema

from .mixins import StockChangeViewMixin

logger = logging.getLogger(__name__)


class GetStockChangeView(StockChangeViewMixin, views.APIView):
    """获取单个库存变动记录"""
    
    permission_classes = [IsAuthenticated]
    
    @extend_schema(
        tags=['读取出入库'],
        responses={200: dict},
        summary="获取单个库存变动记录",
        description="根据ID获取库存变动记录详情，包含明细"
    )
    def get(self, request, record_id):
        """
        获取库存变动记录详情（包含所有明细）
        
        GET /api/v1/stock-change/<record_id>/
        
        返回:
        {
            "stock_change_record": {
                "id": 1,
                "type": 1,
                "warehouse": 1,
                "warehouse_name": "主仓库",
                "source_type": 1,
                "source_id": 1,
                "is_finished": true,
                "finished_at": "2024-01-01T12:00:00Z",
                "created_at": "2024-01-01T12:00:00Z",
                "created_by": "admin"
            },
            "details": [
                {
                    "id": 1,
                    "product": 1,
                    "product_name": "产品名称",
                    "quantity": 85.00,
                    "unit": 1,
                    "unit_display": "米"
                }
            ],
            "total_details": 3
        }
        """
        
        # 检查员工权限
        if not self.check_employee_permission(request):
            return self.permission_error_response('无权限访问')
        
        merchant_id = self.get_merchant_id(request)
        
        try:
            # 获取库存变动记录
            try:
                stock_change_record = stock_models.StockChangeRecord.objects.select_related(
                    'warehouse', 'created_by'
                ).get(id=record_id)
            except stock_models.StockChangeRecord.DoesNotExist:
                return self.not_found_response(f'库存变动记录ID {record_id} 不存在')
            
            # 验证权限：检查记录是否属于当前用户的商户
            if stock_change_record.merchant_id != merchant_id:
                return self.permission_error_response('无权访问该库存变动记录')
            
            # 验证仓库是否对当前用户可见
            if not self.validate_warehouse_visibility(stock_change_record.warehouse_id, request):
                return self.permission_error_response('该库存变动记录的仓库对当前用户不可见')
            
            # 获取所有明细记录
            details = stock_models.StockChangeDetail.objects.filter(
                stock_change_record=stock_change_record
            ).select_related('product').order_by('id')
            
            # 过滤掉用户不可见的产品明细
            visible_details = self.filter_visible_details(details, request)
            
            # 构建响应数据
            response_data = {
                'stock_change_record': self.build_record_data(stock_change_record),
                'details': [self.build_detail_data(detail) for detail in visible_details],
                'total_details': len(visible_details)
            }
            
            logger.info(f"用户 {request.user.username} 读取库存变动记录 ID: {record_id}")
            return Response(response_data, status=status.HTTP_200_OK)
            
        except AttributeError as e:
            logger.error(f"用户 {request.user.username} 无员工信息: {str(e)}", exc_info=True)
            return self.permission_error_response('用户无员工信息，无权访问')
        
        except Exception as e:
            logger.error(f"读取库存变动记录失败: {str(e)}", exc_info=True)
            return Response({
                'error': '读取库存变动记录失败',
                'message': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
