from apps.sam.serializers import ContractCreateUpdateSerializer, ContractSerializer, CustomerCreateUpdateSerializer, CustomerSerializer, OrderCreateUpdateSerializer, OrderSerializer
from apps.sam.models import Contract, Customer, Order
from rest_framework.viewsets import ModelViewSet
from apps.system.mixins import CreateUpdateCustomMixin
from django.shortcuts import render
from rest_framework.decorators import action
from django.db.models import F
from rest_framework.response import Response
# Create your views here.
class CustomerViewSet(CreateUpdateCustomMixin, ModelViewSet):
    """
    客户-增删改查
    """
    perms_map = {'*': '*'}
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    search_fields = ['name', 'contact']
    filterset_fields = []
    ordering_fields = ['create_time']
    ordering = ['-create_time']

    def get_serializer_class(self):
        if self.action in ['create', 'update']:
            return CustomerCreateUpdateSerializer
        return CustomerSerializer


class ContractViewSet(CreateUpdateCustomMixin, ModelViewSet):
    """
    合同-增删改查
    """
    perms_map = {'*': '*'}
    queryset = Contract.objects.select_related('customer').all()
    serializer_class = ContractSerializer
    search_fields = ['name']
    filterset_fields = []
    ordering_fields = ['create_time']
    ordering = ['-create_time']

    def get_serializer_class(self):
        if self.action in ['create', 'update']:
            return ContractCreateUpdateSerializer
        return ContractSerializer

class OrderViewSet(CreateUpdateCustomMixin, ModelViewSet):
    """
    订单-增删改查
    """
    perms_map = {'*': '*'}
    queryset = Order.objects.select_related('contract', 'customer').all()
    serializer_class = OrderSerializer
    search_fields = ['number', 'product']
    filterset_fields = []
    ordering_fields = ['create_time']
    ordering = ['-create_time']

    def get_serializer_class(self):
        if self.action in ['create', 'update']:
            return OrderCreateUpdateSerializer
        return OrderSerializer

    @action(methods=['get'], detail=False, perms_map={'get':'*'})
    def toplan(self, request, pk=None):
        queryset = Order.objects.filter(count__gt=F('planed_count')).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)