import threading

import jdatetime
from rest_framework.pagination import PageNumberPagination

# .

from authentication.helper.refresh import refresh
from authentication.sms_management import poultry_request_receive_city_accept_sms, \
    poultry_request_receive_province_accept_sms

from panel.CityOperator.serializers import (
    CityOperatorCheckRequestSerializer,
    CityOperatorSerializer, CityOperatorForPoultrySerializer, CityOperatorForSubSectorSerializer,
    CityOperatorForSubSectorTransactionsSerializer
)
from authentication.serializer.serializer import (
    SystemAddressSerializer,
    BankCardSerializer
)
from authentication.models import SystemAddress, CityUnit
from panel.poultry.serializers import PoultrySerializer, PoultryRequestSerializer, \
    PoultryRequestForKillingInformationSerializer
from panel.convert_date import convert_to_miladi
from panel.models import (
    CityOperatorCheckRequest,
    PoultryRequest,
    CityOperator,
    PoultryRequestAuction,
    ProvinceOperator,
    Poultry, PoultryHatching, VetFarm, VetFarmInspection, SmsLicense, ProvinceCheckOperatorRequest, ProvinceKillRequest,
    KillHouseCheckRequest, KillRequest
)
from authentication.models import (
    City,
    Province
)
from authentication.models import SystemUserProfile
from panel.filterset import UserProfileFilterSet, CityOperatorRequestFilterSet, PoultryRequestFilterSet
from django_filters.rest_framework import DjangoFilterBackend
from authentication.permissions import CityOperator as CityOperatorPermission
from authentication.permissions import ProvinceOperator as provinceOperatorPermission
from authentication.models import UserProfile, UserMessage
from rest_framework.response import Response
from django.contrib.auth.models import User
from rest_framework import viewsets
from oauth2_provider.contrib.rest_framework import (
    TokenHasReadWriteScope,
    OAuth2Authentication,
)
from rest_framework import status
from django.http import QueryDict
from datetime import datetime, timedelta
from django.db.models import Q
from panel.helper import remove_null_fields

class CustomPagination(PageNumberPagination):
    page_size = 10

class ShowCityOperatorViewSet(viewsets.ModelViewSet):
    queryset = CityOperator.objects.all()
    serializer_class = CityOperatorSerializer
    permission_classes = [TokenHasReadWriteScope]

    # def list(self, request, *args, **kwargs):
    #     # refresh(request.user.id)
    #     if 'breeding_uniq_id' in request.GET:
    #         poultry = Poultry.objects.get(breeding_unique_id=request.GET['breeding_uniq_id'])
    #     else:
    #
    #         user = SystemUserProfile.objects.get(user=request.user)
    #         poultry = Poultry.objects.get(user=user)
    #     # city = City.objects.get(key=poultry.address.city.key)
    #
    #     city_unit = CityUnit.objects.get(name=poultry.address.city.name)
    #     # city_operator_system = CityOperator.objects.get(address__city=city_unit.city, trash=False)
    #     operator_list = []
    #     opertors = CityOperator.objects.filter(address__city__name__in=(city_unit.city.name, 'فاقد شهرستان'),
    #                                            trash=False)
    #     # poultry_request = PoultryRequest.objects.filter(trash=False, poultry=poultry).select_related(
    #     #     'city_operator').last()
    #
    #     for opertor in opertors:
    #         last = True if poultry.city_operator == opertor.unit_name else False
    #         operator_dict = {
    #             "key": opertor.key,
    #             "unit_name": opertor.unit_name,
    #             "last": last
    #         }
    #         operator_list.append(operator_dict)
    #
    #     return Response(operator_list)

    def list(self, request, *args, **kwargs):
        operator_list = []
        if 'breeding_uniq_id' in request.GET:
            poultry = Poultry.objects.get(breeding_unique_id=request.GET['breeding_uniq_id'])
        else:

            user = SystemUserProfile.objects.get(user=request.user)
            poultry = Poultry.objects.get(user=user)
        opertor = CityOperator.objects.filter(unit_name=poultry.city_operator,

                                              trash=False).last()
        if not opertor:
            opertor = CityOperator.objects.filter(unit_name='اتحادیه استان (فاقد تعاونی)',

                                                  trash=False).last()

        operator_dict = {
            "key": opertor.key,
            "unit_name": opertor.unit_name,
        }
        operator_list.append(operator_dict)

        return Response(operator_list)


