from smartfarming.models.pests_bank import MongoPestBank
from rest_framework.views import APIView
from django.core.paginator import Paginator
from smartfarming.serializers.pests_serializers import PestBankSerializers
from rest_framework.response import Response


class PestBankAPIView(APIView):

    def post(self, request):
        # 病虫列表
        request_data = request.data 
        code = request_data.get("code")
        page_num = int(request_data.get("pagenum", 1))
        page_size = int(request_data.get("pagesize", 10))
        pest_name = request_data.get("pest_name")
        if pest_name:
            queryset = MongoPestBank.objects.filter(name__icontains=pest_name).order_by("-search")
        else:
            queryset = MongoPestBank.objects.filter(code=code).order_by("-search")
        total_obj = queryset.count()
        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page_num)
        serializers = PestBankSerializers(page_obj, many=True)
        pest_nums = MongoPestBank.objects.filter(code=2).count()
        disease_nums = MongoPestBank.objects.filter(code=1).count()
        return Response(
            {
                "code": 0, 
                "msg": "success", 
                "data": serializers.data, 
                "count": total_obj, 
                "pest_nums": pest_nums, 
                "disease_nums": disease_nums
            }
        )
