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

from basic_info import models as basic_models
from business import services as business_services
from business import models as business_models
from api_v1.views.stock_change_views.mixins import StockChangeViewMixin


class SalesOrderItemSerializer(serializers.ModelSerializer):
    quantity_of_rolls = serializers.SerializerMethodField(read_only=True)
    product_name = serializers.CharField(source='product.name', read_only=True)
    def get_quantity_of_rolls(self, obj: business_models.SalesOrderItem):
        return obj.split_quantity_of_rolls()

    class Meta:
        model = business_models.SalesOrderItem
        fields = [
            'id', 'product', 'product_name', 'price', 'color', 'quantity', 'unit',
            'empty_diff_percent', 'quantity_of_rolls', 'num_of_rolls',
            'consume_detail_ids', 'batch_number', 'order_quantity', 'remarks', 'created_at', 'updated_at', 'spec',
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'total_amount', 'diff_quantity', 'real_quantity']


class SalesOrderSerializer(serializers.ModelSerializer):
    human_id = serializers.CharField(read_only=True)
    total_amount = serializers.SerializerMethodField(read_only=True)
    diff_quantity = serializers.SerializerMethodField(read_only=True)
    total_quantity = serializers.SerializerMethodField(read_only=True)
    quantity_of_rolls = serializers.SerializerMethodField(read_only=True)

    def get_total_amount(self, obj: business_models.SalesOrder):
        return obj.get_total_amount()

    def get_diff_quantity(self, obj: business_models.SalesOrder):
        return obj.get_total_diff_quantity()

    def get_total_quantity(self, obj: business_models.SalesOrder):
        return obj.get_total_quantity()

    def get_quantity_of_rolls(self, obj: business_models.SalesOrder):
        return [item.split_quantity_of_rolls() for item in obj.items.all()]

    customer_name = serializers.CharField(source='customer.name', read_only=True)
    operator_name = serializers.CharField(source='operator.name', read_only=True)
    warehouse_name = serializers.CharField(source='warehouse.name', read_only=True)
    items = SalesOrderItemSerializer(many=True, read_only=True)

    class Meta:
        model = business_models.SalesOrder
        fields = [
            'id', 'human_id', 'customer', 'customer_name', 'sales_date', 'kind',
            'total_amount', 'diff_quantity', 'total_quantity',
            'operator', 'operator_name', 'warehouse', 'warehouse_name',
            'status', 'is_red_flushed', 'red_flush_id', 'red_flushed_at',
            'balance_before_snapshot',
            'remarks', 'created_at', 'updated_at', 'items', 'quantity_of_rolls',
        ]
        read_only_fields = [
            'id', 'created_at', 'updated_at', 'items', 'customer_name',
            'operator_name', 'warehouse_name', 'is_red_flushed',
            'red_flush_id', 'red_flushed_at',
            'balance_before_snapshot',
        ]


class SalesOrderPagination(pagination.LimitOffsetPagination):
    default_limit = 20
    max_limit = 100