# ویوست مربوط به اپراتور شهرستان
class CityOperatorViewSet(viewsets.ModelViewSet):
    queryset = CityOperator.objects.all()
    serializer_class = CityOperatorSerializer
    permission_classes = [TokenHasReadWriteScope]

    def retrieve(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)

        # get city operator profile information
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)

            # get operator object
            operator = user.city_operator_user.all()

            # send to serializer
            serializer = self.serializer_class(operator[0])
            return Response(serializer.data, status=status.HTTP_200_OK)

    def list(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        city_operators = CityOperator.objects.filter(address__province=user.province, trash=False)
        serializer = CityOperatorForPoultrySerializer(city_operators, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)




class CityOperatorForSubSectorViewSet(viewsets.ModelViewSet):
    queryset = CityOperator.objects.all()
    serializer_class = CityOperatorForSubSectorSerializer
    permission_classes = [TokenHasReadWriteScope]


    def list(self, request, pk=None, *args, **kwargs):

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        city_operators = CityOperator.objects.filter(address__province=user.province, trash=False)
        if 'operators' in request.GET:

            serializer = CityOperatorForSubSectorTransactionsSerializer(city_operators, many=True)
        else:
            serializer = self.serializer_class(city_operators, many=True,context={'request':request})
        return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به بررسی درخواست مرغدار
class CityOperatorCheckRequestViewSet(viewsets.ModelViewSet):
    queryset = CityOperatorCheckRequest.objects.all()
    serializer_class = CityOperatorCheckRequestSerializer
    # permission_classes = [TokenHasReadWriteScope, provinceOperatorPermission, CityOperatorPermission]
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = CityOperatorRequestFilterSet
    filterset_fields = [
        'poultry_request__user__mobile',
        'poultry_request__user__fullname',
        'poultry_request__user__first_name',
        'poultry_request__user__last_name',
        'poultry_request__user__address__breeding_unique_id',
        'poultry_request__order_code',
    ]

    # تابع برای تایید یا رد درخواست مرغدار توسط شهرستان
    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        # refresh(request.user.id)
        role = request.data['role']
        request.data.pop('role')
        key = request.data['key']
        state = request.data['state']
        poultry_request = PoultryRequest.objects.get(key=key, trash=False)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
        if role == 'ProvinceOperator':
            province_operator = SystemUserProfile.objects.filter(user=request.user, trash=False)
            if province_operator.count() > 0:
                province_operator = province_operator.last()
            # city_unit = CityUnit.objects.get(name=poultry_request.poultry.address.city.name)
            # city_operator_system = CityOperator.objects.get(address__city=city_unit.city, trash=False)
            city_operator_system = CityOperator.objects.get(key=poultry_request.city_operator.key, trash=False)
            city_operator = SystemUserProfile.objects.get(key=city_operator_system.user.key, trash=False)

        else:
            city_operator = SystemUserProfile.objects.get(user=request.user, trash=False)
            city_operator_system = CityOperator.objects.get(key=poultry_request.city_operator.key, trash=False)
            province = city_operator.province.name
            province_operator = SystemUserProfile.objects.filter(role__name='ProvinceOperator',
                                                                 province__name=province, trash=False).last()
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            city_operator_check_request = serializer.create(validated_data=request.data)
            if state == 'accept':
                poultry_request.state = {
                    "city_operator": city_operator.first_name + " " + city_operator.last_name,
                    "city_state": "accepted",
                    "city_operator_mobile": city_operator.mobile,
                    "city_operator_date_time_accepted": str(city_operator_check_request.create_date),
                    "province_operator": province_operator.first_name + " " + province_operator.last_name,
                    "provice_operator_mobile": province_operator.mobile,
                    "province_state": "pending"
                }
                poultry_request.state_process = 'accepted'
                poultry_auctions = PoultryRequestAuction.objects.filter(poultry_request=poultry_request,
                                                                        trash=False).order_by(
                    'auction_date')
                if poultry_auctions.count() > 0:
                    list2 = []
                    i = 0
                    for poultry_auction in poultry_auctions:
                        if i == 0:
                            poultry_auction.auction_date = datetime.now() + timedelta(
                                hours=int(poultry_auction.hour))
                            poultry_auction.state = 'active'
                            poultry_auction.save()
                            list2.append(poultry_auction)
                        else:
                            poultry_auction.auction_date = list2[0].auction_date + timedelta(
                                hours=int(poultry_auction.hour))
                            poultry_auction.save()
                            list2.clear()
                            list2.append(poultry_auction)

                        i += 1

                message = UserMessage(
                    message="درخواست شما با کد سفارش {0} از طرف کارشناس شهرستان {1} تایید شده است و در حال حاضر در انتظار تایید کارشناس استان {2} میباشد ".format(
                        poultry_request.order_code, city_operator.fullname, province_operator.fullname),
                    heading="پیام سیستم ثبت شده در تاریخ {0}".format(datetime.now()),
                    sender=city_operator
                )
                message.save()
                message.users.add(poultry_request.poultry.user)

            if state == 'reject':
                if poultry_request.kill_house_list != None and len(poultry_request.kill_house_list) > 0:
                    for item in poultry_request.kill_house_list:
                        parts = item.split("(")
                        name = parts[0].strip()

                        kill_request = KillRequest.objects.filter(kill_house__name=name,
                                                                  recive_date__date=poultry_request.send_date.date(),
                                                                  trash=False, poultry__isnull=True,
                                                                  province_state='accepted').first()
                        if kill_request:
                            kill_request.remain_quantity_for_poultry -= poultry_request.quantity
                            kill_request.save()
                poultry_request.state = {
                    "city_operator": city_operator.first_name + " " + city_operator.last_name,
                    "city_state": " rejected",
                    "city_operator_date_time_rejected": str(city_operator_check_request.create_date),
                    "province_operator": "",
                    "province_state": ""
                }
                # hatching.left_over += (poultry_request.quantity + poultry_request.losses)
                hatching.losses -= poultry_request.losses
                hatching.state = 'pending'
                hatching.allow_hatching = 'pending'
                hatching.save()
                poultry_request.message = city_operator_check_request.message
                poultry_request.state_process = 'rejected'
                message = UserMessage(
                    message="درخواست شما با کد سفارش {0} از طرف کارشناس شهرستان {1} رد شده است ".format(
                        poultry_request.order_code, city_operator.fullname),
                    heading="پیام سیستم ثبت شده در تاریخ {0}".format(datetime.now()),
                    sender=city_operator
                )
                message.save()
                message.users.add(poultry_request.poultry.user)
            city_operator_check_request.city_operator_system = city_operator_system
            city_operator_check_request.poultry_request = poultry_request
            if poultry_request.auction == True:
                city_operator_check_request.show_province = False
            poultry_request.save()
            if role == 'ProvinceOperator':
                city_operator_check_request.province_accept = True
            city_operator_check_request.save()
            if state == 'accept':
                if SmsLicense.objects.filter(city_approval=True).exists():
                    poultry_mobile = city_operator_check_request.poultry_request.poultry.user.mobile
                    order_code = city_operator_check_request.poultry_request.order_code
                    date_str = str(city_operator_check_request.poultry_request.send_date)
                    send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                    send_date = jdatetime.datetime.fromgregorian(year=send_date.year, month=send_date.month,
                                                                 day=send_date.day).strftime('%Y-%m-%d')
                    date_list = reversed(send_date.split('-'))
                    separate = "-"
                    send_date = separate.join(date_list)
                    sms_poultry_request_receive_city_accept_sms = threading.Thread(
                        target=poultry_request_receive_city_accept_sms,
                        args=(
                            poultry_mobile,
                            send_date,city_operator_check_request.poultry_request.order_code,
                            send_date,city_operator_check_request.poultry_request.free_sale_in_province,

                        ))
                    sms_poultry_request_receive_city_accept_sms.start()

                if role == 'ProvinceOperator':
                    poultry_mobile = city_operator_check_request.poultry_request.poultry.user.mobile
                    order_code = city_operator_check_request.poultry_request.order_code

                    province_operator = ProvinceOperator.objects.filter(
                        user=SystemUserProfile.objects.get(role__name='ProvinceOperator', province=user.province))

                    if province_operator.count() > 0:
                        province_operator = province_operator.last()

                    check = ProvinceCheckOperatorRequest(
                        province_operator_system=province_operator,
                        poultry_request=city_operator_check_request.poultry_request,
                        city_request_Poultry=city_operator_check_request,
                        quantity=poultry_request.quantity,

                        state='accept',
                    )
                    check.save()
                    city_operator_check_request.province_state = 'accept'
                    city_operator_check_request.save()
                    poultry_request.province_state = 'accepted'
                    poultry_request.save()
                    sms_poultry_request_receive_province_accept_sms_sms = threading.Thread(
                        target=poultry_request_receive_province_accept_sms,
                        args=(
                            poultry_mobile, order_code))
                    sms_poultry_request_receive_province_accept_sms_sms.start()

            return Response({"result": "درخواست شما با موفقیت برای استان ارسال شد."}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    # تابع برای نمایش  درخواست های تایید شده مرغدار توسط شهرستان
    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        queryset = []

        if 'state' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user)

            if request.GET['state'] == 'waiting':
                if 'date' in request.GET:
                    date = datetime.strptime(request.GET['date'], '%Y-%m-%d')
                else:
                    date = datetime.now().date()

                queryset = []
                queryset = CityOperatorCheckRequest.objects.filter(
                    show_province=True, city_operator_system__address__province=user.province,
                    poultry_request__final_state='pending', trash=False, poultry_request__direct_buying=False,
                    poultry_request__send_date__year=date.year, poultry_request__send_date__month=date.month,
                    poultry_request__send_date__day=date.day
                ).order_by(
                    '-poultry_request__send_date')
                # item_list = CityOperatorCheckRequest.objects.filter(
                #     show_province=True, city_operator_system__address__province=user.province,
                #     poultry_request__final_state='pending', trash=False,
                #     poultry_request__send_date__year=date.year, poultry_request__send_date__month=date.month,
                #     poultry_request__send_date__day=date.day
                # ).order_by(
                #     '-poultry_request__send_date')
                # for req in item_list:
                #     province_check_req = ProvinceCheckOperatorRequest.objects.filter(city_request_Poultry=req)
                #     if province_check_req.count() > 0:
                #         province_check_req = province_check_req.last()
                #         if province_check_req.quantity > 0 and province_check_req.state == 'accept' or province_check_req.state == 'pending':
                #             if req in queryset:
                #                 pass
                #             else:
                #                 queryset.append(req)
                #         province_kill_reqs = ProvinceKillRequest.objects.filter(province_request=province_check_req)
                #         if province_kill_reqs.count() > 0:
                #             counter = 0
                #             for province_kill_req in province_kill_reqs:
                #                 if KillHouseCheckRequest.objects.filter(
                #                         province_kill_request=province_kill_req, state='accepted').exists():
                #                     counter += 1
                #             if province_kill_reqs.count() == counter and province_check_req.quantity == 0:
                #                 pass
                #             else:
                #
                #                 if req in queryset:
                #                     pass
                #                 else:
                #                     queryset.append(req)

            elif request.GET['state'] == 'all':
                queryset = CityOperatorCheckRequest.objects.filter(
                    show_province=True, city_operator_system__address__province=user.province,
                    poultry_request__final_state='pending', trash=False).order_by(
                    '-poultry_request__send_date')
            elif request.GET['state'] == 'new':
                if 'date1' in request.GET and 'date2' in request.GET:
                    date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    queryset_list = CityOperatorCheckRequest.objects.filter(state='accept', province_state='pending',
                                                                            show_province=True,
                                                                            city_operator_system__address__province=user.province,
                                                                            trash=False).order_by(
                        'poultry_request__send_date')

                    queryset = [
                        city_check for city_check in queryset_list
                        if date1 <= city_check.poultry_request.send_date.date() <= date2
                    ]
            else:
                pass
        # if 'state' in request.GET:
        #     if request.GET['state'] == 'CityOperator':
        #         user = SystemUserProfile.objects.get(user=request.user)
        #         city_operator = CityOperator.objects.get(user=user)
        #         queryset = CityOperatorCheckRequest.objects.filter(
        #             poultry_request__user__address__city=city_operator.address.city).order_by('-create_date')

        if 'type' in request.GET:
            if request.GET['type'] == 'filter':
                for item in self.filterset_fields:
                    query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                    if (self.filterset_class(
                            data=query,
                            queryset=self.queryset.filter(state__exact="accept", trash=False)
                    )
                    ).filter():
                        ps = self.filterset_class(data=query, queryset=self.queryset)
                        filtered_city_operator = ps.filter()
                        serializer = self.serializer_class(filtered_city_operator, many=True)
                        return Response(serializer.data)
            return Response({"msg": "Enter 'Type' In Get Parameters"}, status=status.HTTP_403_FORBIDDEN)

        serializer = CityOperatorCheckRequestSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

class CityOperatorCheckRequestNewViewSet(viewsets.ModelViewSet):
    queryset = CityOperatorCheckRequest.objects.all()
    serializer_class = CityOperatorCheckRequestSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = CityOperatorRequestFilterSet
    filterset_fields = [
        'poultry_request__poultry__user__mobile',
        'poultry_request__poultry__user__fullname',
        'poultry_request__poultry__user__first_name',
        'poultry_request__poultry__user__last_name',
        'poultry_request__poultry__user__city__name',
        'poultry_request__order_code',
    ]

    # تابع برای نمایش  درخواست های تایید شده مرغدار توسط شهرستان
    def list(self, request, *args, **kwargs):
        queryset = []

        if 'state' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user)

            if request.GET['state'] == 'waiting':
                if 'date' in request.GET:
                    date = datetime.strptime(request.GET['date'], '%Y-%m-%d')
                else:
                    date = datetime.now().date()

                queryset = []
                queryset = CityOperatorCheckRequest.objects.filter(
                    show_province=True, city_operator_system__address__province=user.province,
                    poultry_request__final_state='pending', trash=False, poultry_request__direct_buying=False,
                    poultry_request__send_date__year=date.year, poultry_request__send_date__month=date.month,
                    poultry_request__send_date__day=date.day
                ).order_by(
                    '-poultry_request__send_date')


            elif request.GET['state'] == 'all':
                queryset = CityOperatorCheckRequest.objects.filter(
                    show_province=True, city_operator_system__address__province=user.province,
                    poultry_request__final_state='pending', trash=False).order_by(
                    '-poultry_request__send_date')
            elif request.GET['state'] == 'new':
                if 'date1' in request.GET and 'date2' in request.GET:
                    date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    queryset = CityOperatorCheckRequest.objects.filter(state='accept', province_state='pending',
                                                                            show_province=True,
                                                                            poultry_request__send_date__date__gte=date1,
                                                                            poultry_request__send_date__date__lte=date2,
                                                                            city_operator_system__address__province=user.province,
                                                                            trash=False).order_by(
                        'poultry_request__send_date')

                    # queryset = [
                    #     city_check for city_check in queryset_list
                    #     if date1 <= city_check.poultry_request.send_date.date() <= date2
                    # ]
            else:
                pass

            if 'search' in request.GET:
                city_check_requests = []
                if request.GET['search'] == 'filter':
                    if request.GET['value'] != "":
                        for item in self.filterset_fields:
                            query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                            if (self.filterset_class(
                                    data=query,
                                    queryset=queryset
                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=queryset)
                                city_check_requests = ps.filter()
                        queryset = [] if len(city_check_requests) == 0 else city_check_requests
        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        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 = CityOperatorCheckRequestSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)



