"""
商户设置相关视图
"""

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

from drf_spectacular.utils import extend_schema
from api_v1 import serializers

from .mixins import StockChangeViewMixin

logger = logging.getLogger(__name__)


class SetMerchantAutoCompleteView(StockChangeViewMixin, views.APIView):
    """设置商户自动完成库存变动"""
    
    permission_classes = [IsAuthenticated]
    
    @extend_schema(
        tags=['修改商户自动确认出入库设定'],
        request=serializers.SetMerchantAutoCompleteStockChangeSerializer,
        responses={200: dict},
        summary="设置商户自动确认库存变动",
        description="开启或关闭商户的库存变动自动完成功能"
    )
    def post(self, request):
        """
        设置商户自动确认库存变动设定
        
        POST /api/v1/merchant/set-auto-complete-stock-change/
        
        请求参数:
        {
            "auto_complete": true  // 是否自动确认库存变动
        }
        """
        
        # 检查员工权限
        if not self.check_employee_permission(request):
            return self.permission_error_response('无权限操作')
        
        try:
            emp = request.user.employee
            merchant = emp.merchant
            
            serializer = serializers.SetMerchantAutoCompleteStockChangeSerializer(data=request.data)
            if serializer.is_valid():
                auto_complete = serializer.validated_data['auto_complete']
                merchant.auto_complete_stock_change = auto_complete
                merchant.save()
                
                logger.info(f"用户 {request.user.username} 设置商户 {merchant.name} 自动确认库存变动为 {auto_complete}")
                return Response({'status': 'success'}, status=status.HTTP_200_OK)
            
            return self.error_response('参数验证失败', serializer.errors)
            
        except AttributeError:
            logger.error(f"用户 {request.user.username} 无权限设置商户自动确认库存变动", 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)