class SalesOrderView(StockChangeViewMixin, views.APIView):
    """销售订单查询与创建"""

    permission_classes = [IsAuthenticated]
    pagination_class = SalesOrderPagination

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

        merchant = request.user.employee.merchant
        queryset = business_models.SalesOrder.objects.filter(merchant=merchant).prefetch_related(
            'items', 'customer', 'operator', 'warehouse'
        )

        # Query 参数过滤
        qp = request.query_params
        customer_id = qp.get('customer')
        warehouse_id = qp.get('warehouse')
        status_value = qp.get('status')
        kind = qp.get('kind')

        if customer_id:
            try:
                queryset = queryset.filter(customer_id=int(customer_id))
            except (TypeError, ValueError):
                pass
        if warehouse_id:
            try:
                queryset = queryset.filter(warehouse_id=int(warehouse_id))
            except (TypeError, ValueError):
                pass
        if status_value:
            queryset = queryset.filter(status=status_value)
        if kind:
            queryset = queryset.filter(kind=kind)

        paginator = self.pagination_class()
        page = paginator.paginate_queryset(queryset.order_by('-created_at'), request, view=self)
        serializer = SalesOrderSerializer(page, many=True)
        return paginator.get_paginated_response(serializer.data)

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

        merchant = request.user.employee.merchant
        data = request.data or {}

        customer_id = data.get('customer')
        warehouse_id = data.get('warehouse_id') or data.get('warehouse')
        order_date = data.get('order_date')
        items = data.get('items', [])
        remarks = data.get('remarks', '')
        kind = data.get('kind')


        if not customer_id:
            return Response({'error': '缺少客户 ID'}, status=status.HTTP_400_BAD_REQUEST)
        if not warehouse_id:
            return Response({'error': '缺少仓库 ID'}, status=status.HTTP_400_BAD_REQUEST)
        if not order_date:
            return Response({'error': '缺少 order_date'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(items, list) or not items:
            return Response({'error': 'items 需要为非空数组'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            customer = basic_models.Customer.objects.get(id=customer_id, merchant=merchant)
        except basic_models.Customer.DoesNotExist:
            return Response({'error': f'客户 {customer_id} 不存在'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            warehouse = basic_models.WareHouse.objects.get(id=warehouse_id, merchant=merchant)
        except basic_models.WareHouse.DoesNotExist:
            return Response({'error': f'仓库 {warehouse_id} 不存在'}, status=status.HTTP_400_BAD_REQUEST)

        operator = request.user.employee

        try:
            sales_order = business_services.create_sales_order(
                merchant=merchant,
                customer=customer,
                order_date=order_date,
                warehouse=warehouse,
                operator=operator,
                items=items,
                remarks=remarks,
                created_by=request.user,
                kind=kind,
            )

        except ValueError as exc:
            return Response({'error': str(exc)}, status=status.HTTP_400_BAD_REQUEST)

        return Response(
            {
                'id': sales_order.id,
                'human_id': sales_order.human_id,
                'status': sales_order.status,
                'balance_before_snapshot': sales_order.balance_before_snapshot,
                'message': '销售单创建成功，等待审批',
            },
            status=status.HTTP_201_CREATED,
        )


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

    def _get_order(self, request, pk: int):
        if not self.check_employee_permission(request):
            return None, self.permission_error_response('无权限访问')
        merchant = request.user.employee.merchant
        try:
            order = business_models.SalesOrder.objects.select_related(
                'customer', 'operator', 'warehouse'
            ).prefetch_related('items').get(id=pk, merchant=merchant)
            return order, None
        except business_models.SalesOrder.DoesNotExist:
            return None, self.not_found_response('销售单不存在')

    def put(self, request, pk: int):
        return self._update(request, pk)

    def patch(self, request, pk: int):
        return self._update(request, pk)

    def get(self, request, pk: int):
        sales_order, error_response = self._get_order(request, pk)
        if error_response:
            return error_response
        return Response(SalesOrderSerializer(sales_order).data, status=status.HTTP_200_OK)

    def _update(self, request, pk: int):
        sales_order, error_response = self._get_order(request, pk)
        if error_response:
            return error_response

        merchant = request.user.employee.merchant
        data = request.data or {}

        customer = sales_order.customer
        customer_id = data.get('customer')
        if customer_id:
            try:
                customer = basic_models.Customer.objects.get(id=customer_id, merchant=merchant)
            except basic_models.Customer.DoesNotExist:
                return Response({'error': f'客户 {customer_id} 不存在'}, status=status.HTTP_400_BAD_REQUEST)

        warehouse = sales_order.warehouse
        warehouse_id = data.get('warehouse_id') or data.get('warehouse')
        if warehouse_id:
            try:
                warehouse = basic_models.WareHouse.objects.get(id=warehouse_id, merchant=merchant)
            except basic_models.WareHouse.DoesNotExist:
                return Response({'error': f'仓库 {warehouse_id} 不存在'}, status=status.HTTP_400_BAD_REQUEST)

        order_date = data.get('order_date') or sales_order.sales_date
        items = data.get('items')
        if not isinstance(items, list) or not items:
            return Response({'error': 'items 需要为非空数组'}, status=status.HTTP_400_BAD_REQUEST)
        remarks = data.get('remarks', sales_order.remarks)
        kind = data.get('kind')

        try:
            updated_order = business_services.update_sales_order(
                sales_order=sales_order,
                customer=customer,
                order_date=order_date,
                warehouse=warehouse,
                items=items,
                remarks=remarks,
                kind=kind,
            )

        except ValueError as exc:
            return Response({'error': str(exc)}, status=status.HTTP_400_BAD_REQUEST)

        serializer = SalesOrderSerializer(updated_order)
        return Response(serializer.data, status=status.HTTP_200_OK)


class SalesOrderReviewSerializer(serializers.Serializer):
    action = serializers.ChoiceField(choices=[('approve', '审批通过'), ('cancel', '作废')])


class SalesOrderReviewView(StockChangeViewMixin, views.APIView):
    """销售单审批 / 作废"""

    permission_classes = [IsAuthenticated]
    ACTION_STATUS_MAP = {
        'approve': business_models.SalesOrderStatusEnum.APPROVED,
        'cancel': business_models.SalesOrderStatusEnum.CANCELLED,
    }

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

        merchant = request.user.employee.merchant
        try:
            sales_order = business_models.SalesOrder.objects.select_related(
                'customer', 'operator', 'warehouse'
            ).prefetch_related('items').get(id=pk, merchant=merchant)
        except business_models.SalesOrder.DoesNotExist:
            return self.not_found_response('销售单不存在')

        serializer = SalesOrderReviewSerializer(data=request.data or {})
        serializer.is_valid(raise_exception=True)
        action = serializer.validated_data['action']
        target_status = self.ACTION_STATUS_MAP[action]

        try:
            business_services.review_sales_order(
                sales_order=sales_order,
                target_status=target_status,
                reviewed_by=request.user,
            )
        except ValueError as exc:
            return Response({'error': str(exc)}, status=status.HTTP_400_BAD_REQUEST)

        refreshed_order = business_models.SalesOrder.objects.select_related(
            'customer', 'operator', 'warehouse'
        ).prefetch_related('items').get(id=sales_order.id)
        return Response(SalesOrderSerializer(refreshed_order).data, status=status.HTTP_200_OK)


class SalesOrderRedFlushSerializer(serializers.Serializer):
    reason = serializers.CharField(required=True, allow_blank=False, trim_whitespace=True)


class SalesOrderRedFlushView(StockChangeViewMixin, views.APIView):
    """销售单红冲"""

    permission_classes = [IsAuthenticated]

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

        merchant = request.user.employee.merchant
        try:
            sales_order = business_models.SalesOrder.objects.select_related(
                'customer', 'operator', 'warehouse'
            ).prefetch_related('items').get(id=pk, merchant=merchant)
        except business_models.SalesOrder.DoesNotExist:
            return self.not_found_response('销售单不存在')

        serializer = SalesOrderRedFlushSerializer(data=request.data or {})
        serializer.is_valid(raise_exception=True)

        try:
            red_flushed_order = business_services.red_flush_sales_order(
                merchant=merchant,
                sales_order=sales_order,
                red_flushed_by=request.user,
                reason=serializer.validated_data['reason'],
            )
        except ValueError as exc:
            return Response({'error': str(exc)}, status=status.HTTP_400_BAD_REQUEST)

        refreshed_order = business_models.SalesOrder.objects.select_related(
            'customer', 'operator', 'warehouse'
        ).prefetch_related('items').get(id=red_flushed_order.id)
        return Response(SalesOrderSerializer(refreshed_order).data, status=status.HTTP_200_OK)