class PoultryEditByCityOperatorViewSet(viewsets.ModelViewSet):
    queryset = Poultry.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultrySerializer

    def update(self, request, *args, **kwargs):
        # refresh(request.user.id)
        # get  poultry object
        poultry_object = self.queryset.get(key=request.data['poultry_key'], trash=False)
        request.data.pop('poultry_key')

        # Remove Null Fields From Address Body
        request = remove_null_fields(type='item', request=request, item='address')
        # Remove Null Fields From User Bank Info Body
        request = remove_null_fields(type='item', request=request, item='user_bank_info')
        # Remove Null Fields From request Body
        request = remove_null_fields(type='req', request=request)

        # update address information
        address_data = request.data['address']
        province = None
        city = None
        if 'province' and 'city' in address_data.keys():
            province = Province.objects.get(key=address_data['province'], trash=False)
            address_data.pop('province')
            city = City.objects.get(key=address_data['city'], trash=False)
            address_data.pop('city')
        address_serializer = SystemAddressSerializer(data=address_data)
        if address_serializer.is_valid():
            addr_object = address_serializer.update(
                instance=poultry_object.address,
                validated_data=address_data
            )
        if province != None and city != None:
            addr_object.province = province
            addr_object.city = city
            addr_object.save()
        request.data.pop('address')

        # update user bank information
        if poultry_object.user_bank_info != None:
            bank_data = request.data['user_bank_info']
            bank_serializer = BankCardSerializer(data=bank_data)
            if bank_serializer.is_valid():
                bank_object = bank_serializer.update(
                    instance=poultry_object.user_bank_info,
                    validated_data=bank_data
                )
                request.data.pop('user_bank_info')
        else:
            bank_data = request.data['user_bank_info']
            bank_serializer = BankCardSerializer(data=bank_data)
            if bank_serializer.is_valid():
                bank_object = bank_serializer.create(
                    validated_data=bank_data
                )
                request.data.pop('user_bank_info')

        # sending data to serializer & update poultry object
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            obj = serializer.update(
                instance=poultry_object,
                validated_data=request.data
            )
            obj.user_bank_info = bank_object
            obj.save()
            serializer = self.serializer_class(obj)
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ManagementRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    # filterset_class = PoultryRequestFilterSet
    filterset_fields = [
        'order_code',
        'poultry__user__mobile',
        'poultry__user__fullname',
        'poultry__user__first_name',
        'poultry__user__last_name',
        'poultry__address__city__name',

    ]
    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        date1 = datetime.strptime(str(request.GET['date1']),
                                           '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(str(request.GET['date2']),
                                           '%Y-%m-%d').date() if 'date2' in request.GET else now
        poultry_requests = []
        user = SystemUserProfile.objects.get(user=request.user)
        queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                 trash=False, state_process__in=('pending', 'accepted'),
                                                                 province_state='pending',
                                                                 final_state='pending', out=False,
                                                 send_date__date__gte=date1, send_date__date__lte=date2
                                                 ).order_by('-send_date')

        if 'search' in request.GET:
            if request.GET['search'] == 'filter':
                if request.GET['value'] != "":
                    for item in self.filterset_fields:
                        query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                        if (PoultryRequestFilterSet(
                                data=query,
                                queryset=queryset
                        )
                        ).filter():
                            ps = PoultryRequestFilterSet(data=query, queryset=queryset)
                            poultry_requests = ps.filter()
                    queryset = [] if len(poultry_requests) == 0 else poultry_requests

        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = PoultryRequestForKillingInformationSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = PoultryRequestForKillingInformationSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
