import math
import threading
from io import BytesIO
from typing import List, Dict

import openpyxl
import requests
from django.contrib.auth.models import Group
from django.db.models import Q, Prefetch, Min, Max, Avg, Case, When, IntegerField, ExpressionWrapper, FloatField
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView

from authentication.sahandsms.sms import kill_house_price
from general_urls import base_url_for_sms_report
from panel.ReportingPanel.views import (
    get_gid_poultry_request,
    get_gid_poultry_request_quarantine_code,
)
from panel.admin import PROJECT_API_KEY
from panel.helper import build_query
from panel.helper_excel import percent_of_losses
from panel.poultry.helpers import poultry_prediction_helper, calculate_hatching_increase, \
    create_update_chicken_commission_prices, market_daily_limitation_info
from ticket.bucket import upload_to_liara, delete_file_from_liara

ARTA_URL_REGISTER = "https://userbackend.rasadyar.com/api/register/"

ARTA_URL_CHANGE_MOBILE_NUMBER = "https://userbackend.rasadyar.com/change_mobile_number/"
from authentication.models import User, Province
import random
import string
from datetime import datetime, timedelta
from django.http import QueryDict
from django.views.decorators.csrf import csrf_exempt
from django_filters.rest_framework import DjangoFilterBackend
from num2fawords import words
from oauth2_provider.contrib.rest_framework import (
    TokenHasReadWriteScope,
)
from django.utils import timezone
from django.db.models import F
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

from ticket.helper import send_image_to_server
from authentication.models import UserProfile, UserMessage, SystemUserProfile, CityUnit, City
from authentication.serializer.serializer import SystemUserProfileSerializer
from django.db.models import Sum
from authentication.sms_management import operator_hatching_sms, operator_poultry_request_sms, \
    operator_out_poultry_request_sms, sms_chain_company_for_ver_farm, \
    confirm_price_poultry_request_sms, send_sms_for_poultry_market
from panel.KillHouse.serializers import PoultryRequestExchangeAcceptSerializer, ProvinceKillRequestSerializer, \
    KillHouseRequestSerializer, KillHouseRequestForBarManagementSerializer, \
    PoultryRequestLetterTotalSerializer, \
    PoultryRequestoutProvinceSerializer, KillHouseRequestForHatchingDetailSerializer, \
    ReturnProvinceKillRequestSerializer, BarDifferenceRequestSerializer
from panel.convert_date import *
from panel.filterset import PoultryRequestExchangeFilterSet, PoultryFilterSet, PoultryHatchingFilterSet, \
    PoultryRequestFilterSet, ChainAllocationFilterSet, ChainCompanyFilterSet, OutProvincePoultryRequestBuyerFilterSet, \
    DashboardPoultryRequestFilterSet, PoultryManageFilterSet, HatchingIncreaseRequestFilterSet, \
    PoultryRequestDirectBuyingFilterSet, EvacuationHatchingDetailFilterSet
from panel.models import (
    PoultryRequest,
    PoultryAssignmentInformation,
    KillHouseRequest,
    CityOperatorCheckRequest,
    ProvinceCheckOperatorRequest,
    DepositAllocation,
    PovinceInspector,
    KillHouseAssignmentInformation,
    KillHouseFactorToProvince,
    ProvinceFactorToKillHouse,
    VetCheckRequest,
    PoultryRequestExchange,
    PoultryRequestExchangeAccept,
    KillHouseRequestExchangeReserve,
    KillHouseCheckRequest,
    ProvinceKillRequest,
    PoultryHatching,
    Poultry,
    PoultryTenant, CityOperator, PoultryRequestAuction, Pricing, KillHouseRequestAction, KillHouseRequestActionWinner,
    ProvinceRequestAction, VetFarmInspection, InspectorOperator, ProvinceOperator,
    KillHouseOperator, KillHouse, Vet, KillHouseVet, VetFarm, ShareOfAllocation, ProvinceFactorToKillHouseForPoultry,
    KillHouseFactorToPoultry, KillHouseComplaint, KillHouseDriver, KillRequest, CheckUnusualCasualties,
    PercentageOfLosses, ProvinceImportKillHouseOutFactors, TotalPoultryRequestQuantity, HourLimit, KillHousePercentage,
    SmsLicense, ProvinceAllowPoultryChooseKillHouse, ProvinceAllowPoultrySellFree, LastUpdate, FreeSaleWithinprovince,
    OperationLimitation, ChickenAgeRange, TimeRange, ChainCompany, Wallet, ChainAllocation, WageType,
    PercentageOfWageType, ChainCompanyTransaction, InternalTransaction, OutProvincePoultryRequestBuyer,
    PoultryOutProvinceRequest, PoultryPrediction, PriceConfirmation, HatchingIncreaseRequest,
    ChickenCommissionPrices, PoultryRequestQuarantineCode, FinePermission, ShowMarketRequest,
    ManagementHatchingAgeRange, IndexWeightCategory, PoultryScience, BarDifferenceRequest, EvacuationHatchingDetail,
    MarketDailyLimitation, HatchingArchivePercent
)
from panel.poultry.serializers import (
    PoultryRequestSerializer,
    PoultryAssignmentInformationSerializer,
    PoultryRequestExchangeSerializer,
    PoultryHatchingSerializer,
    PoultrySerializer,
    PoultryTenantSerializer, TotalPoultryRequestQuantitySerializer, PoultryForPoultryHatchingSerializer,
    TotalPoultrySerializer, LastUpdateSerializer, PoultryRequestForKillingInformationSerializer,
    PoultryForPoultryHatchingForKillInformationSerializer, ChainCompanySerializer, ChainAllocationSerializer,
    ChainCompanyTransactionSerializer, ChainCompanyForTotalWageAllocationWithDAteSerializer,
    ChainCompanyForTotalWageAllocationSerializer, ChainAllocationForWageSerializer,
    ChainCompanyForTotalWageTransactionSerializer, ChainCompanyForTotalWageTransactionTransactionWithDAteSerializer,
    OutProvincePoultryRequestBuyerSerializer, OutProvincePoultryRequestBuyerForBuyerRequestSerializer,
    ChainCompanyForCompanyRequestSerializer, PoultryLocationSerializer, GetAllPoultrySerializer,
    PoultryHatchingForPredictionSerializer, PoultryPredictionSerializer, HatchingIncreaseRequestSerializer,
    ChickenCommissionPricesSerializer, PoultryRequestQuarantineCodeSerializer, PoultryHatchingForDetailsSerializer,
    PoultryRequestForHatchingDetailSerializer, ChainAllocationForHatchingDetailSerializer,
    PoultryHatchingForBazrasiSerializer, PoultryRequestForDirectBuyingSerializer, ManagementHatchingAgeRangeSerializer,
    EvacuationHatchingDetailSerializer, PoultryHatchingForPoultryAndHatchingForPoultryScienceSerializer,
    PoultryDetailForPoultryAndHatchingForPoultryScienceSerializer
)

# آدرس پایه برای ذخیره عکس در گالری مرغدار بر روی استوریج آروان
ARVAN_poultry_URL = 'https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/'


# ARVAN_poultry_URL = 'https://poultry-gallery.s3.ir-thr-at1.arvanstorage.ir/'


def update_chain_hatching(poultry_hatching):
    chain_allocations = ChainAllocation.objects.filter(trash=False, state='accepted', poultry_hatching=poultry_hatching)
    total_killed_quantity = chain_allocations.aggregate(total=Sum('quantity'))['total'] or 0
    total_killed_weight = chain_allocations.aggregate(total=Sum('weight'))['total'] or 0

    poultry_hatching.chain_killed_quantity = total_killed_quantity
    poultry_hatching.chain_killed_weight = total_killed_weight
    poultry_hatching.save()


class CustomPagination(PageNumberPagination):
    page_size = 10


class OutProvincePoultryRequestBuyerViewSet(viewsets.ModelViewSet):
    queryset = OutProvincePoultryRequestBuyer.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = OutProvincePoultryRequestBuyerSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = OutProvincePoultryRequestBuyerFilterSet
    filterset_fields = [
        'mobile',
        'kill_house_unique_id',
        'user__national_id',
        'user__base_order',
        'user__mobile',
        'user__first_name',
        'user__last_name',
        'user__fullname',
        'unit_name',

    ]

    def create(self, request, *args, **kwargs):
        operator_user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).exists():
            return Response({"result": "این کاربر قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)

        else:
            password = "00100"
            data = {
                "username": request.data['mobile'],
                "password": password,
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_URL_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code in (200, 400):
                user = User(username=request.data['mobile'], first_name=request.data['fullname'])
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                system_profile = SystemUserProfile(
                    mobile=request.data['mobile'],
                    first_name=request.data['fullname'],
                    fullname=request.data['fullname'],
                    user=user,
                    base_order=base_id,
                    password=password,
                    city=operator_user.city,
                    province=operator_user.province
                )
                system_profile.save()
            else:
                return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            buyer = serializer.create(validated_data=request.data)
            buyer.user = system_profile
            buyer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    def list(self, request, *args, **kwargs):
        buyer_list = []
        if 'state' in request.GET:
            buyers = OutProvincePoultryRequestBuyer.objects.filter(trash=False).order_by('id')
            if 'search' in request.GET:
                if request.GET['search'] == 'filter':
                    if request.GET['value'] != "" and request.GET['value'] != 'undefined':
                        for item in self.filterset_fields:
                            query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                            if (self.filterset_class(
                                    data=query,
                                    queryset=buyers
                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=buyers)
                                buyer_list = ps.filter()
                        buyers = [] if len(buyer_list) == 0 else buyer_list

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

            page = self.paginate_queryset(buyers)
            if page is not None:
                serializer = OutProvincePoultryRequestBuyerForBuyerRequestSerializer(page, many=True)
                return self.get_paginated_response(serializer.data)
        else:
            buyers = OutProvincePoultryRequestBuyer.objects.filter(active=True, trash=False).order_by('id')
            serializer = self.get_serializer(buyers, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        buyer = OutProvincePoultryRequestBuyer.objects.get(key=request.data['buyer_key'], trash=False)
        request.data.pop('buyer_key')
        system_user_profile = SystemUserProfile.objects.get(key=buyer.user.key, trash=False)
        if 'fullname' in request.data.keys():
            system_user_profile.first_name = request.data['fullname']
            system_user_profile.fullname = request.data['fullname']
            system_user_profile.save()
        if 'mobile' in request.data.keys():
            first_mobile_number = system_user_profile.mobile
            second_mobile_number = request.data['mobile']
            if first_mobile_number != second_mobile_number:
                if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
                    return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                    status=status.HTTP_403_FORBIDDEN)
                data = {
                    "first_mobile_number": first_mobile_number,
                    "second_mobile_number": second_mobile_number,
                }
                req = requests.post(
                    url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                    data=data,
                    verify=False
                )
                if req.status_code == 200:
                    second_mobile_number = second_mobile_number
                    user = User.objects.get(id=system_user_profile.user.id)
                    user.username = second_mobile_number
                    user.save()
                    system_user_profile.mobile = second_mobile_number
                    system_user_profile.save()

        serializer = self.serializer_class(buyer)
        serializer.update(instance=buyer, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        buyer = OutProvincePoultryRequestBuyer.objects.get(key=request.GET["buyer_key"], trash=False)
        buyer.trash = True
        buyer.save()
        return Response({"result": "با موفقیت حذف شد."}, status=status.HTTP_200_OK)


class TotalPoultryViewSet(viewsets.ModelViewSet):
    queryset = Poultry.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = TotalPoultrySerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = PoultryManageFilterSet
    filterset_fields = [
        'breeding_unique_id',
        'user__national_id',
        'user__base_order',
        'user__mobile',
        'user__first_name',
        'user__last_name',
        'address__city__name',
        'unit_name',

    ]

    def list(self, request, *args, **kwargs):
        poultries = []

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'search' in request.GET:
            if 'role' in request.GET:
                if request.GET['role'] == 'CityOperator':
                    city_operator = CityOperator.objects.get(user=user, trash=False)
                    poultries = Poultry.objects.filter(city_operator=city_operator.unit_name, trash=False).order_by(
                        'id')

                elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                    poultries = Poultry.objects.filter(address__city=user.city, trash=False).order_by('id')
                else:
                    poultries = Poultry.objects.filter(trash=False).order_by('id')
            else:
                poultries = Poultry.objects.filter(trash=False).order_by('id')

            value = request.GET.get('value')
            search = request.GET.get('search')
            if value and search == 'filter':
                if value != 'undefined' and value.strip():
                    poultries = poultries.filter(
                        build_query(self.filterset_class, value))

        else:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                poultries = Poultry.objects.filter(city_operator=city_operator.unit_name, trash=False).order_by('id')


            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                poultries = Poultry.objects.filter(address__city=user.city, trash=False).order_by('id')
            else:
                poultries = Poultry.objects.filter(address__province=user.province, trash=False).order_by('id')
        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

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

        serializer = self.get_serializer(poultries, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به ثبت و نمایش و ... مرغداری
class PoultryViewSet(viewsets.ModelViewSet):
    queryset = Poultry.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultrySerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = PoultryFilterSet
    filterset_fields = [
        'breeding_unique_id',
        'user__national_id',
        'user__base_order',
        'user__mobile',

    ]

    # تابع مربوط به ویرایش مرغداری
    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        poultry = Poultry.objects.get(key=request.data["key"], trash=False)
        request.data.pop('key')
        serializer = self.serializer_class(poultry)
        serializer.update(instance=poultry, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

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

        # refresh(request.user.id)

        # list of self poultry houses
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'type' in request.GET:
            if request.GET['type'] == 'filter':
                poultry_list = []
                # for poultry in self.queryset.filter(trash=False):
                #     if PoultryHatching.objects.filter(poultry=poultry,
                #                                       allow_hatching='pending', left_over__gt=0, state='pending',
                #                                       archive=False, trash=False).exists():
                #         poultry_list.append(poultry.key)
                poultry_list = self.queryset.filter(address__province=user.province, trash=False)

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

        elif 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user)
                if 'active_hatching' in request.GET:
                    poultry = []
                    poultry_ids = PoultryHatching.objects.filter(
                        allow_hatching='pending',
                        left_over__gt=0,
                        state='pending',
                        poultry__city_operator=city_operator.unit_name,
                        archive=False,
                        trash=False
                    ).select_related('poultry').only('poultry').values_list('poultry', flat=True).distinct()
                    poultry = Poultry.objects.filter(id__in=poultry_ids)
                    serializer = PoultryForPoultryHatchingForKillInformationSerializer(poultry, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    poultry = Poultry.objects.filter(city_operator=city_operator.unit_name)
            elif request.GET['role'] == 'Poultry':
                poultry = Poultry.objects.filter(user=user, trash=False)
            else:
                if 'active_hatching' in request.GET:
                    poultry_ids = PoultryHatching.objects.filter(
                        poultry__address__province=user.province,
                        allow_hatching='pending',
                        left_over__gt=0,
                        state='pending',
                        archive=False,
                        trash=False
                    ).select_related('poultry').only('poultry').values_list('poultry', flat=True).distinct()
                    age_range = ChickenAgeRange.objects.filter(trash=False).first()
                    if 'min_age' in request.GET or 'direct_buying' in request.GET:
                        if age_range.active:
                            poultry_ids = poultry_ids.filter(chicken_age__range=(age_range.minimum, age_range.maximum))
                        else:
                            if 'min_age' in request.GET:
                                min_age = int(request.GET['min_age'])
                                max_age = int(request.GET.get('max_age', min_age))  # برای اطمینان از وجود 'max_age'
                                poultry_ids = poultry_ids.filter(chicken_age__range=(min_age, max_age))
                            else:
                                poultry_ids = poultry_ids
                    poultry = Poultry.objects.filter(id__in=poultry_ids)
                    serializer = PoultryForPoultryHatchingForKillInformationSerializer(poultry, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    # poultry=PoultryHatching.objects.filter(trash=False,allow_hatching='pending',archive=False).values_list(
                    #     'poultry',flat=True
                    # ).distinct()
                    poultry = Poultry.objects.filter(trash=False, address__province=user.province).select_related(
                        'user', 'address'
                    ).order_by('id')

            serializer = PoultryForPoultryHatchingSerializer(poultry, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)


        elif 'info' in request.GET:
            list1 = []
            # list2 = []
            poultries = Poultry.objects.filter(user=user, trash=False)
            if poultries.count() > 0:
                for poultry in poultries:
                    halls = int(poultry.number_of_halls)
                    inspections_count = 0
                    hatching_state = None
                    hatching_date = None
                    for hall in range(halls):
                        hatching = PoultryHatching.objects.filter(poultry=poultry, hall=hall + 1).order_by('date')
                        if hatching.count() > 0:
                            hatching = hatching.last()
                            hatching_date = hatching.date
                            if hatching.state == 'pending':
                                hatching_state = 'active'
                            else:
                                hatching_state = 'inactive'

                        vet_farms = VetFarm.objects.filter(poultry=poultry, hall=hall + 1)
                        if vet_farms.count() > 0:
                            for vet_farm in vet_farms:
                                inspections = VetFarmInspection.objects.filter(vet_farm=vet_farm)
                                if inspections.count() > 0:
                                    inspections_count += inspections.count()
                        internal_dict = {
                            "poultry_name": poultry.unit_name,
                            "poultry_key": poultry.key,
                            "hall": hall + 1,
                            "hatching_state": hatching_state,
                            "hatching_date": hatching_date,
                            "inspections": inspections_count
                        }
                        list1.append(internal_dict)
                        inspections_count = 0

            return Response(list1, status=status.HTTP_200_OK)

        elif 'operator' in request.GET:
            if request.GET['operator'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user)
                poultry = Poultry.objects.filter(city_operator=city_operator.unit_name, trash=False)
                serializer = PoultrySerializer(poultry, many=True)
        #
        # elif 'id' in request.GET:
        #     poultry = Poultry.objects.get(breeding_unique_id=request.GET['id'])
        #     serializer = PoultrySerializer(poultry)
        elif 'all' in request.GET:
            poultry_list = []
            poultries = Poultry.objects.filter(address__province=user.province, trash=False)
            if poultries.count() > 0:
                for poultry in poultries:
                    allow_state = None
                    allow_sell_state = None
                    allow = ProvinceAllowPoultryChooseKillHouse.objects.filter(poultry=poultry, trash=False)
                    allow_sell = ProvinceAllowPoultrySellFree.objects.filter(poultry=poultry, trash=False)
                    if allow.count() > 0:
                        allow_state = allow.last().allow
                    if allow_sell.count() > 0:
                        allow_sell_state = allow_sell.last().allow
                    poultry_dict = {
                        "name": poultry.unit_name,
                        "key": poultry.key,
                        "allow_state": allow_state,
                        "allow_sell_state": allow_sell_state
                    }
                    poultry_list.append(poultry_dict)
            return Response(poultry_list, status=status.HTTP_200_OK)


        else:
            poultry = Poultry.objects.filter(user=user, trash=False)
            serializer = PoultrySerializer(poultry, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

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

        # get self - poultry profile information
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            user_serializer = SystemUserProfileSerializer(user)
            poultry = Poultry.objects.filter(user=user, trash=False)
            serializer = PoultrySerializer(poultry, many=True)
            profile_info = {
                'profile': user_serializer.data,
                'aviculture': serializer.data
            }
            return Response(profile_info, status=status.HTTP_200_OK)

        # get special poultry information
        if 'partial_key' in request.GET:
            poultry_object = Poultry.objects.get(key=request.GET['partial_key'], trash=False)
            serializer = PoultrySerializer(poultry_object)
            return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        # refresh(request.user.id)
        poultry = self.queryset.get(key=request.data['poultry_key'])
        poultry.trash = True
        poultry.save()
        return Response(status=status.HTTP_200_OK)


class ChainCompanyViewSet(viewsets.ModelViewSet):
    queryset = ChainCompany.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainCompanySerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainCompanyFilterSet
    filterset_fields = [
        'user__national_id',
        'user__mobile',
        'user__first_name',
        'user__last_name',
        'user__fullname',
        'name',

    ]

    def retrieve(self, request, pk=None, *args, **kwargs):
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)

            chain_company = user.chain_company_user.all()

            serializer = self.serializer_class(chain_company[0])
            return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        group = Group.objects.get(name__exact="ChainCompany")
        city = City.objects.get(province_center=True)
        province = Province.objects.get(trash=False)
        system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
        if system_profile:
            if ChainCompany.objects.filter(user=system_profile, trash=False).exists():
                return Response({"result": "این شرکت قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)

        else:
            password = "00100"
            data = {
                "username": request.data['mobile'],
                "password": password,
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_URL_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                user = User(username=request.data['mobile'], first_name=request.data['first_name'],
                            last_name=request.data['last_name'])
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                system_profile = SystemUserProfile(
                    mobile=request.data['mobile'],
                    first_name=request.data['first_name'],
                    last_name=request.data['last_name'],
                    fullname=request.data['first_name'] + " " + request.data['last_name'],
                    user=user,
                    base_order=base_id,
                    password=password,
                    national_id=request.data['national_id'],
                    city=city,
                    province=province
                )
                system_profile.save()
            else:
                return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)

        system_profile.role.add(group)
        wallet = Wallet()
        wallet.save()
        request.data.pop('mobile')
        request.data.pop('first_name')
        request.data.pop('last_name')
        request.data.pop('national_id')
        request.data.pop('postal_code')

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            chain_company = serializer.create(validated_data=request.data)
            chain_company.user = system_profile
            chain_company.wallet = wallet
            chain_company.save()
            return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def list(self, request, *args, **kwargs):

        company_list = []
        if 'state' in request.GET:
            chain_companies = ChainCompany.objects.filter(trash=False).order_by('id')
            if 'search' in request.GET:
                if request.GET['search'] == 'filter':
                    if request.GET['value'] != "" and request.GET['value'] != 'undefined':
                        for item in self.filterset_fields:
                            query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                            if (self.filterset_class(
                                    data=query,
                                    queryset=chain_companies
                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=chain_companies)
                                company_list = ps.filter()
                        chain_companies = [] if len(company_list) == 0 else company_list

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

            page = self.paginate_queryset(chain_companies)
            if page is not None:
                serializer = ChainCompanyForCompanyRequestSerializer(page, many=True)
                return self.get_paginated_response(serializer.data)
        else:
            chain_companies = ChainCompany.objects.filter(trash=False).order_by('id')
            serializer = self.serializer_class(chain_companies, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        company = ChainCompany.objects.get(key=request.data['company_key'], trash=False)
        system_user_profile = SystemUserProfile.objects.get(key=company.user.key, trash=False)
        system_user_profile.first_name = request.data['first_name']
        system_user_profile.last_name = request.data['last_name']
        system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
        system_user_profile.national_id = request.data['national_id']
        system_user_profile.save()
        first_mobile_number = system_user_profile.mobile
        second_mobile_number = request.data['mobile']
        request.data.pop('mobile')
        if first_mobile_number != second_mobile_number:
            if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
                return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                status=status.HTTP_403_FORBIDDEN)
            data = {
                "first_mobile_number": first_mobile_number,
                "second_mobile_number": second_mobile_number,
            }
            req = requests.post(
                url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                data=data,
                verify=False
            )
            if req.status_code == 200:
                second_mobile_number = second_mobile_number
                user = User.objects.get(id=system_user_profile.user.id)
                user.username = second_mobile_number
                user.save()
                system_user_profile.mobile = second_mobile_number
                system_user_profile.save()

        request.data.pop('company_key')
        request.data.pop('first_name')
        request.data.pop('last_name')
        request.data.pop('national_id')

        serializer = self.serializer_class(company)
        serializer.update(instance=company, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ChainCompanyForTotalWageAllocationViewSet(viewsets.ModelViewSet):
    queryset = ChainCompany.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainCompanyForTotalWageAllocationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainCompanyFilterSet
    filterset_fields = [
        'name',
        'user__fullname',
        'user__mobile',
        'address__city__name',
        'address__province__name',

    ]

    def list(self, request, *args, **kwargs):

        if 'date1' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if request.GET['role'] == 'ProvinceOperator':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    union_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Company':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Company':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Guilds':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    guilds_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            else:
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
        else:

            if request.GET['role'] == 'ProvinceOperator':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    union_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Company':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Company':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Guilds':
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    guilds_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)
            else:
                chain_companies = ChainCompany.objects.filter(pk__in=ChainAllocation.objects.filter(
                    archive_wage=False,
                    trash=False).values(
                    'chain_company'), trash=False)

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

        page = self.paginate_queryset(chain_companies)
        if page is not None:
            if 'date1' in request.GET:
                serializer = ChainCompanyForTotalWageAllocationWithDAteSerializer(page, many=True,
                                                                                  context={'request': request})
            else:

                serializer = self.get_serializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)

        if 'date1' in request.GET:
            serializer = ChainCompanyForTotalWageAllocationWithDAteSerializer(chain_companies, many=True,
                                                                              context={'request': request})
        else:

            serializer = self.get_serializer(chain_companies, many=True, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)


class ChainCompanyForTotalWageTransactionViewSet(viewsets.ModelViewSet):
    queryset = ChainCompany.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainCompanyForTotalWageTransactionSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainCompanyFilterSet
    filterset_fields = [
        'name',
        'user__fullname',
        'user__mobile',
        'address__city__name',
        'address__province__name',

    ]

    def list(self, request, *args, **kwargs):

        if 'date1' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if request.GET['role'] == 'ProvinceOperator':
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='chain_company',
                    union_share__gt=0,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Company':
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='chain_company',
                    company_share__gt=0,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Guilds':
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='chain_company',
                    guilds_share__gt=0,
                    trash=False).values(
                    'chain_company'), trash=False)
            else:
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='chain_company',
                    trash=False).values(
                    'chain_company'), trash=False)
        else:

            if request.GET['role'] == 'ProvinceOperator':
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='chain_company',
                    union_share__gt=0,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Company':
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='chain_company',
                    company_share__gt=0,
                    trash=False).values(
                    'chain_company'), trash=False)
            elif request.GET['role'] == 'Guilds':
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='chain_company',
                    guilds_share__gt=0,
                    trash=False).values(
                    'chain_company'), trash=False)
            else:
                chain_companies = ChainCompany.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='chain_company',
                    trash=False).values(
                    'chain_company'), trash=False)

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

        page = self.paginate_queryset(chain_companies)
        if page is not None:
            if 'date1' in request.GET:
                serializer = ChainCompanyForTotalWageTransactionTransactionWithDAteSerializer(page, many=True, context={
                    'request': request})
            else:

                serializer = self.get_serializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)

        if 'date1' in request.GET:
            serializer = ChainCompanyForTotalWageTransactionTransactionWithDAteSerializer(chain_companies, many=True,
                                                                                          context={'request': request})
        else:

            serializer = self.get_serializer(chain_companies, many=True, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)


class ChainCompanyTransactionViewSet(viewsets.ModelViewSet):
    queryset = ChainCompanyTransaction.objects.all()
    serializer_class = ChainCompanyTransactionSerializer
    permission_classes = [TokenHasReadWriteScope]


class PoultryChooseChainCompanyViewSet(viewsets.ModelViewSet):
    queryset = ChainCompany.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainCompanySerializer

    def create(self, request, *args, **kwargs):
        poultry_hitchings = request.data['poultry_hitchings']
        chain_company = ChainCompany.objects.get(key=request.data['chain_company'], trash=False)
        hatchings = PoultryHatching.objects.filter(key__in=poultry_hitchings, trash=False)
        for hatching in hatchings:
            hatching.chain_company = chain_company
            hatching.has_chain_company = True
            hatching.save()

        return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)

    def update(self, request, pk=None, *args, **kwargs):
        hatching = PoultryHatching.objects.get(key=request.data['hatching_key'], trash=False)

        if 'type' in request.data.keys():
            if request.data['type'] == 'delete':
                hatching.chain_company = None
                hatching.has_chain_company = False
                hatching.save()
            else:
                company = ChainCompany.objects.get(key=request.data['company_key'], trash=False)
                hatching.chain_company = company
                hatching.has_chain_company = True
                hatching.save()

        return Response({"result": "با موفقیت ثبت شد!"}, status=status.HTTP_200_OK)


class ChainAllocationForWageViewSet(viewsets.ModelViewSet):
    queryset = ChainAllocation.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainAllocationForWageSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainAllocationFilterSet
    filterset_fields = [
        'poultry_hatching__poultry__breeding_unique_id',
        'poultry_hatching__poultry__user__mobile',
        'poultry_hatching__poultry__user__fullname',
        'poultry_hatching__poultry__user__first_name',
        'poultry_hatching__poultry__user__last_name',
        'poultry_hatching__poultry__unit_name',
        'chain_company__name',

    ]

    def list(self, request, *args, **kwargs):
        chain_allocations_list = []
        if request.GET['role'] == 'ChainCompany':
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            chain_company = ChainCompany.objects.get(user=user, trash=False)
        else:

            chain_company = ChainCompany.objects.get(key=request.GET['chain_company_key'], trash=False)

        if 'date1' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if request.GET['role'] == 'ProvinceOperator':
                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   union_share__gt=0,
                                                                   trash=False).order_by('id')
            elif request.GET['role'] == 'Company':
                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   company_share__gt=0,
                                                                   trash=False).order_by('id')
            elif request.GET['role'] == 'Guilds':
                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   guilds_share__gt=0,
                                                                   trash=False).order_by('id')
            else:

                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   trash=False).order_by('id')
        else:

            if request.GET['role'] == 'ProvinceOperator':
                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company,
                                                                   union_share__gt=0,
                                                                   trash=False).order_by('id')
            elif request.GET['role'] == 'Company':
                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company,
                                                                   company_share__gt=0,
                                                                   trash=False).order_by('id')
            elif request.GET['role'] == 'Guilds':
                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company,
                                                                   guilds_share__gt=0,
                                                                   trash=False).order_by('id')
            else:

                chain_allocations = ChainAllocation.objects.filter(chain_company=chain_company,
                                                                   trash=False).order_by('id')

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

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

        page = self.paginate_queryset(chain_allocations)
        if page is not None:
            serializer = self.serializer_class(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)

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


class ChainAllocationViewSet(viewsets.ModelViewSet):
    queryset = ChainAllocation.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainAllocationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainAllocationFilterSet
    filterset_fields = [
        'poultry_hatching__poultry__breeding_unique_id',
        'poultry_hatching__poultry__user__mobile',
        'poultry_hatching__poultry__user__fullname',
        'poultry_hatching__poultry__user__first_name',
        'poultry_hatching__poultry__user__last_name',
        'poultry_hatching__poultry__unit_name',
        'chain_company__name',

    ]

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        if base_url_for_sms_report == 'ma':
            return Response({
                'result': "امکان ثبت بار برای زنجیره وجود ندارد جهت فروش زنجیره به قسمت فروش خارج استان مراجعه فرمایید"},
                status=status.HTTP_403_FORBIDDEN)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = None
        hatching = PoultryHatching.objects.get(key=request.data['hatching_key'], trash=False)
        chain_company = ChainCompany.objects.get(key=hatching.chain_company.key, trash=False)
        role = request.data['role']
        request.data.pop('hatching_key')
        request.data.pop('role')
        now = datetime.datetime.now()
        if 'kill_house_key' in request.data.keys():
            kill_house = KillHouse.objects.get(key=request.data['kill_house_key'])
            request.data.pop('kill_house_key')
        input_date = datetime.datetime.strptime(request.data['date'], '%Y-%m-%d').date()
        date = datetime.datetime(year=input_date.year, month=input_date.month, day=input_date.day, hour=now.hour,
                                 minute=now.minute,
                                 second=now.second)
        request.data.pop('date')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            chain_allocation = serializer.create(validated_data=request.data)
            chain_allocation.poultry_hatching = hatching
            chain_allocation.chain_company = chain_company
            chain_allocation.date = date
            chain_allocation.company_name = chain_company.name
            chain_allocation.company_user_fullname = chain_company.user.fullname
            chain_allocation.company_user_mobile = chain_company.user.mobile
            chain_allocation.company_user_province = chain_company.user.province.name
            chain_allocation.company_user_city = chain_company.user.city.name
            chain_allocation.registerer = {
                "role": role,
                "fullname": user.fullname,
                "mobile": user.mobile,
                "date": str(datetime.datetime.now()),
            }
            if kill_house != None:
                chain_allocation.kill_house = kill_house
            chain_allocation.save()
            # update_chain_hatching(hatching)
            wage = 0
            wage_type = WageType.objects.filter(en_name='chain', trash=False).first()
            if wage_type.status == True:
                wage = wage_type.amount
            chain_allocation.wage = wage
            chain_allocation.total_wage_amount = wage * int(chain_allocation.weight)
            chain_allocation.save()

            percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0, trash=False)

            if wage_type and wage_type.status == True and percentages_wage_type:
                for percentage_wage_type in percentages_wage_type:
                    if percentage_wage_type.share_type.en_name == 'union':
                        chain_allocation.union_share = int(
                            (percentage_wage_type.percent / 100) * chain_allocation.total_wage_amount)
                        chain_allocation.union_share_percent = percentage_wage_type.percent
                        chain_allocation.save()
                    elif percentage_wage_type.share_type.en_name == 'company':
                        chain_allocation.company_share = int(
                            (percentage_wage_type.percent / 100) * chain_allocation.total_wage_amount)
                        chain_allocation.company_share_percent = percentage_wage_type.percent
                        chain_allocation.save()

                    elif percentage_wage_type.share_type.en_name == 'guilds':
                        chain_allocation.guilds_share = int(
                            (percentage_wage_type.percent / 100) * chain_allocation.total_wage_amount)
                        chain_allocation.guilds_share_percent = percentage_wage_type.percent
                        chain_allocation.save()
                    elif percentage_wage_type.share_type.en_name == 'city':
                        chain_allocation.city_share = int(
                            (percentage_wage_type.percent / 100) * chain_allocation.total_wage_amount)
                        chain_allocation.city_share_percent = percentage_wage_type.percent
                        chain_allocation.save()

                    elif percentage_wage_type.share_type.en_name == 'wallet':
                        chain_allocation.wallet_share = int(
                            (percentage_wage_type.percent / 100) * chain_allocation.total_wage_amount)
                        chain_allocation.wallet_share_percent = percentage_wage_type.percent
                        chain_allocation.save()

                    else:
                        chain_allocation.other_share = int(
                            (percentage_wage_type.percent / 100) * chain_allocation.total_wage_amount)
                        chain_allocation.other_share_percent = percentage_wage_type.percent
                        chain_allocation.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        chain_allocations_list = []

        if request.GET['role'] == "ChainCompany":
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(chain_company__user=user, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True), temporary_trash=False,
                                                                   temporary_deleted=False).order_by('-id')
            else:
                chain_allocations = ChainAllocation.objects.filter(chain_company__user=user, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   state__in=('accepted', 'pending'),
                                                                   trash=False).order_by('-id')
        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(poultry_hatching__poultry__address__city=user.city,
                                                                   date__date__gte=date1, date__date__lte=date2,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True), temporary_trash=False,
                                                                   temporary_deleted=False).order_by('-id')
            else:

                chain_allocations = ChainAllocation.objects.filter(poultry_hatching__poultry__address__city=user.city,
                                                                   date__date__gte=date1, date__date__lte=date2,
                                                                   state='accepted',
                                                                   trash=False).order_by('-id')
        elif request.GET['role'] == "CityOperator":
            city_operator = CityOperator.objects.get(user=user, trash=False)
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(
                    poultry_hatching__poultry__city_operator=city_operator.unit_name, date__date__gte=date1,
                    date__date__lte=date2,
                    state__in=('rejected', 'deleted'),
                    trash__in=(False, True), temporary_trash=False, temporary_deleted=False).order_by('-id')
            else:
                chain_allocations = ChainAllocation.objects.filter(
                    poultry_hatching__poultry__city_operator=city_operator.unit_name, date__date__gte=date1,
                    date__date__lte=date2,
                    state__in=('accepted', 'pending'),
                    trash=False).order_by('-id')

        elif request.GET['role'] == "VetFarm":
            vet = Vet.objects.get(user=user, trash=False)
            poultry_ids = VetFarm.objects.filter(vet=vet, trash=False).select_related('poultry').only(
                'poultry').values_list('poultry', flat=True).distinct()
            poultry = Poultry.objects.filter(id__in=poultry_ids)
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   poultry_hatching__poultry__in=poultry,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True), temporary_trash=False,
                                                                   temporary_deleted=False).order_by('-id')
            else:

                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   poultry_hatching__poultry__in=poultry,
                                                                   state='accepted',
                                                                   trash=False).order_by('-id')
        else:
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True), temporary_trash=False,
                                                                   temporary_deleted=False).order_by('-id')
            else:
                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   state__in=('accepted', 'pending'),
                                                                   trash=False).order_by('-id')

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

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

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

        serializer = self.serializer_class(chain_allocations, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        chain_allocation = ChainAllocation.objects.get(key=request.data['chain_allcation_key'], trash=False)
        request.data.pop('chain_allcation_key')
        if 'check_allocation' in request.data.keys():
            chain_allocation.seconder = {
                "role": None,
                "fullname": user.fullname,
                "mobile": user.mobile,
                "date": str(datetime.datetime.now()),
            }
            chain_allocation.save()
            request.data.pop('check_allocation')
            if request.data['state'] == 'accepted':
                poultry_name = chain_allocation.poultry_hatching.poultry.unit_name
                poultry_mobile = chain_allocation.poultry_hatching.poultry.user.mobile
                quantity = chain_allocation.quantity
                Index_weight = chain_allocation.index_weight
                if chain_allocation.kill_house is not None:
                    kill_house_name = chain_allocation.kill_house.name
                    kill_house_mobile = chain_allocation.kill_house.kill_house_operator.user.mobile

                else:
                    kill_house_name = chain_allocation.buyer_name
                    kill_house_mobile = chain_allocation.buyer_mobile
                city = chain_allocation.poultry_hatching.poultry.user.city.name
                province = chain_allocation.poultry_hatching.poultry.user.province.name
                date_str = str(
                    chain_allocation.date)
                send_date = datetime.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)
                vet_farm = VetFarm.objects.filter(
                    poultry=chain_allocation.poultry_hatching.poultry).first()
                sms_chain_company_for_ver_farm(poultry_name, poultry_mobile,
                                               quantity, Index_weight, kill_house_name, kill_house_mobile, city,
                                               send_date,
                                               vet_farm.vet.user.mobile, province)

        if 'quarantine_code' in request.data.keys():
            chain_allocation.quarantine_code_registrar = {
                "fullname": user.fullname,
                "mobile": user.mobile,
                "date": str(datetime.datetime.now()),
            }
            chain_allocation.save()
        if 'kill_house_key' in request.data.keys() and request.data['kill_house_key'] is not None:
            kill_house = KillHouse.objects.get(key=request.data['kill_house_key'])
            chain_allocation.kill_house = kill_house
            chain_allocation.save()
            request.data.pop('kill_house_key')

        serializer = self.serializer_class(chain_allocation)
        serializer.update(instance=chain_allocation, validated_data=request.data)
        if chain_allocation.state == 'accepted':
            update_chain_hatching(chain_allocation.poultry_hatching)
        chain_allocation.total_wage_amount = chain_allocation.wage * int(chain_allocation.weight)
        chain_allocation.save()

        union_percent = chain_allocation.union_share_percent / 100 if chain_allocation.union_share_percent > 0 else 0
        company_percent = chain_allocation.company_share_percent / 100 if chain_allocation.company_share_percent > 0 else 0
        guilds_percent = chain_allocation.guilds_share_percent / 100 if chain_allocation.guilds_share_percent > 0 else 0
        city_share_percent = chain_allocation.city_share_percent / 100 if chain_allocation.city_share_percent > 0 else 0
        wallet_share_percent = chain_allocation.wallet_share_percent / 100 if chain_allocation.wallet_share_percent > 0 else 0
        other_share_percent = chain_allocation.other_share_percent / 100 if chain_allocation.other_share_percent > 0 else 0
        chain_allocation.union_share = int(union_percent * chain_allocation.total_wage_amount)
        chain_allocation.company_share = int(company_percent * chain_allocation.total_wage_amount)
        chain_allocation.guilds_share = int(guilds_percent * chain_allocation.total_wage_amount)
        chain_allocation.city_share = int(city_share_percent * chain_allocation.total_wage_amount)
        chain_allocation.wallet_share = int(wallet_share_percent * chain_allocation.total_wage_amount)
        chain_allocation.other_share = int(other_share_percent * chain_allocation.total_wage_amount)
        chain_allocation.save()

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

    def destroy(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET['role']
        chain_allocation = ChainAllocation.objects.get(key=request.GET['chain_allcation_key'], trash=False)
        if chain_allocation.quarantine_code is None == False:
            return Response({"result": "به علت ورود کد قرنطینه امکان حذف وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)
        chain_allocation.trash = True
        chain_allocation.state = 'deleted'
        chain_allocation.remover = {
            "role": role,
            "fullname": user.fullname,
            "mobile": user.mobile,
            "date": str(datetime.datetime.now()),
        }
        chain_allocation.save()
        update_chain_hatching(chain_allocation.poultry_hatching)
        return Response(status=status.HTTP_200_OK)


class ParentCompanyChainAllocationViewSet(viewsets.ModelViewSet):
    queryset = ChainAllocation.objects.all()
    permission_classes = [AllowAny]
    serializer_class = ChainAllocationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainAllocationFilterSet
    filterset_fields = [
        'poultry_hatching__poultry__breeding_unique_id',
        'poultry_hatching__poultry__user__mobile',
        'poultry_hatching__poultry__user__fullname',
        'poultry_hatching__poultry__user__first_name',
        'poultry_hatching__poultry__user__last_name',
        'poultry_hatching__poultry__unit_name',
        'chain_company__name',

    ]

    def list(self, request, *args, **kwargs):
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        chain_allocations_list = []

        if 'state' in request.GET:
            chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                               state__in=('rejected', 'deleted'),
                                                               trash__in=(False, True)).order_by('-id')
        else:
            chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                               state__in=('accepted', 'pending'),
                                                               trash=False).order_by('-id')

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

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

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

        serializer = self.serializer_class(chain_allocations, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ForecastPoultryHatchingViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):

        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        age = int(request.GET['age'])
        days_interval = (date2 - date1).days
        hatching_list = []
        hatches = PoultryHatching.objects.filter(state='pending',
                                                 allow_hatching='pending', archive=False,
                                                 trash=False)

        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                hatchings = hatches.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                hatchings = hatches.filter(poultry__address__city=user.city)
            else:
                hatchings = hatches
        else:
            hatchings = hatches

        if hatchings:
            for i in range(days_interval + 1):
                hatching_left_over = 0
                first_date = date1 + timedelta(days=i)
                for hatch in hatchings:
                    if (first_date - hatch.date.date()).days + 1 == age:
                        hatching_left_over += hatch.left_over
                hatching_list.append({"date": first_date, "hatching_left_over": hatching_left_over})
                if days_interval == 0:
                    break

        return Response(hatching_list, status=status.HTTP_200_OK)


class PoultryHatchingForDashBoardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingSerializer
    filterset_class = PoultryHatchingFilterSet
    filterset_fields = [
        'poultry__user__first_name',
        'poultry__user__last_name',
        'poultry__user__fullname',
        'poultry__user__mobile',
        'poultry__unit_name',
        'poultry__address__city__name',
        'chicken_age',
        'licence_number',
        'poultry__breeding_unique_id',
        'CertId',
        'PersonTypeName',
        'InteractTypeName',
        'UnionTypeName',
        'poultry__city_operator',

    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        hatching_filters = {
            'trash': False
        }
        if request.GET['type'] == 'date-dashboard':
            date1 = datetime.datetime.strptime(request.GET['date1'], '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(request.GET['date2'], '%Y-%m-%d').date()
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                poultry_hatchings = PoultryHatching.objects.filter(trash=False, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   # allow_hatching='pending',
                                                                   # state='pending',
                                                                   # archive=False,
                                                                   poultry__city_operator=city_operator.unit_name,
                                                                   )
            elif request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                poultry_hatchings = PoultryHatching.objects.filter(trash=False, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   # allow_hatching='pending',
                                                                   # state='pending',
                                                                   # archive=False,
                                                                   poultry__address__city=user.city,
                                                                   )
            else:
                poultry_hatchings = PoultryHatching.objects.filter(trash=False, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   # allow_hatching='pending',
                                                                   # state='pending',
                                                                   # archive=False
                                                                   )
            if 'search' in request.GET:
                value = request.GET.get('value')
                if request.GET['search'] == 'filter':
                    if value != 'undefined' and value.strip():
                        poultry_hatchings = poultry_hatchings.filter(
                            build_query(self.filterset_class, value)
                        )
            poultries = Poultry.objects.filter(pk__in=poultry_hatchings.values('poultry'), trash=False)
            total_hatching_quantity = poultry_hatchings.aggregate(total=Sum('quantity'))['total'] or 0
            total_hatching_left_over_quantity = poultry_hatchings.aggregate(total=Sum('left_over'))['total'] or 0
            total_hatching_killed_quantity = poultry_hatchings.aggregate(total=Sum('killed_quantity'))['total'] or 0
            total_hatching_killed_weight = poultry_hatchings.aggregate(total=Sum('total_killed_weight'))['total'] or 0
            all_vet_losses = poultry_hatchings.aggregate(total_quantity=Sum('losses')).get(
                'total_quantity') or 0
            all_union_losses = poultry_hatchings.aggregate(total_quantity=Sum('direct_losses')).get(
                'total_quantity') or 0
            all_total_losses = poultry_hatchings.aggregate(total_quantity=Sum('total_losses')).get(
                'total_quantity') or 0
            return Response({
                "poultries": len(poultries),
                "total_hatching_quantity": total_hatching_quantity,
                "total_hatching_left_over_quantity": total_hatching_left_over_quantity,
                "total_hatching_killed_quantity": total_hatching_killed_quantity,
                "total_hatching_killed_weight": total_hatching_killed_weight,
                "total_hatching_vet_losses": all_vet_losses,
                "total_hatching_union_losses": all_union_losses,
                "total_hatching_all_losses": all_total_losses,
            })
        else:
            tab = request.GET.get('tab')
            age1 = request.GET.get('age1')
            age2 = request.GET.get('age2')
            date1 = request.GET.get('date1')
            date2 = request.GET.get('date2')
            role = request.GET.get('role')
            if tab == 'unknown':
                hatching_filters['unknown'] = True
            elif tab == 'archive':
                hatching_filters['unknown'] = False
            elif tab == 'active':
                hatching_filters['unknown'] = False
                hatching_filters['allow_hatching'] = 'pending'
                hatching_filters['state'] = 'pending'
                hatching_filters['archive'] = False
            else:
                hatching_filters['unknown'] = False

            if age1 and age2:
                if int(age2) > 0:
                    hatching_filters['chicken_age__gte'] = int(age1)
                    hatching_filters['chicken_age__lte'] = int(age2)

            if date1:
                hatching_filters['date__date__gte'] = date1
                hatching_filters['date__date__lte'] = date2

            if role == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                hatching_filters['poultry__city_operator'] = city_operator.unit_name



            elif role in ['CityJahad', 'CityPoultry', 'CityVet']:
                hatching_filters['poultry__address__city'] = user.city

            poultry_hatchings = PoultryHatching.objects.filter(**hatching_filters).order_by('date')

            if tab == 'archive':
                poultry_hatchings = poultry_hatchings.filter(
                    Q(allow_hatching='True', state='complete') | Q(archive=True))

            if 'search' in request.GET:
                value = request.GET.get('value')
                if request.GET['search'] == 'filter':
                    if value != 'undefined' and value.strip():
                        poultry_hatchings = poultry_hatchings.filter(
                            build_query(self.filterset_class, value)
                        )

            total_hatching_quantity = poultry_hatchings.aggregate(total=Sum('quantity'))['total'] or 0
            total_hatching_left_over_quantity = poultry_hatchings.aggregate(total=Sum('left_over'))['total'] or 0
            total_hatching_killed_quantity = poultry_hatchings.aggregate(total=Sum('killed_quantity'))['total'] or 0
            total_hatching_killed_weight = poultry_hatchings.aggregate(total=Sum('total_killed_weight'))['total'] or 0
            all_vet_losses = poultry_hatchings.aggregate(total_quantity=Sum('losses')).get(
                'total_quantity') or 0
            all_union_losses = poultry_hatchings.aggregate(total_quantity=Sum('direct_losses')).get(
                'total_quantity') or 0
            all_total_losses = poultry_hatchings.aggregate(total_quantity=Sum('total_losses')).get(
                'total_quantity') or 0
            now = timezone.now().date()
            age_distribution = {"age-20-30": 0, "age-30-40": 0, "age-40-50": 0, "age-50-60": 0, "age-more-than-60": 0}

            for poultry_hatching in poultry_hatchings:
                age = (now - poultry_hatching.date.date()).days + 1
                if 20 <= age <= 30:
                    age_distribution["age-20-30"] += poultry_hatching.left_over
                elif age <= 40:
                    age_distribution["age-30-40"] += poultry_hatching.left_over
                elif age <= 50:
                    age_distribution["age-40-50"] += poultry_hatching.left_over
                elif age <= 60:
                    age_distribution["age-50-60"] += poultry_hatching.left_over
                else:
                    age_distribution["age-more-than-60"] += poultry_hatching.left_over

            return Response({
                "poultries": poultry_hatchings.values('poultry').distinct().count(),
                "hatchings": poultry_hatchings.count(),
                "total_hatching_quantity": total_hatching_quantity,
                "total_hatching_left_over_quantity": total_hatching_left_over_quantity,
                **age_distribution,
                "total_hatching_killed_quantity": total_hatching_killed_quantity,
                "total_hatching_killed_weight": total_hatching_killed_weight,
                "total_hatching_vet_losses": all_vet_losses,
                "total_hatching_union_losses": all_union_losses,
                "total_hatching_all_losses": all_total_losses,
            })


# ویوست مربوط به ثبت و نمایش و ... جوجه ریزی مرغدار
class PoultryHatchingViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingSerializer
    pagination_class = CustomPagination
    filterset_class = PoultryHatchingFilterSet
    filterset_fields = [
        'poultry__user__first_name',
        'poultry__user__last_name',
        'poultry__user__fullname',
        'poultry__user__mobile',
        'poultry__unit_name',
        'poultry__address__city__name',
        'chicken_age',
        'licence_number',
        'poultry__breeding_unique_id',
        'CertId',
        'PersonTypeName',
        'InteractTypeName',
        'UnionTypeName',
        'poultry__city_operator',

    ]

    def generate_random_filename(self, extension="jpg", length=15):
        """Generates a random filename with the given extension."""
        random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
        return f"{random_str}.{extension}"

    def process_violation_images(self, images):
        """Uploads images to Arvan Cloud and returns the URLs."""
        violation_images = []
        for image in images:
            file_url = upload_to_liara(image, image.name)
            violation_images.append(file_url)
        return violation_images

    # تابع مربوط به ثبت جوجه ریزی مرغدار
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        if 'role' in request.data.keys():
            role = request.data['role']
            request.data.pop('role')
        else:
            role = None
        poultry = Poultry.objects.get(key=request.data["key"], trash=False)
        request.data.pop("key")
        if role == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user, trash=False)
            if city_operator.unit_name != poultry.city_operator:
                return Response({"result": "مرغدار زیر مجموعه تعاونی دیگری دیگری است !"},
                                status=status.HTTP_403_FORBIDDEN)
        hatching = PoultryHatching.objects.filter(poultry=poultry, trash=False)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            if PoultryHatching.objects.filter(poultry=poultry, hall=int(request.data['hall']),
                                              state__in=('pending', 'complete'), allow_hatching='pending',
                                              archive=False,
                                              trash=False).exists():
                return Response({"result": "برای شما دوره فعال جوجه ریزی وجود دارد !"},
                                status=status.HTTP_403_FORBIDDEN)
            hatch = PoultryHatching.objects.filter(poultry=poultry, hall=int(request.data['hall']),
                                                   state__in=('pending', 'complete'), allow_hatching='pending',
                                                   archive=False,
                                                   trash=False)
            if hatch.count() > 0:
                hatch = hatch.last()
                hatch.quantity += int(request.data['quantity'])
                # hatch.left_over += int(request.data['quantity'])
                hatch.state = 'pending'
                counter = 1
                for chicken_breed in hatch.breed:
                    if request.data['chicken_breed'] == chicken_breed['breed']:
                        chicken_breed['main_quantity'] += int(request.data['quantity'])
                        chicken_breed['remain_quantity'] += int(request.data['quantity'])
                        break
                    counter += 1
                if counter == 1:
                    pass
                else:
                    hatch.breed.append({
                        'breed': request.data['chicken_breed'],
                        'main_quantity': int(request.data['quantity']),
                        'remain_quantity': int(request.data['quantity'])
                    })

                if hatch.chicken_breed == request.data['chicken_breed']:
                    pass
                else:
                    hatch.chicken_breed = hatch.chicken_breed + " " + "-" + " " + request.data[
                        'chicken_breed']

                hatch.save()
                if SmsLicense.objects.filter(hatching=True).exists():
                    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()

                    poultry_fullname = hatch.poultry.unit_name
                    quantity = hatch.quantity
                    chicken_breed = hatch.chicken_breed
                    date_str = str(hatch.date)
                    date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                    date = jdatetime.datetime.fromgregorian(year=date.year, month=date.month,
                                                            day=date.day).strftime(
                        '%Y-%m-%d')
                    date_list = reversed(date.split('-'))
                    separate = "-"
                    date = separate.join(date_list)

                    province = hatch.poultry.user.province.name
                    city = hatch.poultry.user.city.name
                    province_operator_mobile = province_operator.user.mobile

                    operator_hatching_sms(province_operator_mobile, poultry_fullname, quantity, date, chicken_breed,
                                          province, city)
                    free_sale = FreeSaleWithinprovince.objects.filter(trash=False, allow=True).first()
                    if free_sale:
                        if free_sale.type == 'weight':
                            hatch.total_commitment = hatch.quantity * free_sale.weight
                        else:
                            hatch.total_commitment_quantity = int(hatch.quantity * (free_sale.percent / 100))

                        hatch.save()
                serializer = self.serializer_class(hatch)
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            if int(request.data['quantity']) == 0:
                return Response({"result": "you enter zero"}, status=status.HTTP_403_FORBIDDEN)
            breed_list = []
            poultry_hatching = serializer.create(validated_data=request.data)
            poultry_hatching.poultry = poultry
            if hatching.count() > 0:
                poultry_hatching.period = hatching.last().period + 1
            else:
                poultry_hatching.period = 1
            if role != None:
                poultry_hatching.registrar = {
                    "role": role,
                    "fullname": user.fullname,
                    "date": str(poultry_hatching.create_date)
                }

            # poultry_hatching.left_over = poultry_hatching.quantity
            breed_list.append({
                'breed': request.data['chicken_breed'],
                'main_quantity': int(request.data['quantity']),
                'remain_quantity': int(request.data['quantity'])
            })
            poultry_hatching.breed = breed_list
            poultry_hatching.latest_hatching_change = {
                "role": role,
                "date": str(datetime.datetime.now().date()),
                "full_name": user.fullname
            }
            poultry_hatching.save()
            free_sale = FreeSaleWithinprovince.objects.filter(trash=False, allow=True).first()
            if free_sale:
                if free_sale.type == 'weight':
                    poultry_hatching.total_commitment = poultry_hatching.quantity * free_sale.weight
                else:
                    poultry_hatching.total_commitment_quantity = int(
                        poultry_hatching.quantity * (free_sale.percent / 100))

                poultry_hatching.save()

            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()

            poultry_mobile = poultry_hatching.poultry.user.mobile
            poultry_fullname = poultry_hatching.poultry.unit_name
            quantity = poultry_hatching.quantity
            chicken_breed = poultry_hatching.chicken_breed
            date_str = poultry_hatching.date
            date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
            date = jdatetime.datetime.fromgregorian(year=date.year, month=date.month, day=date.day).strftime(
                '%Y-%m-%d')
            date_list = reversed(date.split('-'))
            separate = "-"
            date = separate.join(date_list)
            if SmsLicense.objects.filter(hatching=True).exists():
                province = poultry_hatching.poultry.user.province.name
                city = poultry_hatching.poultry.user.city.name
                base_order = poultry_hatching.poultry.user.base_order
                province_operator_mobile = province_operator.user.mobile
                province_operator_name = province_operator.user.fullname
                # hatching_sms(poultry_mobile, poultry_fullname, quantity, chicken_breed, date, province, city, base_order)
                operator_hatching_sms(province_operator_mobile, poultry_fullname, quantity, date, chicken_breed,
                                      province, city)

            serializer = self.serializer_class(poultry_hatching)
            return Response(serializer.data, status=status.HTTP_201_CREATED)

    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        hatching = PoultryHatching.objects.get(key=request.data["key"], trash=False)
        request.data.pop('key')
        if 'violation_check' in request.data.keys():
            if hatching.violation_reporter is not None:
                hatching.violation_report_editor = user.fullname
                hatching.violation_report_edit_date = datetime.datetime.now()
            else:
                hatching.violation_reporter = user.fullname
                hatching.violation_report_date = datetime.datetime.now()
            if request.FILES.get('violation_image_0'):
                violation_files = [
                    f for i in range(5)
                    if (f := request.FILES.get(f'violation_image_{i}'))
                ]
                images = hatching.violation_image
                if images:
                    for image in images:
                        delete_file_from_liara(image.split('/')[-1])
                violation_images = self.process_violation_images(violation_files)
                hatching.violation_image = violation_images
            if request.data['archive'] == True:
                hatching.allow_hatching = 'True'
                hatching.state = 'complete'
                hatching.archive_date = datetime.datetime.now()
                hatching.archive = True
                if hatching.first_date_input_archive is None:
                    hatching.first_date_input_archive = datetime.datetime.now()
                else:
                    hatching.second_date_input_archive = datetime.datetime.now()
                hatching.input_archiver = user.fullname
            hatching.save()
            request.data.pop('violation_check')
            request.data.pop('archive')
        if 'unknown' in request.data.keys():
            hatching.poultry.order_limit = False
            hatching.poultry.save()
        if 'archive_state' in request.data.keys():
            if hatching.left_over > (hatching.quantity * 10):
                return Response({'result': 'به دلیل مانده بیش از ده درصد امکان بایگانی کردن این جوجه ریزی را ندارید!'},
                                status=status.HTTP_403_FORBIDDEN)
            role = request.data['role']
            request.data.pop('role')
            request.data.pop('archive_state')
            hatching.allow_hatching = True
            if hatching.unknown:
                hatching.unknown = False
                hatching.poultry.order_limit = False
                hatching.poultry.save()
            hatching.state = 'complete'
            hatching.archive_date = datetime.datetime.now()
            hatching.archive = True
            if hatching.first_date_input_archive is None:
                hatching.first_date_input_archive = datetime.datetime.now()
            else:
                hatching.second_date_input_archive = datetime.datetime.now()
            if hatching.left_over > (hatching.quantity * percent_of_losses):
                hatching.violation = True
            hatching.input_archiver = user.fullname
            hatching.last_change = {
                "date": str(datetime.datetime.now()),
                "full_name": user.fullname,
                "role": role,
                "type": "manual_archive"
            }
            hatching.save()

        if 'quantity' in request.data.keys() and request.data['quantity'] != None:
            quantity = int(request.data['quantity'])
            # poultry_requests_quantity = \
            #     PoultryRequest.objects.filter(hatching=hatching, state_process__in=('pending', 'accepted'),
            #                                   province_state__in=('pending', 'accepted'), final_state='pending',
            #                                   trash=False).aggregate(
            #         total_quantity=Sum('quantity'))[
            #         'total_quantity'] or 0
            if quantity < hatching.killed_quantity:
                # if int(request.data['quantity']) < hatching.left_over:
                return Response({"result": "تعداد وارد شده کمتر از تعداد کشتار شده قبلی است."})
            else:
                role = request.data['role']
                request.data.pop('role')
                # if quantity > hatching.quantity:
                # hatching.left_over += quantity - hatching.quantity
                # elif quantity < hatching.quantity and hatching.left_over != 0:
                #     hatching.left_over -= hatching.quantity - quantity
                hatching.quantity = quantity
                hatching.allow_hatching = 'pending'
                hatching.state = 'pending'
                # hatching.output_archive_date = datetime.datetime.now()
                # hatching.output_archiver = user.fullname
                hatching.last_change = {
                    "date": str(datetime.datetime.now()),
                    "full_name": user.fullname,
                    "role": role,
                    "type": "change_hatching"
                }
                hatching.save()
                free_sale = FreeSaleWithinprovince.objects.filter(trash=False, allow=True).first()
                if free_sale:
                    if free_sale.type == 'weight':
                        hatching.total_commitment = hatching.quantity * free_sale.weight
                    else:
                        hatching.total_commitment_quantity = int(hatching.quantity * (free_sale.percent / 100))

                    hatching.save()
        if 'type' in request.data.keys():
            if request.data['type'] == 'return_archive':
                if PoultryHatching.objects.filter(poultry=hatching.poultry, hall=hatching.hall, trash=False,
                                                  allow_hatching='pending', archive=False
                                                  ).exists():
                    return Response({"result": "شما در این سالن جوجه ریزی فعال دارید"},
                                    status=status.HTTP_403_FORBIDDEN)
                elif (datetime.datetime.now().date() - hatching.date.date()).days > 85:
                    return Response({"result": "جوجه ریزی انتخابی بالاتر از 85 روز میباشد،امکان بازگشت وجود ندارد!"},
                                    status=status.HTTP_403_FORBIDDEN)
                else:
                    hatching.allow_hatching = 'pending'
                    hatching.state = 'pending'
                    hatching.archive = False
                    hatching.chicken_age = (datetime.datetime.now().date() - hatching.date.date()).days + 1
                    hatching.output_archive_date = datetime.datetime.now()
                    hatching.output_archiver = user.fullname
                    free_sale = FreeSaleWithinprovince.objects.filter(trash=False, allow=True).first()
                    if free_sale:
                        if free_sale.type == 'weight':
                            hatching.total_commitment = hatching.quantity * free_sale.weight
                        else:
                            hatching.total_commitment_quantity = int(hatching.quantity * (free_sale.percent / 100))

                    hatching.save()
        if 'violation' in request.data.keys():
            if request.data['violation'] == True and hatching.violation == False:
                hatching.violation = True
            if request.data['violation'] == False and hatching.violation == True:
                hatching.violation = False
            hatching.save()
            request.data.pop('violation')
        if 'delete_tenant' in request.data.keys():
            hatching.tenant_fullname = None
            hatching.tenant_national_code = None
            hatching.tenant_mobile = None
            hatching.tenant_city = None
            hatching.has_tenant = False
            hatching.save()
            request.data.pop('delete_tenant')
        if 'direct_losses' in request.data.keys():
            if request.data['direct_losses'] > hatching.left_over:
                return Response({"result": "تعداد وارد شده از باقی مانده سالن بیشتر است"},
                                status=status.HTTP_403_FORBIDDEN)
            date = datetime.datetime.now()
            if hatching.direct_losses_inputer is None:
                hatching.direct_losses_inputer = user.fullname
                hatching.direct_losses_date = date
            else:
                hatching.direct_losses_editor = user.fullname
                hatching.direct_losses_last_edit_date = date
            hatching.save()
        if 'end_period_losses' in request.data.keys():
            if request.data['losses'] > hatching.left_over:
                return Response({"result": "تعداد وارد شده از باقی مانده سالن بیشتر است"},
                                status=status.HTTP_403_FORBIDDEN)
            if request.data['type'] == 'add':
                hatching.losses += request.data['losses']
            else:
                hatching.losses = request.data['losses']

            date = datetime.datetime.now()
            if hatching.end_period_losses_inputer is None:
                hatching.end_period_losses_inputer = user.fullname
                hatching.end_period_losses_date = date
            else:
                hatching.end_period_losses_editor = user.fullname
                hatching.end_period_losses_last_edit_date = date
            hatching.save()
            return Response({"result": "با موفقیت ثبت شد."}, status=status.HTTP_200_OK)
        serializer = self.serializer_class(hatching)
        serializer.update(instance=hatching, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # تابع مربوط به نمایش دوره جوجه ریزی مرغدار
    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        poultry_hatchings = []
        # refresh(request.user.id)
        from datetime import datetime
        now = datetime.now().date()
        user = SystemUserProfile.objects.get(user=request.user)

        if 'all_active_and_archive' in request.GET:
            base_query = PoultryHatching.objects.filter(
                trash=False
            ).select_related(
                'poultry__user',
                'poultry__address__city',
                'poultry__address__province',
                'chain_company'
            )

            if request.GET.get('role') == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                poultry_hatchings = base_query.filter(
                    poultry__city_operator=city_operator.unit_name,
                    poultry__address__province=user.province
                )
            elif request.GET.get('role') in ['CityJahad', 'CityPoultry', 'CityVet']:
                poultry_hatchings = base_query.filter(
                    poultry__address__city=user.city
                )
            elif request.GET.get('role') == 'ChainCompany':
                poultry_hatchings = base_query.filter(
                    chain_company__user=user,
                    poultry__address__province=user.province
                )
            else:
                poultry_hatchings = base_query.filter(
                    poultry__address__province=user.province
                )

            if 'date1' in request.GET and 'date2' in request.GET:
                date1 = datetime.strptime(request.GET['date1'], '%Y-%m-%d').date()
                date2 = datetime.strptime(request.GET['date2'], '%Y-%m-%d').date()
                poultry_hatchings = poultry_hatchings.filter(
                    date__date__gte=date1,
                    date__date__lte=date2
                )

            if 'age1' in request.GET and int(request.GET.get('age2')) > 0:
                age1 = int(request.GET['age1'])
                age2 = int(request.GET['age2'])
                poultry_hatchings = poultry_hatchings.filter(
                    chicken_age__gte=age1,
                    chicken_age__lte=age2
                )

            if 'search' in request.GET and value and value != 'undefined' and value.strip():
                poultry_hatchings = poultry_hatchings.filter(
                    build_query(self.filterset_class, value)
                )

            poultry_hatchings = poultry_hatchings.order_by('-date')

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

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

            serializer = self.get_serializer(poultry_hatchings, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        if 'unknown' in request.GET:
            base_query = PoultryHatching.objects.filter(
                trash=False, unknown=True
            ).select_related(
                'poultry__user',
                'poultry__address__city',
                'poultry__address__province',
                'chain_company'
            )

            if request.GET.get('role') == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                poultry_hatchings = base_query.filter(
                    poultry__city_operator=city_operator.unit_name,
                    poultry__address__province=user.province
                )
            elif request.GET.get('role') in ['CityJahad', 'CityPoultry', 'CityVet']:
                poultry_hatchings = base_query.filter(
                    poultry__address__city=user.city
                )
            elif request.GET.get('role') == 'ChainCompany':
                poultry_hatchings = base_query.filter(
                    chain_company__user=user,
                    poultry__address__province=user.province
                )
            else:
                poultry_hatchings = base_query.filter(
                    poultry__address__province=user.province
                )

            if 'date1' in request.GET and 'date2' in request.GET:
                date1 = datetime.strptime(request.GET['date1'], '%Y-%m-%d').date()
                date2 = datetime.strptime(request.GET['date2'], '%Y-%m-%d').date()
                poultry_hatchings = poultry_hatchings.filter(
                    date__date__gte=date1,
                    date__date__lte=date2
                )

            if 'age1' in request.GET and int(request.GET.get('age2')) > 0:
                age1 = int(request.GET['age1'])
                age2 = int(request.GET['age2'])
                poultry_hatchings = poultry_hatchings.filter(
                    chicken_age__gte=age1,
                    chicken_age__lte=age2
                )

            if 'search' in request.GET and value and value != 'undefined' and value.strip():
                poultry_hatchings = poultry_hatchings.filter(
                    build_query(self.filterset_class, value)
                )

            poultry_hatchings = poultry_hatchings.order_by('-date')

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

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

            serializer = self.get_serializer(poultry_hatchings, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        if 'role' in request.GET:
            if 'age1' in request.GET and int(request.GET.get('age2')) > 0:
                age1 = int(request.GET.get('age1'))
                age2 = int(request.GET.get('age2'))
                poultry_hatch = PoultryHatching.objects.filter(trash=False, chicken_age__range=(age1, age2),
                                                               unknown=False)
            else:
                if 'date1' in request.GET:
                    date1 = datetime.strptime(request.GET['date1'], '%Y-%m-%d').date()
                    date2 = datetime.strptime(request.GET['date2'], '%Y-%m-%d').date()
                    poultry_hatch = PoultryHatching.objects.filter(trash=False, date__date__gte=date1,
                                                                   date__date__lte=date2, unknown=False)
                else:
                    poultry_hatch = PoultryHatching.objects.filter(trash=False, unknown=False)
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                if 'search' in request.GET:
                    if 'chain' in request.GET:
                        if 'archive' in request.GET:
                            queryset = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__province=user.province, has_chain_company=True,
                                poultry__city_operator=city_operator.unit_name
                            ).order_by('-archive_date')
                        else:
                            queryset = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                            has_chain_company=True,
                                                            poultry__city_operator=city_operator.unit_name)
                    else:

                        if 'archive' in request.GET:
                            queryset = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__province=user.province,
                                poultry__city_operator=city_operator.unit_name
                            ).order_by('-archive_date')
                        else:
                            queryset = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                            poultry__city_operator=city_operator.unit_name)
                    if request.GET['search'] == 'filter':
                        if value != 'undefined' and value.strip():
                            poultry_hatchings = queryset.filter(
                                build_query(self.filterset_class, value)
                            )
                        else:
                            poultry_hatchings = queryset

                elif 'archive' in request.GET:
                    if 'chain' in request.GET:
                        poultry_hatchings = poultry_hatch.filter(
                            Q(allow_hatching='True', state='complete') | Q(archive=True),
                            poultry__address__province=user.province, has_chain_company=True,
                            poultry__city_operator=city_operator.unit_name
                        ).order_by('-archive_date')
                    else:
                        poultry_hatchings = poultry_hatch.filter(
                            Q(allow_hatching='True', state='complete') | Q(archive=True),
                            poultry__address__province=user.province,
                            poultry__city_operator=city_operator.unit_name
                        ).order_by('-archive_date')


                else:
                    if 'chain' in request.GET:

                        poultry_hatchings = poultry_hatch.filter(poultry__address__province=user.province,
                                                                 has_chain_company=True,
                                                                 allow_hatching='pending',
                                                                 poultry__city_operator=city_operator.unit_name).order_by(
                            'date')
                    else:
                        poultry_hatchings = poultry_hatch.filter(poultry__address__province=user.province,
                                                                 allow_hatching='pending',
                                                                 poultry__city_operator=city_operator.unit_name).order_by(
                            'date')
            elif request.GET['role'] == 'ChainCompany':
                if 'search' in request.GET:
                    if 'chain' in request.GET:
                        if 'archive' in request.GET:
                            queryset = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__province=user.province, has_chain_company=True,
                                chain_company__user=user
                            ).order_by('-archive_date')
                        else:
                            queryset = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                            has_chain_company=True,
                                                            chain_company__user=user)
                    else:

                        if 'archive' in request.GET:
                            queryset = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__province=user.province,
                                chain_company__user=user
                            ).order_by('-archive_date')
                        else:
                            queryset = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                            chain_company__user=user)
                    if request.GET['search'] == 'filter':
                        if value != 'undefined' and value.strip():
                            poultry_hatchings = queryset.filter(
                                build_query(self.filterset_class, value)
                            )
                        else:
                            poultry_hatchings = queryset

                elif 'archive' in request.GET:
                    if 'chain' in request.GET:
                        poultry_hatchings = poultry_hatch.filter(
                            Q(allow_hatching='True', state='complete') | Q(archive=True),
                            poultry__address__province=user.province, has_chain_company=True,
                            chain_company__user=user
                        ).order_by('-archive_date')
                    else:
                        poultry_hatchings = poultry_hatch.filter(
                            Q(allow_hatching='True', state='complete') | Q(archive=True),
                            poultry__address__province=user.province,
                            chain_company__user=user
                        ).order_by('-date')


                else:
                    if 'chain' in request.GET:

                        poultry_hatchings = poultry_hatch.filter(poultry__address__province=user.province,
                                                                 has_chain_company=True,
                                                                 allow_hatching='pending',
                                                                 chain_company__user=user).order_by(
                            'date')
                    else:
                        poultry_hatchings = poultry_hatch.filter(poultry__address__province=user.province,
                                                                 allow_hatching='pending',
                                                                 chain_company__user=user).order_by(
                            'date')
            else:
                if 'search' in request.GET:

                    if 'archive' in request.GET:
                        if 'chain' in request.GET:
                            if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                                poultry_hatchings = poultry_hatch.filter(
                                    Q(allow_hatching='True', state='complete') | Q(archive=True),
                                    poultry__address__city=user.city, has_chain_company=True,

                                ).order_by('-archive_date')
                            else:
                                poultry_hatchings = poultry_hatch.filter(
                                    Q(allow_hatching='True', state='complete') | Q(archive=True),
                                    poultry__address__province=user.province, has_chain_company=True,

                                ).order_by('-archive_date')
                        else:

                            if request.GET['role'] in ['CityJahad', 'CityPoultry']:
                                poultry_hatchings = poultry_hatch.filter(
                                    Q(allow_hatching='True', state='complete') | Q(archive=True),
                                    poultry__address__city=user.city, trash=False

                                ).order_by('-archive_date')
                            else:
                                poultry_hatchings = poultry_hatch.filter(
                                    Q(allow_hatching='True', state='complete') | Q(archive=True),
                                    poultry__address__province=user.province, trash=False
                                ).order_by('-archive_date')
                    else:
                        if 'chain' in request.GET:
                            if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                                poultry_hatchings = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                                         poultry__address__city=user.city,
                                                                         has_chain_company=True, trash=False
                                                                         )
                            else:

                                poultry_hatchings = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                                         poultry__address__province=user.province,
                                                                         has_chain_company=True, trash=False
                                                                         )
                        else:

                            if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                                poultry_hatchings = poultry_hatch.filter(archive=False, allow_hatching='pending',
                                                                         poultry__address__city=user.city,
                                                                         ).order_by('date')
                            else:

                                poultry_hatchings = poultry_hatch.filter(archive=False, allow_hatching='pending',

                                                                         ).order_by('date')

                    if request.GET['search'] == 'filter':
                        poultry_hatchings_list = []
                        if value != 'undefined' and value.strip():
                            poultry_hatchings = poultry_hatchings.filter(
                                build_query(self.filterset_class, value)
                            )
                        else:
                            poultry_hatchings = poultry_hatchings

                elif 'archive' in request.GET:
                    if 'chain' in request.GET:
                        if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                            poultry_hatchings = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__city=user.city, has_chain_company=True,

                            ).order_by('-archive_date')
                        else:

                            poultry_hatchings = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__province=user.province, has_chain_company=True,
                            ).order_by('-archive_date')
                    else:

                        if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                            poultry_hatchings = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__city=user.city,
                            ).order_by('-date')
                        else:

                            poultry_hatchings = poultry_hatch.filter(
                                Q(allow_hatching='True', state='complete') | Q(archive=True),
                                poultry__address__province=user.province,
                            ).order_by('-date')

                else:
                    if 'chain' in request.GET:
                        if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                            poultry_hatchings = poultry_hatch.filter(poultry__address__city=user.city,
                                                                     archive=False, has_chain_company=True,
                                                                     allow_hatching='pending').order_by(
                                'date')
                        else:

                            poultry_hatchings = poultry_hatch.filter(poultry__address__province=user.province,
                                                                     archive=False, has_chain_company=True,
                                                                     allow_hatching='pending').order_by(
                                'date')
                    else:

                        if request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                            poultry_hatchings = poultry_hatch.filter(poultry__address__city=user.city,
                                                                     archive=False,
                                                                     allow_hatching='pending').order_by(
                                'date')
                        else:
                            poultry_hatchings = poultry_hatch.filter(poultry__address__province=user.province,
                                                                     archive=False,
                                                                     allow_hatching='pending').order_by(
                                'date')

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

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

            serializer = self.get_serializer(poultry_hatchings, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)


        elif 'illegal' in request.GET:
            poultry_hatching = PoultryHatching.objects.filter(poultry__address__province=user.province,
                                                              archive=True).order_by('date')
            serializer = PoultryHatchingSerializer(poultry_hatching, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        elif 'forecast' in request.GET:
            hatch_quantity = 0
            hatch_losses = 0
            from datetime import datetime
            date1 = datetime.strptime(request.GET['date1'], '%Y-%m-%d').date()
            date2 = datetime.strptime(request.GET['date2'], '%Y-%m-%d').date()
            hatchs = PoultryHatching.objects.filter(state='pending',
                                                    poultry__address__province=user.province)
            if hatchs.count() > 0:
                for hatch in hatchs:
                    if date1.year <= hatch.date.year and date1.month <= hatch.date.month and date1.day <= hatch.date.day and hatch.date.year >= date2.year and hatch.date.month >= date2.month and hatch.date.day >= date2.day:
                        hatch_quantity += hatch.quantity - (hatch.quantity * 0.1)
                        hatch_losses += hatch.losses
            return Response({"hatch_quantity": hatch_quantity, "hatch_losses": hatch_losses})

        elif 'filter' in request.GET:
            now = datetime.now().date()
            quantity_1_5 = 0
            quantity_5_10 = 0
            quantity_10_15 = 0
            quantity_15_20 = 0
            quantity_20_25 = 0
            quantity_25_30 = 0
            quantity_30_35 = 0
            quantity_35_40 = 0
            quantity_40_45 = 0
            quantity_45_50 = 0
            quantity_50_55 = 0
            quantity_55_60 = 0
            hatching = PoultryHatching.objects.filter(state='pending')
            if hatching.count() > 0:
                for hatch in hatching:
                    age = (now - hatch.date.date()).days + 1
                    if age >= 1 and age <= 5:
                        quantity_1_5 += hatch.quantity
                    elif age >= 5 and age <= 10:
                        quantity_5_10 += hatch.quantity
                    elif age >= 10 and age <= 15:
                        quantity_10_15 += hatch.quantity
                    elif age >= 15 and age <= 20:
                        quantity_15_20 += hatch.quantity
                    elif age >= 20 and age <= 25:
                        quantity_20_25 += hatch.quantity
                    elif age >= 25 and age <= 30:
                        quantity_25_30 += hatch.quantity
                    elif age >= 30 and age <= 35:
                        quantity_30_35 += hatch.quantity
                    elif age >= 35 and age <= 40:
                        quantity_35_40 += hatch.quantity
                    elif age >= 40 and age <= 45:
                        quantity_40_45 += hatch.quantity
                    elif age >= 45 and age <= 50:
                        quantity_45_50 += hatch.quantity
                    elif age >= 50 and age <= 55:
                        quantity_50_55 += hatch.quantity
                    elif age >= 55 and age <= 60:
                        quantity_55_60 += hatch.quantity
                    out_put = {
                        'quantity_1_5': quantity_1_5,
                        'quantity_5_10': quantity_5_10,
                        'quantity_10_15': quantity_10_15,
                        'quantity_15_20': quantity_15_20,
                        'quantity_20_25': quantity_20_25,
                        'quantity_25_30': quantity_25_30,
                        'quantity_30_35': quantity_30_35,
                        'quantity_35_40': quantity_35_40,
                        'quantity_40_45': quantity_40_45,
                        'quantity_45_50': quantity_45_50,
                        'quantity_50_55': quantity_50_55,
                        'quantity_55_60': quantity_55_60,

                    }
                    return Response(out_put, status=status.HTTP_200_OK)
        elif 'age' in request.GET:
            poultry = []
            poultry_hatching = PoultryHatching.objects.filter(state='pending')
            now = datetime.now().date()
            if poultry_hatching.count() > 0:
                for hatch in poultry_hatching:
                    age = (now - hatch.date.date()).days + 1
                    if age >= int(request.GET['age1']) and age <= int(request.GET['age2']):
                        if hatch.poultry in poultry:
                            pass
                        else:
                            poultry.append(hatch.poultry)
            serializer = PoultrySerializer(poultry, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        elif 'amar' in request.GET:
            now = datetime.now().date()
            total_list = []
            l1 = []
            chickenbreed_list = ['وارداتی', 'آرین', 'راس', 'آربراکرز(آپلاس)', 'کاب', 'هوبارد', 'ترکیبی']
            for city in City.objects.all():
                for breed in chickenbreed_list:
                    quantity_1_5 = 0
                    quantity_1_5_losses = 0
                    quantity_5_10 = 0
                    quantity_5_10_losses = 0
                    quantity_10_15 = 0
                    quantity_10_15_losses = 0
                    quantity_15_20 = 0
                    quantity_15_20_losses = 0
                    quantity_20_25 = 0
                    quantity_20_25_losses = 0
                    quantity_25_30 = 0
                    quantity_25_30_losses = 0
                    quantity_30_35 = 0
                    quantity_30_35_losses = 0
                    quantity_35_40 = 0
                    quantity_35_40_losses = 0
                    quantity_40_45 = 0
                    quantity_40_45_losses = 0
                    quantity_45_50 = 0
                    quantity_45_50_losses = 0
                    quantity_50_55 = 0
                    quantity_50_55_losses = 0
                    quantity_55_60 = 0
                    quantity_55_60_losses = 0
                    hatchs = PoultryHatching.objects.filter(state='pending', poultry__address__city=city,
                                                            chicken_breed=breed)
                    if hatchs.count() > 0:
                        for hatch in hatchs:
                            age = (now - hatch.date.date()).days + 1
                            if age >= 1 and age <= 5:
                                quantity_1_5 += hatch.quantity
                                quantity_1_5_losses += hatch.losses
                            elif age >= 5 and age <= 10:
                                quantity_5_10 += hatch.quantity
                                quantity_5_10_losses += hatch.losses
                            elif age >= 10 and age <= 15:
                                quantity_10_15 += hatch.quantity
                                quantity_10_15_losses += hatch.losses
                            elif age >= 15 and age <= 20:
                                quantity_15_20 += hatch.quantity
                                quantity_15_20_losses += hatch.losses
                            elif age >= 20 and age <= 25:
                                quantity_20_25 += hatch.quantity
                                quantity_20_25_losses += hatch.losses
                            elif age >= 25 and age <= 30:
                                quantity_25_30 += hatch.quantity
                                quantity_25_30_losses += hatch.quantity
                            elif age >= 30 and age <= 35:
                                quantity_30_35 += hatch.quantity
                                quantity_30_35_losses += hatch.losses
                            elif age >= 35 and age <= 40:
                                quantity_35_40 += hatch.quantity
                                quantity_35_40_losses += hatch.losses
                            elif age >= 40 and age <= 45:
                                quantity_40_45 += hatch.quantity
                                quantity_40_45_losses += hatch.losses
                            elif age >= 45 and age <= 50:
                                quantity_45_50 += hatch.quantity
                                quantity_45_50_losses += hatch.losses
                            elif age >= 50 and age <= 55:
                                quantity_50_55 += hatch.quantity
                                quantity_50_55_losses += hatch.losses
                            elif age >= 55 and age <= 60:
                                quantity_55_60 += hatch.quantity
                                quantity_55_60_losses += hatch.losses
                    internal_dict = {
                        'quantity_1_5': quantity_1_5,
                        'quantity_1_5_losses': quantity_1_5_losses,
                        'quantity_5_10': quantity_5_10,
                        'quantity_5_10_losses': quantity_5_10_losses,
                        'quantity_10_15': quantity_10_15,
                        'quantity_10_15_losses': quantity_10_15_losses,
                        'quantity_15_20': quantity_15_20,
                        'quantity_15_20_losses': quantity_15_20_losses,
                        'quantity_20_25': quantity_20_25,
                        'quantity_20_25_losses': quantity_20_25_losses,
                        'quantity_25_30': quantity_25_30,
                        'quantity_25_30_losses': quantity_25_30_losses,
                        'quantity_30_35': quantity_30_35,
                        'quantity_30_35_losses': quantity_30_35_losses,
                        'quantity_35_40': quantity_35_40,
                        'quantity_35_40_losses': quantity_35_40_losses,
                        'quantity_40_45': quantity_40_45,
                        'quantity_40_45_losses': quantity_40_45_losses,
                        'quantity_45_50': quantity_45_50,
                        'quantity_45_50_losses': quantity_45_50_losses,
                        'quantity_50_55': quantity_50_55,
                        'quantity_50_55_losses': quantity_50_55_losses,
                        'quantity_55_60': quantity_55_60,
                        'quantity_55_60_losses': quantity_55_60_losses,

                    }
                    l1.append({breed: internal_dict})

                total_list.append({city.name: l1})
                l1 = []

            return Response(total_list, status=status.HTTP_200_OK)

        # list of self poultry houses
        elif 'key' in request.GET:
            poultry = Poultry.objects.get(key=request.GET['key'], trash=False)
            if 'hall' in request.GET:
                poultry_hatching = PoultryHatching.objects.filter(poultry=poultry, hall=int(request.GET['hall']),
                                                                  state='pending', trash=False).order_by('date')
            elif 'increase' in request.GET:
                poultry_hatching = PoultryHatching.objects.filter(poultry=poultry, state='pending',
                                                                  trash=False).order_by('date')
            else:
                poultry_hatching = PoultryHatching.objects.filter(poultry=poultry, state='pending', left_over__gt=0,
                                                                  trash=False).order_by('date')

        elif 'role' in request.GET:
            if 'age1' in request.GET and int(request.GET.get('age2')) > 0:
                age1 = int(request.GET.get('age1'))
                age2 = int(request.GET.get('age2'))
                poultry_hatch = self.queryset.filter(trash=False, chicken_age__range=(age1, age2))
            else:
                poultry_hatch = self.queryset.filter(trash=False)
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=SystemUserProfile.objects.get(user=request.user))
                city = city_operator.address.city
                city_unit_list = []
                city_units = CityUnit.objects.filter(city=city)
                for city in city_units:
                    city_unit_list.append(city.name)
                poultry_hatching = poultry_hatch.filter(poultry__address__city__name__in=city_unit_list,
                                                        state__in=('pending', 'complete'),
                                                        trash=False).order_by(
                    '-create_date')
            else:
                poultry_hatching = poultry_hatch.filter(poultry__address__province=user.province,
                                                        # state__in=('pending', 'complete'),
                                                        trash=False).order_by(
                    '-create_date')
        else:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            poultry = Poultry.objects.filter(user=user, trash=False)

            if poultry.count() > 1:
                list1 = []
                for p in poultry:
                    list1.append(p.id)
                poultry_hatching = PoultryHatching.objects.filter(poultry_id__in=list1, trash=False).order_by(
                    'date')

            else:

                poultry_hatching = PoultryHatching.objects.filter(poultry=poultry.last(), trash=False).order_by(
                    'date')
        serializer = PoultryHatchingSerializer(poultry_hatching, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        queryset = PoultryHatching.objects.get(key__exact=request.GET["key"], trash=False)
        vet_farm_inspection = VetFarmInspection.objects.filter(poultry_hatching=queryset, trash=False)
        poultry_request = PoultryRequest.objects.filter(hatching=queryset, trash=False)
        if vet_farm_inspection.count() > 0:
            return Response({"result": "object has inspection"}, status=status.HTTP_400_BAD_REQUEST)
        elif poultry_request.count() > 0:
            return Response({"result": "object has poultry_request"}, status=status.HTTP_403_FORBIDDEN)
        queryset.trash = True
        queryset.save()
        # queryset.delete()
        return Response({"result": "object deleted"}, status=status.HTTP_200_OK)


class PoultryHatchingForPredictionViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingForPredictionSerializer
    pagination_class = CustomPagination
    filterset_class = PoultryHatchingFilterSet
    filterset_fields = [
        'poultry__user__first_name',
        'poultry__user__last_name',
        'poultry__user__mobile',
        'poultry__unit_name',
        'poultry__address__city__name',
        'chicken_age',
        'poultry__breeding_unique_id',
        'poultry__city_operator',

    ]

    def list(self, request, *args, **kwargs):

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'hatching_list' in request.GET:
            poultry_hatchings = PoultryHatching.objects.filter(
                id__in=(request.GET['hatching_list']).split(',')).order_by('date')
        else:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                poultry_hatchings = PoultryHatching.objects.filter(archive=False, allow_hatching='pending',
                                                                   state='pending',
                                                                   poultry__city_operator=city_operator.unit_name,
                                                                   trash=False).order_by('date')

            elif request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
                poultry_hatchings = PoultryHatching.objects.filter(archive=False, allow_hatching='pending',
                                                                   state='pending',
                                                                   poultry__address__city=user.city,
                                                                   trash=False).order_by('date')

            else:
                poultry_hatchings = PoultryHatching.objects.filter(archive=False, allow_hatching='pending',
                                                                   state='pending',
                                                                   trash=False).order_by('date')

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

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

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

        serializer = self.get_serializer(poultry_hatchings, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class PoultryHatchingForPredictionDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingForPredictionSerializer

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user, trash=False)
            poultry_hatchings = PoultryHatching.objects.filter(archive=False, allow_hatching='pending', state='pending',
                                                               poultry__city_operator=city_operator.unit_name,
                                                               trash=False).order_by('date')

        elif request.GET['role'] in ['CityJahad', 'CityPoultry', 'CityVet']:
            poultry_hatchings = PoultryHatching.objects.filter(archive=False, allow_hatching='pending', state='pending',
                                                               poultry__address__city=user.city,
                                                               trash=False).order_by('date')

        else:
            poultry_hatchings = PoultryHatching.objects.filter(archive=False, allow_hatching='pending', state='pending',
                                                               trash=False).order_by('date')

        now_ages = poultry_hatchings.aggregate(total=Sum('now_age'))['total'] or 0
        total_hatching_quantity = poultry_hatchings.aggregate(total=Sum('quantity'))['total'] or 0
        total_hatching_left_over = poultry_hatchings.aggregate(total=Sum('left_over'))['total'] or 0
        ave_now_age = now_ages / len(poultry_hatchings) if len(poultry_hatchings) > 0 else 0
        sum_age = 0
        ave_age = 0
        ave_weight = 0
        counter = 0
        poultry_requests = PoultryRequest.objects.filter(trash=False, state_process__in=('pending', 'accepted'),
                                                         province_state__in=('pending', 'accepted'),
                                                         out_province_request_cancel=False,
                                                         hatching__in=poultry_hatchings)
        for poultry_request in poultry_requests:
            sum_age += (poultry_request.send_date.date() - poultry_request.hatching.date.date()).days + 1
            counter += 1
        ave_age = int(sum_age / counter) if counter > 0 else 0

        province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
                                                                    province_request__poultry_request__hatching__in=poultry_hatchings,
                                                                    first_car_allocated_quantity=0,
                                                                    return_to_province=False)

        province_kill_requests_quantity = \
            province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total'] or 0

        province_kill_requests_weight = \
            province_kill_requests.aggregate(total=Sum('total_killed_weight'))['total'] or 0
        kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                              province_request__poultry_request__hatching__in=poultry_hatchings)

        kill_house_requests_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
        kill_house__requests_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0

        total_quantity = province_kill_requests_quantity + kill_house_requests_quantity
        total_weight = province_kill_requests_weight + kill_house__requests_weight

        ave_weight = round(total_weight / total_quantity, 2) if total_quantity > 0 else 0

        result = {
            "hatchings": len(poultry_hatchings),
            "total_hatching_quantity": total_hatching_quantity,
            "total_hatching_left_over": total_hatching_left_over,
            "ave_age": ave_age, "ave_now_age": ave_now_age,
            "ave_weight": ave_weight,
            "province_kill_requests": len(province_kill_requests),
            "province_kill_requests_quantity": province_kill_requests_quantity,
            "province_kill_requests_weight": province_kill_requests_weight,
            "kill_house_requests": len(kill_house_requests),
            "kill_house_requests_quantity": kill_house_requests_quantity,
            "kill_house__requests_weight": kill_house__requests_weight,
            "total_quantity": total_quantity,
            "total_weight": total_weight
        }

        return Response(result, status=status.HTTP_200_OK)


class PoultryHatchingForPredictionChartViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingForPredictionSerializer

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        consumption_limit_type = request.GET.get('consumption_limit_type')
        consumption_limit = request.GET.get('consumption_limit')
        killing_age_external_type = request.GET.get('killing_age_external_type')
        killing_age_internal_type = request.GET.get('killing_age_internal_type')
        killing_age = request.GET.get('killing_age')
        time_frame_type = request.GET.get('time_frame_type')
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        date_list = []
        final_list = []

        poultries = Poultry.objects.filter(killing_ave_age__gt=1, trash=False)
        if killing_age_external_type == 'poultry_ave_killing_age':
            if killing_age_internal_type == 'poultry':
                if time_frame_type == 'all':
                    hatchings = PoultryHatching.objects.filter(trash=False, state='pending',
                                                               archive=False, temporary_trash=False,
                                                               temporary_deleted=False, predicate_date__isnull=False)
                    date_list = hatchings.values_list('predicate_date', flat=True).distinct()
                    for date in date_list:
                        n_hatchings = hatchings.filter(predicate_date=date)
                        poultries = Poultry.objects.filter(pk__in=n_hatchings.values_list('poultry', flat=True))
                        ages = poultries.values_list('killing_ave_age', flat=True).distinct()

                        index_weight = poultries.aggregate(total=Sum('real_killing_ave_weight'))[
                                           'total'] or 0
                        quantity = n_hatchings.aggregate(total=Sum('left_over'))[
                                       'total'] or 0

                        result = {
                            "date": date,
                            "quantity": quantity,
                            "poultry": len(poultries),
                            "age": ages,
                            "hatchings": n_hatchings.values_list('id', flat=True),
                            "weight": int(quantity * index_weight) if consumption_limit_type in (
                                'quantity', 'live_weight') else int((quantity * index_weight) * 0.75),
                        }
                        final_list.append(result)

                else:
                    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    hatchings = PoultryHatching.objects.filter(trash=False, state='pending',
                                                               archive=False, temporary_trash=False,
                                                               temporary_deleted=False, predicate_date__date__gte=date1,
                                                               predicate_date__date__lte=date2)
                    # poultries = poultries.filter(date__gte=date1,date__lte=date2).order_by('date')
                    date_list = poultries.values_list('date', flat=True).distinct()

                    for date in date_list:
                        n_hatchings = hatchings.filter(predicate_date__date=date)
                        poultries = Poultry.objects.filter(pk__in=n_hatchings.values_list('poultry', flat=True))
                        ages = poultries.values_list('killing_ave_age', flat=True).distinct()

                        index_weight = poultries.aggregate(total=Sum('real_killing_ave_weight'))[
                                           'total'] or 0
                        quantity = n_hatchings.aggregate(total=Sum('left_over'))[
                                       'total'] or 0
                        result = {
                            "date": date,
                            "quantity": quantity,
                            "poultry": len(poultries.filter(date=date)),
                            "age": ages,
                            "hatchings": n_hatchings.values_list('id', flat=True),
                            "weight": int(quantity * index_weight) if consumption_limit_type in (
                                'quantity', 'live_weight') else int((quantity * index_weight) * 0.75),
                        }
                        final_list.append(result)

            else:
                sum_of_ages = poultries.aggregate(total=Sum('killing_ave_age'))[
                                  'total'] or 0
                ave_killing_age = int(sum_of_ages / len(poultries))
                if time_frame_type == 'all':
                    final_list = poultry_prediction_helper(ave_killing_age, consumption_limit_type)


                else:
                    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    final_list = poultry_prediction_helper(ave_killing_age, consumption_limit_type, date1, date2)

        else:
            if killing_age_internal_type == 'poultry':
                if time_frame_type == 'all':
                    final_list = poultry_prediction_helper(int(killing_age), consumption_limit_type)
                    # poultries = poultries.filter(killing_ave_age=int(killing_age))
                    # date_list = poultries.values_list('date', flat=True).distinct()
                    # for date in date_list:
                    #     index_weight = poultries.filter(date=date).aggregate(total=Sum('killing_ave_weight'))[
                    #                        'total'] or 0
                    #     quantity = poultries.filter(date=date).aggregate(total=Sum('active_left_over'))[
                    #                    'total'] or 0
                    #
                    #     result = {
                    #         "date": date,
                    #         "quantity": quantity,
                    #         "poultry": len(poultries.filter(date=date)),
                    #         "age": int(killing_age),
                    #         "wight": quantity * index_weight,
                    #     }
                    #     final_list.append(result)

                else:
                    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    final_list = poultry_prediction_helper(int(killing_age), consumption_limit_type, date1, date2)

                    # poultries = poultries.filter(killing_ave_age=int(killing_age),date__gte=date1,date__lte=date2)
                    # date_list = poultries.values_list('date', flat=True)
                    # for date in date_list:
                    #     index_weight = poultries.filter(date=date).aggregate(total=Sum('killing_ave_weight'))[
                    #                        'total'] or 0
                    #     quantity = poultries.filter(date=date).aggregate(total=Sum('active_left_over'))[
                    #                    'total'] or 0
                    #
                    #     result = {
                    #         "date": date,
                    #         "quantity": quantity,
                    #         "poultry": len(poultries.filter(date=date)),
                    #         "age": int(killing_age),
                    #         "wight": quantity * index_weight,
                    #     }
                    #     final_list.append(result)

            else:

                ave_killing_age = int(killing_age)

                if time_frame_type == 'all':
                    final_list = poultry_prediction_helper(ave_killing_age, consumption_limit_type)



                else:
                    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    final_list = poultry_prediction_helper(ave_killing_age, consumption_limit_type, date1, date2)

        return Response(final_list)


class PoultryTenantViewSet(viewsets.ModelViewSet):
    queryset = PoultryTenant.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryTenantSerializer


# ویوست مربوط به ثبت و نمایش و ... درخواست بورسی مرغدار
class PoultryRequestExchangeViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequestExchange.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryRequestExchangeSerializer

    filter_backends = [DjangoFilterBackend]
    filterset_class = PoultryRequestExchangeFilterSet
    filterset_fields = [
        'quantity',
        'send_date',
        'chicken_breed',
        'Index_weight',
        'fee',
        'age',
    ]

    # تابع مربوط به ثبت درخواست بورسی مرغدار
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = UserProfile.objects.get(user=request.user, trash=False)
        send_date = request.data['send_date']
        hatching_date = request.data['hatching_date']
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            poultry_request_exchange = serializer.create(validated_data=request.data)
            send_date = datetime.strptime(send_date, '%Y-%m-%d %H:%M:%S').date()
            hatching_date = datetime.strptime(hatching_date, '%Y-%m-%d %H:%M:%S').date()
            poultry_request_exchange.age = (send_date - hatching_date).days
            poultry_request_exchange.user = user
            poultry_request_exchange.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    # تابع مربوط به نمایش درخواست بورسی مرغدار
    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        queryset = []
        list1 = []
        values_item = []
        query_list = []
        query_dictionary = {}
        query_list_obj = []
        filter_list = []
        obj_list = []
        q2 = []

        if 'operator' in request.GET:
            if request.GET['operator'] == 'kill_house':
                chicken_breed = request.GET['chicken_breed'].split(",")
                send_date1 = request.GET['send_date1'].strip()
                send_date2 = request.GET['send_date2'].strip()
                send_date1 = datetime.strptime(send_date1, '%Y-%m-%d').date()
                send_date2 = datetime.strptime(send_date2, '%Y-%m-%d').date()
                q = PoultryRequestExchange.objects.filter(chicken_breed__in=chicken_breed, trash=False).order_by(
                    'fee')
                for x in q:
                    if x.send_date.date() >= send_date1 and x.send_date.date() <= send_date2:
                        q2.append(x)
                serializer = self.serializer_class(q2, many=True)
                return Response(serializer.data)

        if 'type' in request.GET:
            if request.GET['type'] == 'filter':
                if request.GET['value'] != "":
                    d1 = request.GET['value'].split(",")
                    for item in self.filterset_fields:
                        for x in d1:
                            query = QueryDict('{0}__contains={1}'.format(item, x))
                            if (self.filterset_class(data=query, queryset=self.queryset.all())).filter():
                                query_list.append(query)

                    for i in query_list:
                        for key, value in i.items():
                            query_dictionary[key] = value
                    if len(d1) != len(query_dictionary):
                        pass
                    else:
                        for i in PoultryRequestExchange.objects.filter(**query_dictionary):
                            query_list_obj.append(i)

                if 'age_period' in request.GET:
                    if request.GET['age_period'] != "":
                        age_split = request.GET['age_period'].split(',')
                        for item in self.queryset:
                            if int(age_split[0]) <= item.age <= int(age_split[1]):
                                obj_list.append(item)
                        for i in obj_list:
                            for j in query_list_obj:
                                if i == j:
                                    filter_list.append(i)
                        query_list_obj.clear()
                        for i in filter_list:
                            query_list_obj.append(i)

                serializer = self.serializer_class(query_list_obj, many=True)
                return Response(serializer.data)
            return Response({"msg": "Enter 'Type' In Get Parameters"}, status=status.HTTP_403_FORBIDDEN)

        queryset = PoultryRequestExchange.objects.all()
        serializer = self.serializer_class(queryset, many=True)
        return Response(serializer.data)


# ویوست مربوط به تایید یا رد درخواست بورسی رزرو شده توسط کشتارگاه برای درخواست بورسی مرغدار
class PoultryRequestExchangeAcceptViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequestExchangeAccept.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryRequestExchangeAcceptSerializer

    # تابع مربوط به تایید یا رد درخواست بورسی رزرو شده توسط کشتارگاه برای درخواست بورسی مرغدار
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        poultry_exchange = PoultryRequestExchange.objects.get(key=request.data['poultry_request_key'], trash=False)
        kill_house_exchange_reserve = KillHouseRequestExchangeReserve.objects.get(
            key=request.data['kill_house_request_key'], trash=False)
        request.data.pop('poultry_request_key')
        request.data.pop('kill_house_request_key')

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            poultry_request_exchange_accept = serializer.create(validated_data=request.data)
            poultry_request_exchange_accept.poultry_request_exchange = poultry_exchange
            poultry_request_exchange_accept.kill_house_request_exchange_reserve = kill_house_exchange_reserve
            poultry_request_exchange_accept.save()
            if poultry_request_exchange_accept.state == 'accepted':
                poultry_exchange.quantity -= kill_house_exchange_reserve.quantity
                poultry_exchange.state = 'pending'
                poultry_exchange.save()
                kill_house_exchange_reserve.state = 'accepted'
            else:
                kill_house_exchange_reserve.state = 'rejected'

            kill_house_exchange_reserve.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)


# ویوست مربوط به ثبت و نمایش و ... درخواست مرغدار

class PoultryRequestForLetterViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date = datetime.datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date()
        poultry_requests = PoultryRequest.objects.filter(send_date__date=date,
                                                         quantity__gt=F('remain_quantity'),
                                                         trash=False)
        serializer = PoultryRequestLetterTotalSerializer(poultry_requests, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class CancelOutProvincePoultryRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def update(self, request, pk=None, *args, **kwargs):
        date = datetime.datetime.now()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.data['role']
        poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])
        if poultry_request.quarantine_code != None:
            return Response({"result": "به علت ورود کد قرنطینه امکان لغو وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)
        if poultry_request.wage_pay == True:
            return Response({"result": "به علت پرداخت امکان لغو وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)
        poultry_request.out_province_request_cancel = True
        poultry_request.out_province_request_canceller = {
            "role": role,
            "fullname": user.fullname,
            "mobile": user.mobile,
            "date": str(date),
        }
        poultry_request.save()
        if poultry_request.province_state == 'accepted':
            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
            hatching.out_province_killed_weight -= int(poultry_request.quantity * poultry_request.Index_weight)
            hatching.out_province_killed_quantity -= poultry_request.quantity
            hatching.save()
        return Response({"result": "با موفقیت ثیت شد"}, status=status.HTTP_200_OK)


class OutProvincePoultryRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestoutProvinceSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    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):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        wage_type = WageType.objects.filter(en_name='poultry-sell-out-province', trash=False).first()
        state = request.GET['state']
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        if request.GET['role'] == 'VetFarm':
            vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
            poultries = Poultry.objects.filter(
                pk__in=vet_farms.values('poultry')
            )
            if state == 'pending':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    poultry__in=poultries, send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    poultry__in=poultries, send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True),
                    poultry__in=poultries, send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    trash=False).order_by('-send_date')

        elif request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            if state == 'pending':

                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    poultry__city_operator=city_operator.unit_name,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    poultry__city_operator=city_operator.unit_name,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:

                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True),
                    poultry__city_operator=city_operator.unit_name,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    trash=False).order_by('-send_date')



        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            if state == 'pending':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    poultry__address__city=user.city,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    poultry__address__city=user.city,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:

                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True),
                    poultry__address__city=user.city,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    trash=False).order_by('-send_date')
        elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']:
            if request.GET['state'] == 'pending':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    send_date__date__gte=date1,
                    send_date__date__lte=date2, out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')

            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    send_date__date__gte=date1,
                    send_date__date__lte=date2, out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='rejected',
                        province_state='rejected',
                        has_wage=True, wage_pay=False,
                        out_province_request_cancel=True, archive=True) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=True, wage_pay=False, out_province_request_cancel=True) | Q(
                        state_process='accepted', province_state='accepted', final_state='archive',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                        state_process='accepted', province_state='accepted', final_state='archive',
                        has_wage=True, wage_pay=False, out_province_request_cancel=True),
                    send_date__date__gte=date1,
                    send_date__date__lte=date2, out=True,
                    trash=False).order_by('-send_date')

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

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

        page = self.paginate_queryset(poultry_requests)
        if page is not None:
            serializer = PoultryRequestoutProvinceSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = PoultryRequestoutProvinceSerializer(poultry_requests, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])
        poultry_request.out_province_driver_info['driverhealthCode'] = request.data['driver_health_code']
        poultry_request.save()
        return Response({"result": "با موفقیت ثیت شد"}, status=status.HTTP_200_OK)


class OutProvincePoultryRequestDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestoutProvinceSerializer
    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):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)

        if request.GET['role'] == 'VetFarm':
            vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
            poultries = Poultry.objects.filter(
                pk__in=vet_farms.values('poultry')
            )
            poultry_requests = PoultryRequest.objects.filter(
                poultry__in=poultries,
                out=True,
                temporary_trash=False,
                temporary_deleted=False,
                trash=False).order_by('-send_date')


        elif request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            poultry_requests = PoultryRequest.objects.filter(
                poultry__city_operator=city_operator.unit_name,
                temporary_trash=False,
                temporary_deleted=False,
                out=True,
                trash=False).order_by('-send_date')

        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            poultry_requests = PoultryRequest.objects.filter(
                poultry__address__city=user.city,
                temporary_trash=False,
                temporary_deleted=False,
                out=True,
                trash=False).order_by('-send_date')

        elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']:
            poultry_requests = PoultryRequest.objects.filter(
                out=True,
                temporary_trash=False,
                temporary_deleted=False,
                trash=False).order_by('-send_date')
        if 'date1' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            poultry_requests = poultry_requests.filter(send_date__date__gte=date1, send_date__date__lte=date2)

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

        poultry = Poultry.objects.filter(trash=False, pk__in=poultry_requests.values_list('poultry', flat=True))
        total_out_province_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))[
                                                          'total'] or 0
        total_out_province_poultry_request_weight = \
            poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[
                'total'] or 0

        accepted_poultry_requests_with_out_wage = poultry_requests.filter(
            state_process='accepted', province_state='accepted', final_state='archive',
            out_province_request_cancel=False, has_wage=False, wage_pay=False,
        )

        total_accepted_poultry_request_quantity_with_out_wage = \
            accepted_poultry_requests_with_out_wage.aggregate(total=Sum('quantity'))[
                'total'] or 0

        total_accepted_poultry_request_weight_with_out_wage = \
            accepted_poultry_requests_with_out_wage.aggregate(total=Sum(F('quantity') * F('Index_weight')))[
                'total'] or 0

        paid_poultry_requests = poultry_requests.filter(
            state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
            wage_pay=True, out_province_request_cancel=False
        )

        total_paid_poultry_request_quantity = paid_poultry_requests.aggregate(total=Sum('quantity'))[
                                                  'total'] or 0

        total_paid_poultry_request_weight = \
            paid_poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[
                'total'] or 0

        result = {
            "poultries": len(poultry),
            "total_number_of_poultry_request": len(poultry_requests),
            "total_poultry_request_quantity": total_out_province_poultry_request_quantity,
            "total_poultry_request_weight": total_out_province_poultry_request_weight,
            "total_number_of_accepted_poultry_request_with_out_wage": len(accepted_poultry_requests_with_out_wage),
            "total_accepted_poultry_request_quantity_with_out_wage": total_accepted_poultry_request_quantity_with_out_wage,
            "total_accepted_poultry_request_weight_with_out_wage": total_accepted_poultry_request_weight_with_out_wage,
            "total_number_of_accepted_poultry_request_with_wage": len(paid_poultry_requests),
            "total_accepted_poultry_request_quantity_with_wage": total_paid_poultry_request_quantity,
            "total_accepted_poultry_request_weight_with_wage": total_paid_poultry_request_weight,
            "total_number_of_accepted_poultry_request": len(accepted_poultry_requests_with_out_wage) + len(
                paid_poultry_requests),
            "total_accepted_poultry_request_quantity": total_paid_poultry_request_quantity + total_accepted_poultry_request_quantity_with_out_wage,
            "total_accepted_poultry_request_weight": total_paid_poultry_request_weight + total_accepted_poultry_request_weight_with_out_wage,

        }

        return Response(result, status=status.HTTP_200_OK)


class ParentCompanyOutProvincePoultryRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestoutProvinceSerializer
    permission_classes = [AllowAny]
    pagination_class = CustomPagination
    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):
        state = request.GET['state']
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if request.GET['state'] == 'pending':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                      wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')

        elif state == 'accepted':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
        else:
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                  wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                         province_state='rejected',
                                                                         final_state='archive',
                                                                         has_wage=False, wage_pay=False,
                                                                         out_province_request_cancel=False) | Q(
                    state_process='rejected',
                    province_state='rejected',
                    has_wage=True, wage_pay=False,
                    out_province_request_cancel=True, archive=True) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=True, wage_pay=False, out_province_request_cancel=True) | Q(
                    state_process='accepted', province_state='accepted', final_state='archive',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                    state_process='accepted', province_state='accepted', final_state='archive',
                    has_wage=True, wage_pay=False, out_province_request_cancel=True),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                trash=False).order_by('-send_date')

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

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

        page = self.paginate_queryset(poultry_requests)
        if page is not None:
            serializer = PoultryRequestoutProvinceSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = PoultryRequestoutProvinceSerializer(poultry_requests, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class TemporaryOutProvincePoultryRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestoutProvinceSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        wage_type = WageType.objects.filter(en_name='poultry-sell-out-province', trash=False).first()
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        if request.GET['role'] == 'VetFarm':
            vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
            poultries = Poultry.objects.filter(
                pk__in=vet_farms.values('poultry')
            )

            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                poultry__in=poultries, send_date__date__gte=date1,
                send_date__date__lte=date2,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')


        elif request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)

            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                poultry__city_operator=city_operator.unit_name,
                send_date__date__gte=date1,
                send_date__date__lte=date2,
                out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')




        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:

            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                poultry__address__city=user.city,
                send_date__date__gte=date1,
                send_date__date__lte=date2,
                out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')

        elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX']:
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')

        serializer = PoultryRequestoutProvinceSerializer(poultry_requests, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])
        poultry_request.out_province_driver_info['driverhealthCode'] = request.data['driver_health_code']
        poultry_request.save()
        return Response({"result": "با موفقیت ثیت شد"}, status=status.HTTP_200_OK)


class PoultryRequestViewSet(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 create(self, request, *args, **kwargs):
        request_buyer = None
        traffic_codes = None
        vet = None
        if 'kill_req_key' in request.data.keys():
            if request.data['kill_req_key'] is not None:
                kill_request = KillRequest.objects.get(key=request.data['kill_req_key'])
                if request.data['quantity'] > (kill_request.kill_capacity - kill_request.remain_quantity_for_poultry):
                    return Response({"result": "تعداد وارد شده از باقی مانده ظرفیت کشتارگاه انتخابی بیشتر است!"},
                                    status=status.HTTP_403_FORBIDDEN)
                kill_request.remain_quantity_for_poultry += request.data['quantity']
                kill_request.save()
            request.data.pop('kill_req_key')
        wage_type = WageType.objects.filter(en_name='poultry-sell-out-province', trash=False).first()
        time_range = TimeRange.objects.filter(trash=False).first()
        if time_range:
            time = next(
                (t for t in time_range.time_range if t.get("name") == "poultry_request" and t.get("active", False)),
                None)
            if time:

                start_hour = datetime.datetime.strptime(time.get("start", 0), "%H:%M:%S").time()
                end_hour = datetime.datetime.strptime(time.get("end", 0), "%H:%M:%S").time()
                current_hour = datetime.datetime.now().time().replace(second=0, microsecond=0)
                if not (start_hour < current_hour < end_hour):
                    return Response(
                        {"result": "لطفا در ساعات مجاز برای ثبت درخواست اقدام نمایید!"},
                        status=status.HTTP_403_FORBIDDEN)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        last_poultry_request = PoultryRequest.objects.all()
        if last_poultry_request.count() > 0:
            general_order_code = last_poultry_request.last().general_order_code + 1
        else:
            general_order_code = 1

        now_request_date = datetime.datetime.now().date()
        now = datetime.datetime.now().time()
        now_hour = HourLimit.objects.all()
        if now_hour.count() > 0:
            now_hour = now_hour.last()
            if now_hour.active == True:
                request_date = datetime.datetime.strptime(request.data['send_date'], '%Y-%m-%d').date()
                if request_date.year >= now_request_date.year and request_date.month >= now_request_date.month and request_date.day > now_request_date.day:
                    pass

                else:
                    if now.hour >= now_hour.hour:
                        text = 'زمان ثبت درخواست کشتار درامروز تا ساعت {0} بوده است. شما میتوانید برای تاریخ های آینده درخواست ثبت نمایید ! '.format(
                            now_hour.hour)
                        if 'role' not in request.data.keys():
                            return Response({'result': text}, status=status.HTTP_403_FORBIDDEN)
        poultry_hatching = PoultryHatching.objects.get(key=request.data['poultry_hatching_key'], trash=False)
        vet = VetFarm.objects.filter(poultry=poultry_hatching.poultry, trash=False).last()
        free_sale_with_province = FreeSaleWithinprovince.objects.filter(trash=False).first()
        if poultry_hatching.poultry.order_limit:
            return Response(
                {"result": "امکان ثبت کشتار برای مرغدار وجود ندارد جهت اطلاعات بیشتر بااتحادیه استان خود هماهنگ کنید!"},
                status=status.HTTP_403_FORBIDDEN)
        # if RequestLimitation.objects.filter(trash=False).first().limitation:
        #     if ('out' in request.data.keys() and request.data['out'] == True) or (
        #             'free_sale_in_province' in request.data.keys() and request.data['free_sale_in_province'] == True):
        #         free_sale_state = FreeSaleWithinprovince.objects.filter(trash=False).first()
        #         if free_sale_state and free_sale_state.allow:
        #             percent = (free_sale_state.percent - 10)/100
        #             govermental_quantity = percent * poultry_hatching.quantity
        #             govermental_poultry_requests = PoultryRequest.objects.filter(state_process__in=('pending','accepted'),province_state__in=('pending','accepted'),out=False,free_sale_in_province=False, trash=False, hatching=poultry_hatching)
        #             govermental_poultry_requests_sum = \
        #             govermental_poultry_requests.aggregate(total=Sum('quantity'))[
        #                 'total'] or 0
        #             if govermental_poultry_requests_sum < govermental_quantity:
        #                 return Response({"result": "امکان فروش آزاد تا تکمیل تعهد دولتی وجود ندارد!"},
        #                                 status=status.HTTP_403_FORBIDDEN)

        # Q(direct_buying=True) | Q(out=True, wage_pay=True) | Q(free_sale_in_province=True),
        # state_process='accepted', province_state='accepted', trash=False, hatching=poultry_hatching)

        if free_sale_with_province.allow == True:
            if ('out' in request.data.keys() and request.data['out'] == True) or (
                    'free_sale_in_province' in request.data.keys() and request.data['free_sale_in_province'] == True):
                poultry_requests_for_free_sale = PoultryRequest.objects.filter(
                    Q(direct_buying=True) | Q(out=True, wage_pay=True) | Q(free_sale_in_province=True),
                    state_process='accepted', province_state='accepted', trash=False, hatching=poultry_hatching)
                poultry_requests_for_free_sale_sum = poultry_requests_for_free_sale.aggregate(total=Sum('quantity'))[
                                                         'total'] or 0
                if poultry_requests_for_free_sale_sum + request.data[
                    'quantity'] > poultry_hatching.total_free_commitment_quantity:
                    return Response({"result": "مجموع  حجم کشتار آزاد از حجم کل تعهد  آزاد بیشتر است "},
                                    status=status.HTTP_403_FORBIDDEN)
        if 'role' in request.data.keys() and request.data['role'] not in ('AdminX', 'SuperAdmin'):

            age_range = ChickenAgeRange.objects.filter(trash=False).first()
            if age_range.active == True:
                chicken_age = (datetime.datetime.strptime(request.data['send_date'],
                                                          '%Y-%m-%d').date() - poultry_hatching.date.date()).days + 1
                if chicken_age < age_range.minimum or chicken_age > age_range.maximum:
                    return Response(
                        {"result": "به علت استاندارد نبودن سن مرغ برای کشتار امکان ثبت درخواست وجود ندارد!"},
                        status=status.HTTP_403_FORBIDDEN)
        if 'role' in request.data.keys():
            role = request.data['role']
            poultry_object = Poultry.objects.get(key=request.data['poultry_key'])
            request.data.pop('role')
            request.data.pop('poultry_key')
            if role == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                if city_operator.unit_name != poultry_object.city_operator:
                    poultry_city = poultry_object.city_operator
                    return Response({"result": "مرغدار زیر مجموعه {0} است !".format(poultry_city)},
                                    status=status.HTTP_403_FORBIDDEN)

        else:
            role = None
            poultry_object = None
        if 'operator_key' in request.data.keys():
            if request.data['operator_key'] == None or request.data['operator_key'] == "":
                c_operator = None

            else:
                c_operator = CityOperator.objects.get(key=request.data['operator_key'])
            request.data.pop('operator_key')
        else:
            c_operator = None
        auction_list = request.data['auction_list']
        request.data.pop('poultry_hatching_key')
        request.data.pop('auction_list')
        if auction_list != None:
            for auction in auction_list:
                pricing = Pricing.objects.get(key=auction['pricing_key'], trash=False)
                if pricing.ceiling_price < int(auction['fee']):
                    return Response({"result": "fee is more than celling price"}, status=status.HTTP_403_FORBIDDEN)
        if role != None:
            poultry = poultry_object
            user = SystemUserProfile.objects.get(key=poultry_object.user.key, trash=False)
        else:
            poultry = Poultry.objects.get(id=poultry_hatching.poultry.id, trash=False)
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
        poultry_requests = PoultryRequest.objects.filter(poultry__user=poultry.user, trash=False).order_by(
            'create_date')
        if poultry_hatching.left_over < int(request.data['quantity']) or poultry_hatching.left_over < int(
                request.data['quantity']) + int(request.data['losses']):
            return Response({"result": "تعداد درخواست از باقی مانده سالن بیشتر است!"}, status=status.HTTP_403_FORBIDDEN)

        cash = request.data['cash']
        credit = request.data['credit']
        request.data.pop('cash')
        request.data.pop('credit')
        dict1 = {}
        new_date = datetime.datetime.strptime(request.data['send_date'], '%Y-%m-%d').date()
        change_date = datetime.datetime(year=new_date.year, month=new_date.month, day=new_date.day, hour=now.hour,
                                        minute=now.minute,
                                        second=now.second)
        request.data.pop('send_date')
        if 'out_province_poultry_request_buyer_key' in request.data.keys():
            if request.data['out_province_poultry_request_buyer_key'] != None:
                request_buyer = OutProvincePoultryRequestBuyer.objects.get(
                    key=request.data['out_province_poultry_request_buyer_key'])
                out_province_request_limitation = PoultryOutProvinceRequest.objects.filter(trash=False).first()
                if role and role not in ('AdminX', 'SuperAdmin'):
                    if out_province_request_limitation:
                        if out_province_request_limitation.allow:
                            out_poultry_requests = PoultryRequest.objects.filter(trash=False, out=True,
                                                                                 hatching=poultry_hatching,
                                                                                 out_province_request_cancel=False,
                                                                                 state_process__in=(
                                                                                     'pending', 'accepted'),
                                                                                 province_state__in=(
                                                                                     'pending', 'accepted'))
                            out_poultry_requests_quantity = out_poultry_requests.aggregate(total=Sum('quantity'))[
                                                                'total'] or 0
                            if poultry_hatching.quantity * (
                                    out_province_request_limitation.limitation / 100) < out_poultry_requests_quantity + \
                                    request.data['quantity']:
                                return Response(
                                    {"result": " تعداد وارد شده بیشتر از ظرفیت فروش به خارج استان برای مرغدار است ! "},
                                    status=status.HTTP_403_FORBIDDEN)
            # request.data.pop('out_province_poultry_request_buyer_key')
            if wage_type and wage_type.status == False:
                request.data.pop('payer_type')
                request.data.pop('poultry_mobile')
                request.data.pop('buyer_mobile')

            else:
                if 'poultry_mobile' in request.data.keys() and request.data['poultry_mobile'] is not None:
                    if poultry_hatching.poultry.user.mobile != request.data['poultry_mobile']:
                        first_mobile_number = poultry_hatching.poultry.user.mobile
                        second_mobile_number = request.data['poultry_mobile']
                        system_user_profile = SystemUserProfile.objects.get(mobile=first_mobile_number, trash=False)
                        poultry_user = User.objects.get(id=system_user_profile.user.id)

                        if SystemUserProfile.objects.filter(mobile=second_mobile_number, trash=False).exists():
                            return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                            status=status.HTTP_403_FORBIDDEN)
                        data = {
                            "first_mobile_number": first_mobile_number,
                            "second_mobile_number": second_mobile_number,
                        }
                        req = requests.post(
                            url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                            data=data,
                            verify=False
                        )
                        if req.status_code == 200:
                            poultry_user.username = second_mobile_number
                            user.save()
                            system_user_profile.mobile = second_mobile_number
                            system_user_profile.save()
                elif 'buyer_mobile' in request.data.keys() and request.data['buyer_mobile'] is not None:
                    if request_buyer.user.mobile != request.data['buyer_mobile']:
                        first_mobile_number = request_buyer.user.mobile
                        second_mobile_number = request.data['buyer_mobile']
                        system_user_profile = SystemUserProfile.objects.get(mobile=first_mobile_number, trash=False)
                        buyer_user = User.objects.get(id=system_user_profile.user.id)

                        if SystemUserProfile.objects.filter(mobile=second_mobile_number, trash=False).exists():
                            return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                            status=status.HTTP_403_FORBIDDEN)
                        data = {
                            "first_mobile_number": first_mobile_number,
                            "second_mobile_number": second_mobile_number,
                        }
                        req = requests.post(
                            url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                            data=data,
                            verify=False
                        )
                        if req.status_code == 200:
                            buyer_user.username = second_mobile_number
                            user.save()
                            system_user_profile.mobile = second_mobile_number
                            system_user_profile.save()
                            request_buyer.mobile = second_mobile_number
                            request_buyer.save()
                request.data.pop('poultry_mobile')
                request.data.pop('buyer_mobile')

            request.data.pop('out_province_poultry_request_buyer_key')

        if 'confirm_poultry_mobile' in request.data.keys():
            if request.data.get('confirm_poultry_mobile') != "":
                first_mobile_number = poultry.user.mobile
                second_mobile_number = request.data['confirm_poultry_mobile']
                if first_mobile_number != second_mobile_number:
                    system_user_profile = SystemUserProfile.objects.get(mobile=first_mobile_number, trash=False)
                    system_person = SystemUserProfile.objects.filter(mobile=second_mobile_number, trash=False)
                    if system_person:
                        return Response({"result": f'این شماره در سامانه به نام {system_person.first().fullname} است'},
                                        status=status.HTTP_403_FORBIDDEN)
                    data = {
                        "first_mobile_number": first_mobile_number,
                        "second_mobile_number": second_mobile_number,
                    }
                    req = requests.post(
                        url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                        data=data,
                        verify=False
                    )
                    if req.status_code == 200:
                        system_user_profile.user.username = second_mobile_number
                        system_user_profile.user.save()
                        system_user_profile.mobile = second_mobile_number
                        system_user_profile.save()
            request.data.pop('confirm_poultry_mobile')
        if 'traffic_codes' in request.data:
            traffic_codes = request.data.get('traffic_codes', [])
            request.data.pop('traffic_codes')
        if 'market' in request.data and request.data['market']:
            if MarketDailyLimitation.objects.filter(active=True).exists():
                market_result = market_daily_limitation_info()
                if request.data['quantity'] > market_result['remain_quantity']:
                    return Response({"result": "تعداد وارد شده از باقی مانده سقف کشتار معاملات بیشتر است!"},
                                    status=status.HTTP_403_FORBIDDEN)

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            poultry_request = serializer.create(validated_data=request.data)
            price_confirmation = PriceConfirmation.objects.filter(trash=False).first()
            price_confirmation = price_confirmation.poultry_status if price_confirmation else False

            poultry_request.general_order_code = general_order_code
            poultry_request.send_date = change_date
            poultry_request.killing_age = (poultry_request.send_date.date() - poultry_hatching.date.date()).days + 1
            if request_buyer != None:
                poultry_request.out_province_poultry_request_buyer = request_buyer
                poultry_request.buyer_mobile = request_buyer.mobile
                poultry_request.buyer_fullname = request_buyer.fullname
                poultry_request.buyer_city = request_buyer.city
                poultry_request.buyer_province = request_buyer.province
            if int(poultry_request.losses) > 0:
                poultry_hatching.losses += int(poultry_request.losses)
            poultry_hatching.save()
            poultry_request.poultry = poultry
            poultry_request.hatching = poultry_hatching
            if vet:
                poultry_request.vet_farm = vet.vet
            city = poultry.address.city.name
            city_unit = CityUnit.objects.filter(name=city, trash=False)
            if c_operator != None:
                main_operator = c_operator.user.first_name + " " + c_operator.user.last_name
                city_operator_user = c_operator

            else:
                if city_unit.count() > 0:
                    city_operator_user = CityOperator.objects.filter(address__city__name=city_unit[0].city.name,
                                                                     trash=False)
                    if city_operator_user.count() > 0:
                        city_operator_user = city_operator_user.last()
                    else:
                        city_operator_user = CityOperator.objects.filter(address__city__province_center=True,
                                                                         trash=False)
                        city_operator_user = city_operator_user.last()

                else:
                    city_operator_user = CityOperator.objects.filter(address__city__name=city, trash=False)
                    if city_operator_user.count() > 0:
                        city_operator_user = city_operator_user.last()
                    else:
                        city_operator_user = CityOperator.objects.filter(address__city__province_center=True,
                                                                         trash=False)
                        city_operator_user = city_operator_user.last()

                main_operator = city_operator_user.user.first_name + " " + city_operator_user.user.last_name
            poultry_request.state = {
                "city_operator": main_operator,
                "city_state": poultry_request.state_process,
                "city_operator_mobile": city_operator_user.user.mobile,
                "province_operator": "",
                "province_state": ""
            }

            if poultry_requests.count() > 0:
                poultry_request.order_code = poultry_requests.last().order_code + 1
            else:
                poultry_request.order_code = int(str(user.base_order) + '0001')

            poultry_request.save()
            if len(auction_list) > 0:
                for auction in auction_list:
                    poultry_request_auction = PoultryRequestAuction(
                        poultry_request=poultry_request,
                        pricing=Pricing.objects.all().last(),
                        fee=auction['fee'],
                        hour=auction['hour']
                    )
                    poultry_request_auction.save()
            dict1.update({
                'cash': cash,
                'credit': credit
            })
            poultry_request.cell_type = dict1
            poultry_request.city_operator = city_operator_user
            if role != None:
                system_user = SystemUserProfile.objects.get(user=request.user, trash=False)
                poultry_request.registrar = {
                    "role": role,
                    "fullname": system_user.fullname,
                    "date": str(poultry_request.create_date)
                }
            if poultry_request.out_province_poultry_request_buyer != None:
                poultry_request.out = True
                # if role != None and role == 'ProvinceOperator':
                #     poultry_request.state_process = 'accepted'
                #     poultry_request.province_state = 'accepted'
                #     poultry_request.final_state = 'archive'
            poultry_request.previous_quantity = int(request.data['quantity'])
            poultry_request.remain_quantity = int(request.data['quantity'])
            poultry_request.first_quantity = int(request.data['quantity'])
            poultry_request.save()

            message = UserMessage(message="درخواست شما با کد سفارش {0} در انتطار تایید کارشناس شهرستان/{1}".format(
                poultry_request.order_code, main_operator))
            message.save()
            message.users.add(user)
            vet_farm = VetFarm.objects.filter(poultry=poultry_hatching.poultry, hall=poultry_hatching.hall,
                                              state='pending')
            if vet_farm.count() > 0:
                vet_farm = vet_farm.last()
                inspections = VetFarmInspection.objects.filter(vet_farm=vet_farm, hall=vet_farm.hall,
                                                               state='pending')
                for inspection in inspections:
                    inspection.state = 'complete'
                    inspection.save()
                vet_farm.save()
            if SmsLicense.objects.filter(poultry_request=True).exists():
                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()
                poultry_fullname = poultry_request.poultry.unit_name
                poultry_mobile = poultry_request.poultry.user.mobile
                quantity = poultry_request.quantity
                chicken_breed = poultry_request.chicken_breed
                order_code = poultry_request.order_code
                request_kill_house = poultry_request.kill_house_list[0] if poultry_request.kill_house_list else "-"
                date_str = poultry_request.send_date
                send_date = datetime.datetime.strptime(str(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)
                province_operator_mobile = province_operator.user.mobile

                sms_operator_poultry_request_sms = threading.Thread(target=operator_poultry_request_sms,
                                                                    args=(
                                                                        province_operator_mobile, poultry_fullname,
                                                                        quantity, chicken_breed,
                                                                        order_code, send_date,
                                                                        poultry_request.free_sale_in_province,
                                                                        poultry_request.amount, request_kill_house,
                                                                        poultry_mobile))
                sms_operator_poultry_request_sms.start()

                if poultry_request.out_province_poultry_request_buyer != None:
                    vet = VetFarm.objects.filter(trash=False, poultry=poultry_request.poultry).first()
                    vet_number = vet.vet.user.mobile if vet else None
                    if wage_type and wage_type.status == False:
                        sms_operator_out_poultry_request_sms = threading.Thread(target=operator_out_poultry_request_sms,
                                                                                args=(
                                                                                    province_operator_mobile,
                                                                                    poultry_fullname,
                                                                                    quantity, chicken_breed,
                                                                                    order_code, send_date,
                                                                                    poultry_request.free_sale_in_province,
                                                                                    poultry_request.amount,
                                                                                    vet_number
                                                                                ))
                        sms_operator_out_poultry_request_sms.start()

            if role != None and role == 'ProvinceOperator' and poultry_request.out == False:

                city_operator_check_request = CityOperatorCheckRequest(
                    city_operator_system=poultry_request.city_operator,
                    poultry_request=poultry_request,
                    state='accept',
                    province_accept=True,
                    province_state='accept',
                    allow_hatching=True

                )
                city_operator_check_request.save()
                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=poultry_request,
                        city_request_Poultry=city_operator_check_request,
                        quantity=poultry_request.quantity,

                        state='accept',
                    )
                    check.save()
                    poultry_request.state_process = 'accepted'
                    poultry_request.province_state = 'accepted'
                if poultry_request.city_operator.address.city.name == 'فاقد شهرستان':
                    poultry_request.archive = True
                poultry_request.save()

            elif role != None and role == 'CityOperator' and poultry_request.out == False:

                city_operator_check_request = CityOperatorCheckRequest(
                    city_operator_system=poultry_request.city_operator,
                    poultry_request=poultry_request,
                    state='accept',
                    province_accept=False,
                    province_state='pending',
                    allow_hatching=True

                )
                city_operator_check_request.save()
                poultry_request.state_process = 'accepted'
                if poultry_request.city_operator.address.city.name == 'فاقد شهرستان':
                    poultry_request.archive = True
                poultry_request.save()
            else:
                if poultry_request.city_operator.address.city.name == 'فاقد شهرستان':
                    city_operator_check_request = CityOperatorCheckRequest(
                        city_operator_system=poultry_request.city_operator,
                        poultry_request=poultry_request,
                        state='accept',
                        province_accept=False,
                        province_state='pending',
                        allow_hatching=True

                    )
                    city_operator_check_request.save()
                    if poultry_request.city_operator.address.city.name == 'فاقد شهرستان':
                        poultry_request.archive = True
                    poultry_request.state_process = 'accepted'
                    poultry_request.save()
            if poultry_request.out == True:
                if wage_type and wage_type.status == True:
                    poultry_request.has_wage = True
                    if poultry_request.payer_type == 'buyer':
                        poultry_request.payer_fullname = poultry_request.out_province_poultry_request_buyer.fullname
                    else:
                        poultry_request.payer_fullname = poultry_request.poultry.user.fullname
                    poultry_request.save()
                    wage = wage_type.amount
                    poultry_request.wage = wage
                    percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0,
                                                                                trash=False)

                    if percentages_wage_type:
                        poultry_request.total_wage_amount = int(
                            (poultry_request.Index_weight * poultry_request.quantity) * wage)
                        # fine = FinePermission.objects.filter(trash=False).first()
                        # time_for_fine = datetime.datetime.now()
                        # time_for_fine = time_for_fine.replace(second=0, microsecond=0).time()
                        # if fine.out_poultry_request:
                        #     if fine.out_poultry_request_start_time < time_for_fine < fine.out_poultry_request_end_time:
                        #         poultry_request.fine = True
                        #         poultry_request.fine_amount = fine.out_poultry_request_fine_coefficient  * poultry_request.total_wage_amount
                        #         poultry_request.fine_coefficient = fine.out_poultry_request_fine_coefficient

                        for percentage_wage_type in percentages_wage_type:
                            if percentage_wage_type.share_type.en_name == 'union':
                                poultry_request.union_share = int(
                                    (percentage_wage_type.percent / 100) * poultry_request.total_wage_amount)
                                poultry_request.union_share_percent = percentage_wage_type.percent
                                poultry_request.save()
                            elif percentage_wage_type.share_type.en_name == 'company':
                                poultry_request.company_share = int(
                                    (percentage_wage_type.percent / 100) * poultry_request.total_wage_amount)
                                poultry_request.company_share_percent = percentage_wage_type.percent
                                poultry_request.save()

                            elif percentage_wage_type.share_type.en_name == 'guilds':
                                poultry_request.guilds_share = int(
                                    (percentage_wage_type.percent / 100) * poultry_request.total_wage_amount)
                                poultry_request.guilds_share_percent = percentage_wage_type.percent
                                poultry_request.save()
                            elif percentage_wage_type.share_type.en_name == 'city':
                                poultry_request.city_share = int(
                                    (percentage_wage_type.percent / 100) * poultry_request.total_wage_amount)
                                poultry_request.city_share_percent = percentage_wage_type.percent
                                poultry_request.save()

                            elif percentage_wage_type.share_type.en_name == 'wallet':
                                poultry_request.wallet_share = int(
                                    (percentage_wage_type.percent / 100) * poultry_request.total_wage_amount)
                                poultry_request.wallet_share_percent = percentage_wage_type.percent
                                poultry_request.save()

                            else:
                                poultry_request.other_share = int(
                                    (percentage_wage_type.percent / 100) * poultry_request.total_wage_amount)
                                poultry_request.other_share_percent = percentage_wage_type.percent
                                poultry_request.save()
            # poultry_prediction(poultry_hatching.poultry)

            if price_confirmation and not poultry_request.out:
                poultry_fullname = poultry_request.poultry.unit_name
                poultry_mobile = poultry_request.poultry.user.mobile
                quantity = poultry_request.quantity
                chicken_breed = poultry_request.chicken_breed
                order_code = poultry_request.order_code
                request_kill_house = poultry_request.kill_house_list[0] if poultry_request.kill_house_list else "-"
                date_str = poultry_request.send_date
                send_date = datetime.datetime.strptime(str(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)

                # poultry_fullname = poultry_request.poultry.unit_name
                # poultry_mobile = poultry_request.poultry.user.mobile
                # quantity = poultry_request.quantity
                # chicken_breed = poultry_request.chicken_breed
                # date_str = poultry_request.send_date
                # send_date = datetime.datetime.strptime(str(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)
                # confirm_code = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
                confirm_code = str(random.randint(10000, 99000))
                confirm_price_poultry_request = threading.Thread(target=confirm_price_poultry_request_sms,
                                                                 args=(
                                                                     poultry_mobile, poultry_fullname,
                                                                     quantity, chicken_breed,
                                                                     order_code, send_date,
                                                                     poultry_request.free_sale_in_province,
                                                                     poultry_request.amount, request_kill_house,
                                                                     confirm_code))
                confirm_price_poultry_request.start()
                poultry_request.price_confirmation_code = confirm_code
                poultry_request.price_confirmation = True
                poultry_request.save()
            if poultry_request.market == True:
                send_sms_for_poultry_market(poultry_request)
            create_update_chicken_commission_prices()

            if traffic_codes and isinstance(traffic_codes, list):
                codes_to_create = []
                now = datetime.datetime.now()
                for traffic_code in traffic_codes:
                    if traffic_code and str(traffic_code).strip():
                        codes_to_create.append(
                            PoultryRequestQuarantineCode(
                                poultry_request=poultry_request,
                                traffic_code=str(traffic_code).strip(),
                                registrar=user.fullname,
                                register_date=now
                            )
                        )

                if codes_to_create:
                    PoultryRequestQuarantineCode.objects.bulk_create(codes_to_create)

            serializer_request = self.serializer_class(poultry_request)
            return Response(serializer_request.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    # تابع مربوط به ویرایش درخواست ثبت شده مرغدار
    def update(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)

        if 'confirmation_code' in request.data.keys():
            poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])
            if poultry_request.price_confirmation_code != request.data['confirmation_code']:
                return Response({"result": "کد وارد شده صحیح نمی باشد!"},
                                status=status.HTTP_403_FORBIDDEN)
            poultry_request.input_price_confirmation_code = request.data['confirmation_code']
            poultry_request.save()
            return Response({"result": "با موفقیت انجام شد!"},
                            status=status.HTTP_200_OK)

        if 'quarantine_code' in request.data.keys():
            poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])

            date_time_of_now = datetime.datetime.now().date()
            if OperationLimitation.objects.all().first().vet_farm_out_province_limitation == True:
                if date_time_of_now > poultry_request.send_date.date() + timedelta(days=1):
                    return Response(
                        {"result": "به علت مغایرت در تاریخ ثبت و تاریخ کشتار امکان ثبت اطلاعات وجود ندارد!"},
                        status=status.HTTP_403_FORBIDDEN)
            if PoultryRequest.objects.filter(quarantine_code=request.data['quarantine_code'], trash=False).exists():
                return Response({"result": "کد وارد شده تکراری میباشد!"}, status=status.HTTP_403_FORBIDDEN)

            poultry_request.quarantine_code = request.data['quarantine_code']
            poultry_request.quarantine_code_registrar = {
                "role": request.data['role'],
                "fullname": user.fullname,
                "mobile": user.mobile,
                "date": str(datetime.datetime.now().date()),
            }
            poultry_request.save()
            get_gid_poultry_request(poultry_request.id)
            return Response({"result": "با موفقیت ثیت شد"}, status=status.HTTP_200_OK)
        if 'edit' in request.data.keys():
            poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])
            request.data.pop('poultry_request_key')
            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
            if 'out_province_poultry_request_buyer_key' in request.data.keys():
                request_buyer = OutProvincePoultryRequestBuyer.objects.get(
                    key=request.data['out_province_poultry_request_buyer_key'])
                poultry_request.out_province_poultry_request_buyer = request_buyer
                poultry_request.buyer_mobile = request_buyer.mobile
                poultry_request.buyer_fullname = request_buyer.fullname
                poultry_request.buyer_city = request_buyer.city
                poultry_request.buyer_province = request_buyer.province
                request.data.pop('out_province_poultry_request_buyer_key')

            if 'quantity' in request.data.keys():
                if poultry_request.market:
                    if MarketDailyLimitation.objects.filter(active=True).exists():
                        market_result = market_daily_limitation_info()
                        if int(request.data['quantity']) > poultry_request.quantity:
                            diff_quantity = int(request.data['quantity']) - poultry_request.quantity

                            if diff_quantity > market_result['remain_quantity']:
                                return Response({"result": "تعداد وارد شده از باقی مانده سقف کشتار معاملات بیشتر است!"},
                                                status=status.HTTP_403_FORBIDDEN)

                if poultry_request.out:
                    out_province_request_limitation = PoultryOutProvinceRequest.objects.filter(trash=False).first()
                    if out_province_request_limitation:
                        if out_province_request_limitation.limitation_status:
                            out_poultry_requests = PoultryRequest.objects.filter(trash=False, out=True,
                                                                                 hatching=poultry_request.hatching,
                                                                                 out_province_request_cancel=False,
                                                                                 state_process__in=(
                                                                                     'pending', 'accepted'),
                                                                                 province_state__in=(
                                                                                     'pending', 'accepted')).exclude(
                                id=poultry_request.id)
                            out_poultry_requests_quantity = out_poultry_requests.aggregate(total=Sum('quantity'))[
                                                                'total'] or 0
                            if poultry_request.hatching.quantity * (
                                    out_province_request_limitation.limitation / 100) < out_poultry_requests_quantity + \
                                    int(request.data['quantity']):
                                return Response(
                                    {"result": " تعداد وارد شده بیشتر از ظرفیت فروش به خارج استان برای مرغدار است ! "},
                                    status=status.HTTP_403_FORBIDDEN)
                if int(request.data['quantity']) > poultry_request.quantity:
                    diffrent_quantity = int(request.data['quantity']) - poultry_request.quantity
                    if hatching.left_over < diffrent_quantity:
                        return Response({"result": "تعداد وارد شده از باقی مانده جوجه ریزی بیشتر است !"},
                                        status=status.HTTP_403_FORBIDDEN)
                    if poultry_request.out == True and poultry_request.province_state == 'accepted':
                        hatching.out_province_killed_quantity += diffrent_quantity
                        hatching.out_province_killed_weight += int(diffrent_quantity * poultry_request.Index_weight)
                        hatching.save()
                elif int(request.data['quantity']) < poultry_request.quantity:
                    if poultry_request.out == True and poultry_request.province_state == 'accepted':
                        diffrent_quantity = poultry_request.quantity - int(request.data['quantity'])

                        hatching.out_province_killed_quantity -= diffrent_quantity
                        hatching.out_province_killed_weight -= int(diffrent_quantity * poultry_request.Index_weight)
                        hatching.save()

                poultry_request.remain_quantity = int(request.data['quantity'])
                poultry_request.save()

            if 'poultry_mobile' in request.data.keys() and request.data['poultry_mobile'] is not None:
                if poultry_request.poultry.user.mobile != request.data['poultry_mobile']:
                    first_mobile_number = poultry_request.poultry.user.mobile
                    second_mobile_number = request.data['poultry_mobile']
                    system_user_profile = SystemUserProfile.objects.get(mobile=first_mobile_number, trash=False)
                    poultry_user = User.objects.get(id=system_user_profile.user.id)

                    if SystemUserProfile.objects.filter(mobile=second_mobile_number, trash=False).exists():
                        return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                        status=status.HTTP_403_FORBIDDEN)
                    data = {
                        "first_mobile_number": first_mobile_number,
                        "second_mobile_number": second_mobile_number,
                    }
                    req = requests.post(
                        url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                        data=data,
                        verify=False
                    )
                    if req.status_code == 200:
                        poultry_user.username = second_mobile_number
                        user.save()
                        system_user_profile.mobile = second_mobile_number
                        system_user_profile.save()
            elif 'buyer_mobile' in request.data.keys() and request.data['buyer_mobile'] is not None:
                if poultry_request.out_province_poultry_request_buyer.user.mobile != request.data['buyer_mobile']:
                    first_mobile_number = poultry_request.out_province_poultry_request_buyer.user.mobile
                    second_mobile_number = request.data['buyer_mobile']
                    system_user_profile = SystemUserProfile.objects.get(mobile=first_mobile_number, trash=False)
                    buyer_user = User.objects.get(id=system_user_profile.user.id)

                    if SystemUserProfile.objects.filter(mobile=second_mobile_number, trash=False).exists():
                        return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                        status=status.HTTP_403_FORBIDDEN)
                    data = {
                        "first_mobile_number": first_mobile_number,
                        "second_mobile_number": second_mobile_number,
                    }
                    req = requests.post(
                        url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                        data=data,
                        verify=False
                    )
                    if req.status_code == 200:
                        buyer_user.username = second_mobile_number
                        user.save()
                        system_user_profile.mobile = second_mobile_number
                        system_user_profile.save()
                        request_buyer = OutProvincePoultryRequestBuyer.objects.get(
                            key=poultry_request.out_province_poultry_request_buyer.key)
                        request_buyer.mobile = second_mobile_number
                        request_buyer.save()
            request.data.pop('poultry_mobile')
            request.data.pop('buyer_mobile')
            serializer = self.serializer_class(poultry_request)
            serializer.update(instance=poultry_request, validated_data=request.data)
            poultry_request.total_wage_amount = int(
                (poultry_request.Index_weight * poultry_request.quantity) * poultry_request.wage)
            poultry_request.save()
            union_percent = poultry_request.union_share_percent / 100 if poultry_request.union_share_percent > 0 else 0
            company_percent = poultry_request.company_share_percent / 100 if poultry_request.company_share_percent > 0 else 0
            guilds_percent = poultry_request.guilds_share_percent / 100 if poultry_request.guilds_share_percent > 0 else 0
            city_share_percent = poultry_request.city_share_percent / 100 if poultry_request.city_share_percent > 0 else 0
            wallet_share_percent = poultry_request.wallet_share_percent / 100 if poultry_request.wallet_share_percent > 0 else 0
            other_share_percent = poultry_request.other_share_percent / 100 if poultry_request.other_share_percent > 0 else 0
            poultry_request.union_share = int(union_percent * poultry_request.total_wage_amount)
            poultry_request.company_share = int(company_percent * poultry_request.total_wage_amount)
            poultry_request.guilds_share = int(guilds_percent * poultry_request.total_wage_amount)
            poultry_request.city_share = int(city_share_percent * poultry_request.total_wage_amount)
            poultry_request.wallet_share = int(wallet_share_percent * poultry_request.total_wage_amount)
            poultry_request.other_share = int(other_share_percent * poultry_request.total_wage_amount)
            poultry_request.save()
            return Response({"result": "با موفقیت وبرایش شد"}, status=status.HTTP_200_OK)
        quantity = 0
        last_check_quantity = 0
        province_kill_request_quantity = 0
        if 'state' in request.data.keys():
            state = request.data['state']
            request.data.pop('state')
        else:
            state = None
        poultry_request = PoultryRequest.objects.get(key=request.data["key"], trash=False)
        request.data.pop('key')
        province_check = ProvinceCheckOperatorRequest.objects.filter(poultry_request=poultry_request)
        if 'quantity' in request.data.keys() or 'allocated_number' in request.data.keys():
            if 'quantity' in request.data.keys():
                if poultry_request.out:
                    out_province_request_limitation = PoultryOutProvinceRequest.objects.filter(trash=False).first()
                    if out_province_request_limitation:
                        if out_province_request_limitation.limitation_status:
                            out_poultry_requests = PoultryRequest.objects.filter(trash=False, out=True,
                                                                                 hatching=poultry_request.hatching,
                                                                                 out_province_request_cancel=False,
                                                                                 state_process__in=(
                                                                                     'pending', 'accepted'),
                                                                                 province_state__in=(
                                                                                     'pending', 'accepted')).exclude(
                                id=poultry_request.id)
                            out_poultry_requests_quantity = out_poultry_requests.aggregate(total=Sum('quantity'))[
                                                                'total'] or 0
                            if poultry_request.hatching.quantity * (
                                    out_province_request_limitation.limitation / 100) < out_poultry_requests_quantity + \
                                    int(request.data['quantity']):
                                return Response(
                                    {"result": " تعداد وارد شده بیشتر از ظرفیت فروش به خارج استان برای مرغدار است ! "},
                                    status=status.HTTP_403_FORBIDDEN)
                quantity = int(request.data['quantity'])
                province_kill_requests = ProvinceKillRequest.objects.filter(
                    province_request__poultry_request=poultry_request, trash=False)
                if province_kill_requests.count() > 0:
                    for province_kill_request in province_kill_requests:
                        province_kill_request_quantity += province_kill_request.main_quantity
                    if quantity < province_kill_request_quantity:
                        return Response({"result": "درخواست کشتار شما کمتر از مجموع کل تخصیصات داده شده است!"},
                                        status=status.HTTP_403_FORBIDDEN)

                if (quantity - poultry_request.quantity) > poultry_request.hatching.left_over:
                    # if quantity > poultry_request.hatching.left_over + poultry_request.remain_quantity:
                    return Response({"result": "درخواست کشتار شما بزرگتر از کل مانده جوجه ریزی است!"},
                                    status=status.HTTP_403_FORBIDDEN)
                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:
                            if quantity > poultry_request.quantity:
                                if kill_request.remain_quantity_for_poultry + (
                                        quantity - poultry_request.quantity) > kill_request.kill_capacity:
                                    return Response(
                                        {"result": "مقدار وارد شده از باقی مانده اعلام نیاز کشتارگاه بیشتر است!"},
                                        status=status.HTTP_403_FORBIDDEN)
                                kill_request.remain_quantity_for_poultry += quantity - poultry_request.quantity
                            else:
                                kill_request.remain_quantity_for_poultry -= poultry_request.quantity - quantity

                            kill_request.save()


            else:
                quantity = request.data['allocated_number']
                request.data.pop('allocated_number')
                if quantity == 0:
                    quantity = poultry_request.quantity
                    poultry_request.final_state = request.data['final_state']
                else:
                    request.data.pop('final_state')
                if province_check.count() > 0:
                    province_check = province_check.last()
                    last_check_quantity += province_check.quantity
                    province_check.quantity = 0
                    province_check.save()

            poultry_request.previous_quantity = poultry_request.quantity
            if poultry_request.quantity > quantity:
                a = -1 * (poultry_request.quantity - quantity)
            else:
                a = quantity - poultry_request.quantity

            poultry_request.remain_quantity += a
            poultry_request.save()

            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
            if poultry_request.quantity - quantity == 0:
                if state != None:
                    pass
                else:
                    province_check = ProvinceCheckOperatorRequest.objects.filter(poultry_request=poultry_request)
                    if province_check.count() > 0:
                        province_check = province_check.last().quantity
                        if province_check == 0 and last_check_quantity > 0:
                            if poultry_request.quantity == last_check_quantity:
                                poultry_request.final_state = 'archive'
                                poultry_request.archive = True
                                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()
                            # hatching.left_over += last_check_quantity
                            hatching.save()

                        else:
                            pass
                    else:

                        poultry_request.final_state = 'archive'
                        poultry_request.archive = True
                        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()
                        # hatching.left_over += quantity

            else:
                if quantity > poultry_request.quantity:
                    # hatching.left_over -= quantity - poultry_request.quantity
                    # hatching.save()
                    if poultry_request.final_state != 'archive':
                        province_check = ProvinceCheckOperatorRequest.objects.filter(poultry_request=poultry_request)
                        if province_check.count() > 0:
                            province_check = province_check.last()
                            province_check.quantity += quantity - poultry_request.quantity
                            province_check.save()


                else:
                    # hatching.left_over += poultry_request.quantity - quantity
                    if poultry_request.final_state != 'archive':
                        province_check = ProvinceCheckOperatorRequest.objects.filter(poultry_request=poultry_request)
                        if province_check.count() > 0:
                            province_check = province_check.last()
                            if 'quantity' in request.data.keys():
                                # province_check.quantity = (poultry_request.quantity - quantity) - last_check_quantity
                                # last_province_quantity = province_check.quantity
                                if quantity < poultry_request.quantity:
                                    if province_check.quantity > 0:
                                        province_check.quantity -= poultry_request.quantity - quantity



                            else:
                                province_check.quantity = (poultry_request.quantity - quantity) - last_check_quantity
                            province_check.save()
            if hatching.left_over > 0:
                hatching.state = 'pending'
                hatching.allow_hatching = 'pending'
            hatching.save()
            poultry_request.quantity = quantity
            poultry_request.save()
        serializer = self.serializer_class(poultry_request)
        serializer.update(instance=poultry_request, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

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

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'role' in request.GET:
            if request.GET['role'] == 'Poultry':
                if 'waiting' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__user=user, awaiting_payment=True,
                                                             trash=False, out=False).order_by('-send_date')
                elif 'inspector' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__user=user, inspector='pending',
                                                             trash=False, out=False).order_by('-send_date')
                else:
                    now = datetime.datetime.now().date()

                    date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                                       '%Y-%m-%d').date() if 'date1' in request.GET else now
                    date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                                       '%Y-%m-%d').date() if 'date2' in request.GET else now

                    queryset_lists = PoultryRequest.objects.filter(poultry__user=user,
                                                                   final_state__in=('pending', 'archive'),
                                                                   trash=False, out=False).order_by('-send_date')
                    queryset = [
                        queryset_list for queryset_list in queryset_lists
                        if date1 <= queryset_list.send_date.date() <= date2
                    ]
            elif request.GET['role'] == 'VetSupervisor':

                if 'check' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                        if 'deleted_requests' in request.GET:

                            kill_house_requests = KillHouseRequest.objects.filter(
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                province_request__poultry_request__poultry__address__province=user.province,
                                trash=True,
                                message__isnull=False, temporary_trash=False, temporary_deleted=False
                            ).select_related('kill_request')
                            serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                            return Response(serializer.data, status=status.HTTP_200_OK)
                        else:
                            kill_house_requests = KillHouseRequest.objects.filter(
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                province_request__poultry_request__poultry__address__province=user.province,
                                trash=False
                            ).select_related('kill_request')

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

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

                        serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                        return Response(serializer.data, status=status.HTTP_200_OK)
            elif request.GET['role'] == 'VetFarm':
                vet = Vet.objects.filter(user=user, trash=False)
                poultries = []
                if vet.count() > 0:
                    vet = vet.last()
                    vet_farms = VetFarm.objects.filter(vet=vet, trash=False)
                    if vet_farms.count() > 0:
                        for vet_farm in vet_farms:
                            if vet_farm.poultry in poultries:
                                pass
                            else:
                                poultries.append(vet_farm.poultry)
                        if 'check' in request.GET:
                            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                            if 'deleted_requests' in request.GET:

                                kill_house_requests = KillHouseRequest.objects.filter(
                                    kill_request__recive_date__date__gte=date1,
                                    kill_request__recive_date__date__lte=date2,
                                    province_request__poultry_request__poultry__in=poultries,
                                    trash=True,
                                    message__isnull=False, temporary_trash=False, temporary_deleted=False
                                ).select_related('kill_request')
                                serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                                return Response(serializer.data, status=status.HTTP_200_OK)
                            else:
                                kill_house_requests = KillHouseRequest.objects.filter(
                                    kill_request__recive_date__date__gte=date1,
                                    kill_request__recive_date__date__lte=date2,
                                    province_request__poultry_request__poultry__in=poultries,
                                    trash=False
                                ).select_related('kill_request')

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

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

                            serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                            return Response(serializer.data, status=status.HTTP_200_OK)



                        elif 'waiting' in request.GET:
                            queryset = PoultryRequest.objects.filter(poultry__in=poultries,
                                                                     poultry__address__province=user.province,
                                                                     awaiting_payment=True,
                                                                     trash=False, out=False).order_by('send_date')
                        elif 'inspector' in request.GET:
                            queryset = PoultryRequest.objects.filter(poultry__in=poultries,
                                                                     poultry__address__province=user.province,
                                                                     inspector='pending',
                                                                     trash=False, out=False).order_by('send_date')
                        else:
                            queryset = PoultryRequest.objects.filter(poultry__in=poultries,
                                                                     poultry__address__province=user.province,
                                                                     final_state__in=('pending', 'archive'),
                                                                     trash=False, out=False).order_by('send_date')
                    else:
                        queryset = []

            elif request.GET['role'] == 'ProvinceInspector':
                if 'waiting' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             awaiting_payment=True,
                                                             trash=False, out=False).order_by('send_date')
                elif 'inspector' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             inspector='pending',
                                                             trash=False, out=False).order_by('send_date')
                # elif 'out' in request.GET:

                else:

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

                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             state_process__in=('pending', 'accepted'),
                                                             province_state__in=('pending', 'accepted'),
                                                             trash=False, out=False,
                                                             send_date__year=date.year, send_date__month=date.month,
                                                             send_date__day=date.day
                                                             ).order_by('-send_date')
            elif request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user)

                if 'check' in request.GET:

                    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                    if 'deleted_requests' in request.GET:

                        kill_house_requests = KillHouseRequest.objects.filter(
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            province_request__poultry_request__poultry__city_operator=city_operator.unit_name,
                            trash=True,
                            message__isnull=False, temporary_trash=False, temporary_deleted=False
                        ).select_related('kill_request')
                        serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                        return Response(serializer.data, status=status.HTTP_200_OK)
                    else:
                        kill_house_requests = KillHouseRequest.objects.filter(
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            province_request__poultry_request__poultry__city_operator=city_operator.unit_name,
                            trash=False
                        ).select_related('kill_request')

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

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

                    serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)



                # list1 = []
                # for c in CityUnit.objects.filter(city__name=user.city.name, trash=False):
                #     list1.append(c.name)
                elif 'waiting' in request.GET:
                    # queryset = PoultryRequest.objects.filter(poultry__address__city__name__in=list1,
                    #                                          awaiting_payment=True,
                    #                                          trash=False).order_by('send_date')

                    queryset = PoultryRequest.objects.filter(city_operator=city_operator,
                                                             awaiting_payment=True,
                                                             trash=False, out=False).order_by('send_date')
                elif 'inspector' in request.GET:
                    # queryset = PoultryRequest.objects.filter(poultry__address__city__name__in=list1,
                    #                                          inspector='pending',
                    #                                          trash=False).order_by('send_date')
                    queryset = PoultryRequest.objects.filter(city_operator=city_operator,
                                                             inspector='pending',
                                                             trash=False, out=False).order_by('send_date')
                else:
                    # queryset = PoultryRequest.objects.filter(poultry__address__city__name__in=list1,
                    #                                          trash=False).order_by(
                    #     'send_date')
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    if 'state' in request.GET:
                        if request.GET['state'] == 'pending':
                            queryset = PoultryRequest.objects.filter(poultry__city_operator=city_operator.unit_name,
                                                                     trash=False, out=False, state_process='pending',
                                                                     final_state='pending',
                                                                     send_date__date__gte=date1,
                                                                     send_date__date__lte=date2
                                                                     ).order_by('send_date')
                        elif request.GET['state'] == 'accepted':
                            queryset = PoultryRequest.objects.filter(poultry__city_operator=city_operator.unit_name,
                                                                     trash=False, out=False, state_process='accepted',
                                                                     final_state='pending',
                                                                     send_date__date__gte=date1,
                                                                     send_date__date__lte=date2
                                                                     ).order_by('send_date')
                    else:
                        queryset = PoultryRequest.objects.filter(poultry__city_operator=city_operator.unit_name,
                                                                 state_process__in=('pending', 'accepted'),
                                                                 province_state__in=('pending', 'accepted'),
                                                                 trash=False, out=False, final_state='pending',
                                                                 send_date__date__gte=date1, send_date__date__lte=date2
                                                                 ).order_by('send_date')

                    if 'search' in request.GET:
                        poultry_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 (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)
                    # queryset = [
                    #     poultry_req for poultry_req in queryset_list
                    #     if date1 <= poultry_req.send_date.date() <= date2
                    # ]
            elif request.GET['role'] == 'PoultryScience':
                poultry_science = PoultryScience.objects.filter(trash=False, user=user).values_list('poultry__id',
                                                                                                    flat=True).distinct()
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                queryset = PoultryRequest.objects.filter(poultry__id__in=poultry_science,
                                                         state_process__in=('pending', 'accepted'),
                                                         province_state__in=('pending', 'accepted'),
                                                         trash=False, out=False, final_state='pending',
                                                         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)

            elif request.GET['role'] in ['CityCommerce', 'CityVet', 'CityPoultry', 'CityJahad']:

                if 'check' in request.GET:

                    if 'date1' in request.GET and 'date2' in request.GET:

                        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

                        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                        if 'deleted_requests' in request.GET:

                            kill_house_requests = KillHouseRequest.objects.filter(

                                kill_request__recive_date__date__gte=date1,

                                kill_request__recive_date__date__lte=date2,

                                province_request__poultry_request__poultry__address__city=user.city,

                                trash=True,

                                message__isnull=False, temporary_trash=False, temporary_deleted=False

                            ).select_related('kill_request')

                            serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)

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

                        else:

                            kill_house_requests = KillHouseRequest.objects.filter(

                                kill_request__recive_date__date__gte=date1,

                                kill_request__recive_date__date__lte=date2,

                                province_request__poultry_request__poultry__address__city=user.city,

                                trash=False

                            ).select_related('kill_request')

                        page_size = request.query_params.get('page_size', None)

                        if page_size:
                            self.pagination_class.page_size = int(page_size)

                        page = self.paginate_queryset(kill_house_requests)

                        if page is not None:
                            serializer = KillHouseRequestForBarManagementSerializer(page, many=True)

                            return self.get_paginated_response(serializer.data)

                        serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)

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

                elif 'date1' in request.GET and 'date2' in request.GET:

                    now = datetime.datetime.now().date()

                    date1 = datetime.datetime.strptime(str(request.GET['date1']),

                                                       '%Y-%m-%d').date() if 'date1' in request.GET else now

                    date2 = datetime.datetime.strptime(str(request.GET['date2']),

                                                       '%Y-%m-%d').date() if 'date2' in request.GET else now

                    if 'state_process' in request.GET:

                        queryset = PoultryRequest.objects.filter(poultry__address__city=user.city,

                                                                 trash=False, state_process='pending', out=False,

                                                                 send_date__date__gte=date1, send_date__date__lte=date2

                                                                 ).order_by('-send_date')

                    else:

                        poultry_requests = []

                        queryset = PoultryRequest.objects.filter(poultry__address__city=user.city,

                                                                 state_process__in=('pending', 'accepted'),

                                                                 province_state__in=('pending', 'accepted'),

                                                                 final_state='pending',

                                                                 trash=False, 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)

            elif request.GET['role'] == 'ProvinceFinancial':
                if 'waiting' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             awaiting_payment=True,
                                                             trash=False, out=False).order_by('send_date')
                elif 'inspector' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             inspector='pending',
                                                             trash=False, out=False).order_by('send_date')
                elif 'all' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             assignment=True,
                                                             final_state='pending',
                                                             trash=False, out=False).order_by('send_date')
                else:
                    if 'date' in request.GET:
                        date = datetime.datetime.strptime(request.GET['date'], '%Y-%m-%d')
                    else:
                        date = datetime.datetime.now()

                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             state_process__in=('pending', 'accepted'),
                                                             province_state__in=('pending', 'accepted'),
                                                             trash=False, out=False,
                                                             send_date__year=date.year, send_date__month=date.month,
                                                             send_date__day=date.day
                                                             ).order_by('-send_date')
            elif request.GET['role'] in ['ProvinceOperator', 'Commerce', 'SuperAdmin', 'AdminX', 'Supporter']:
                if 'waiting' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             awaiting_payment=True,
                                                             trash=False, out=False).order_by('send_date')
                elif 'inspector' in request.GET:
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             inspector='pending',
                                                             trash=False, out=False).order_by('send_date')
                elif 'out' in request.GET:
                    # if 'date' in request.GET:
                    #     date = datetime.datetime.strptime(request.GET['date'], '%Y-%m-%d')
                    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    # else:
                    #     date = datetime.datetime.now()
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             send_date__date__gte=date1,
                                                             send_date__date__lte=date2,
                                                             trash=False, out=True).order_by('-send_date')
                elif 'check' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                        if 'deleted_requests' in request.GET:

                            kill_house_requests = KillHouseRequest.objects.filter(
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                province_request__poultry_request__poultry__address__province=user.province,
                                trash=True,
                                message__isnull=False, temporary_trash=False, temporary_deleted=False
                            ).select_related('kill_request')
                            # serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                            # return Response(serializer.data, status=status.HTTP_200_OK)
                            page_size = request.query_params.get('page_size', None)
                            if page_size:
                                self.pagination_class.page_size = int(page_size)

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

                            serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                            return Response(serializer.data, status=status.HTTP_200_OK)
                        else:
                            kill_house_requests = KillHouseRequest.objects.filter(
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                province_request__poultry_request__poultry__address__province=user.province,
                                trash=False
                            ).select_related('kill_request')

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

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

                        serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                        return Response(serializer.data, status=status.HTTP_200_OK)

                elif 'date1' in request.GET and 'date2' in request.GET:

                    now = datetime.datetime.now().date()
                    date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                                       '%Y-%m-%d').date() if 'date1' in request.GET else now
                    date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                                       '%Y-%m-%d').date() if 'date2' in request.GET else now
                    if 'state_process' in request.GET:
                        queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                                 trash=False, state_process='pending', out=False,
                                                                 send_date__date__gte=date1, send_date__date__lte=date2
                                                                 ).order_by('-send_date')
                    else:
                        poultry_requests = []
                        queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                                 state_process__in=('pending', 'accepted'),
                                                                 province_state__in=('pending', 'accepted'),
                                                                 final_state='pending',
                                                                 trash=False, 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)

                    # queryset = [
                    #     queryset_list for queryset_list in queryset_lists
                    #     if date1 <= queryset_list.send_date.date() <= date2
                    # ]

                    # date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    # date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    # queryset_list = PoultryRequest.objects.filter(poultry__address__province=user.province,
                    #                                               trash=False, out=False,
                    #                                               ).order_by('-send_date')
                    #
                    # queryset = []
                    # queryset = [
                    #     poultry_req for poultry_req in queryset_list
                    #     if date1 <= poultry_req.send_date.date() <= date2
                    # ]
                else:
                    if 'date' in request.GET:
                        date = datetime.datetime.strptime(request.GET['date'], '%Y-%m-%d')
                    else:
                        date = datetime.datetime.now() - timedelta(days=2)

                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             state_process__in=('pending', 'accepted'),
                                                             province_state__in=('pending', 'accepted'),
                                                             trash=False, out=False,
                                                             send_date__year__gte=date.year,
                                                             send_date__month__gte=date.month,
                                                             send_date__day__gte=date.day
                                                             ).order_by('-send_date')

            elif request.GET['role'] == 'KillHouse':
                kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                if 'check' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                        if 'deleted_requests' in request.GET:

                            kill_house_requests = KillHouseRequest.objects.filter(
                                (Q(killhouse_user__in=kill_house) | Q(
                                    kill_request__slaughter_house__in=kill_house)),
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                province_request__poultry_request__poultry__address__province=user.province,
                                trash=True,
                                message__isnull=False, temporary_trash=False, temporary_deleted=False
                            ).select_related('kill_request')
                            # serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                            # return Response(serializer.data, status=status.HTTP_200_OK)
                            page_size = request.query_params.get('page_size', None)
                            if page_size:
                                self.pagination_class.page_size = int(page_size)

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

                            serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                            return Response(serializer.data, status=status.HTTP_200_OK)
                        else:
                            kill_house_requests = KillHouseRequest.objects.filter(
                                (Q(killhouse_user__in=kill_house) | Q(
                                    kill_request__slaughter_house__in=kill_house)),
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                province_request__poultry_request__poultry__address__province=user.province,
                                trash=False
                            ).select_related('kill_request')

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

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

                        serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True)
                        return Response(serializer.data, status=status.HTTP_200_OK)

                # if 'check' in request.GET:
                #     kill_house_req_dict = {}
                #     kill_house_req_list = []
                #     bar_remover = None
                #
                #     now = datetime.datetime.now().date()
                #     date1 = datetime.datetime.strptime(str(request.GET['date1']),
                #                                        '%Y-%m-%d').date() if 'date1' in request.GET else now
                #     date2 = datetime.datetime.strptime(str(request.GET['date2']),
                #                                        '%Y-%m-%d').date() if 'date2' in request.GET else now
                #     queryset_list = PoultryRequest.objects.filter(
                #         poultry__address__province=user.province,
                #         final_state__in=('pending', 'archive'),
                #         trash=False, out=False,
                #     ).order_by('-send_date')
                #
                #     queryset = []
                #     queryset = [
                #         poultry_req for poultry_req in queryset_list
                #         if date1 <= poultry_req.send_date.date() <= date2
                #     ]
                #     if len(queryset) > 0:
                #         for poultry_req in queryset:
                #             vet_farm = VetFarm.objects.filter(poultry=poultry_req.poultry)
                #             if vet_farm.count() > 0:
                #                 vet_farm = vet_farm.last()
                #                 vet_name = vet_farm.vet.user.fullname
                #                 vet_mobile = vet_farm.vet.user.mobile
                #             else:
                #                 vet_name = None
                #                 vet_mobile = None
                #             if 'deleted_requests' in request.GET:
                #                 kill_house_requests = KillHouseRequest.objects.filter(
                #                     province_kill_request__province_request__poultry_request=poultry_req,
                #                     killhouse_user__in=kill_house, trash=True,
                #                     message__isnull=False)
                #             else:
                #                 kill_house_requests = KillHouseRequest.objects.filter(
                #                     province_kill_request__province_request__poultry_request=poultry_req,
                #                     killhouse_user__in=kill_house, trash=False)
                #             if kill_house_requests.count() > 0:
                #                 for kill_house_request in kill_house_requests:
                #                     kill_house_name = kill_house_request.kill_request.kill_house.name
                #                     if kill_house_request.kill_request.slaughter_house:
                #                         kill_place = kill_house_request.kill_request.slaughter_house.name
                #                     else:
                #                         kill_place = kill_house_name
                #
                #                     if kill_house_request.bar_remover != None:
                #                         bar_remover = kill_house_request.bar_remover
                #                     vet_check = VetCheckRequest.objects.filter(
                #                         kill_house_request=kill_house_request)
                #                     if vet_check.count() > 0:
                #                         vet_check_state = vet_check.last().state
                #                     else:
                #                         vet_check_state = 'pending'
                #
                #                     kill_house_req_dict.update({
                #                         "poultry_req_key": poultry_req.key,
                #                         "poultry_req_order_code": poultry_req.order_code,
                #                         "poultry_name": poultry_req.poultry.unit_name,
                #                         "poultry_mobile": poultry_req.poultry.user.mobile,
                #                         "poultry_city": poultry_req.poultry.address.city.name,
                #                         "chicken_breed": poultry_req.chicken_breed,
                #                         "date": poultry_req.send_date,
                #                         "poultry_request_first_quantity": kill_house_request.quantity,
                #                         "poultry_request_final_quantity": kill_house_request.quantity,
                #                         "clearance_code": kill_house_request.clearance_code,
                #                         "traffic_code": kill_house_request.traffic_code,
                #                         "kill_house_name": kill_house_name,
                #                         "buyer_mobile": kill_house_request.kill_request.kill_house.kill_house_operator.user.mobile,
                #                         "driver_mobile": kill_house_request.add_car.driver.driver_mobile,
                #                         "kill_house_request_key": kill_house_request.key,
                #                         "registerar": kill_house_request.registrar_clearance_code,
                #                         "bar_code": kill_house_request.bar_code,
                #                         "health_code": kill_house_request.add_car.driver.health_code,
                #                         "message": kill_house_request.message,
                #                         "date_of_reject": kill_house_request.modify_date,
                #                         "vet_name": vet_name,
                #                         "vet_mobile": vet_mobile,
                #                         "driver_name": kill_house_request.add_car.driver.driver_name,
                #                         "pelak": kill_house_request.add_car.driver.pelak,
                #                         "type_car": kill_house_request.add_car.driver.type_car,
                #                         "quantity": kill_house_request.add_car.driver.type_car,
                #                         "vet_check_state": vet_check_state,
                #                         "bar_remover": bar_remover,
                #                         "kill_place": kill_place,
                #
                #                     })
                #                     kill_house_req_list.append(kill_house_req_dict)
                #                     kill_house_req_dict = {}
                #
                #         return Response(kill_house_req_list, status=status.HTTP_200_OK)

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

                queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                         state_process__in=('pending', 'accepted'),
                                                         province_state__in=('pending', 'accepted'),
                                                         trash=False, out=False,
                                                         send_date__year=date.year, send_date__month=date.month,
                                                         send_date__day=date.day
                                                         ).order_by('-send_date')

        else:

            if 'type' in request.GET:
                if request.GET['type'] == 'auction':
                    queryset = []
                    poultry_req_auctions = PoultryRequestAuction.objects.filter(state='active',
                                                                                trash=False).order_by(
                        'fee').order_by(
                        'create_date')
                    for poultry_req_auction in poultry_req_auctions:
                        queryset.append(
                            PoultryRequest.objects.get(id=poultry_req_auction.poultry_request.id, auction=True))

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

    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        queryset = PoultryRequest.objects.get(id=pk, trash=False)
        if queryset.province_state == 'accepted':
            role = Group.objects.get(name='ProvinceOperator')
            if role not in user.role.all():
                return Response({"result": " بدلیل تایید درخواست از طرف استان امکان حذف وجود ندارد!"},
                                status=status.HTTP_400_BAD_REQUEST)
        if ProvinceKillRequest.objects.filter(province_request__poultry_request=queryset, trash=False,
                                              ).exists():
            return Response({"result": " بدلیل وجود تخصیص به کشتارگاه امکان حذف وجود ندارد!"},
                            status=status.HTTP_400_BAD_REQUEST)

        # if queryset.state_process == 'pending' and queryset.province_state == 'pending':
        #
        #
        #     # if 'role' in request.GET:
        #     #     if request.GET['role'] == 'ProvinceOperator':
        #
        #     hatching = queryset.hatching
        #     hatching.left_over += queryset.quantity + queryset.losses
        #     hatching.losses -= queryset.losses
        #     hatching.state = 'pending'
        #     hatching.save()
        #     try:
        #         city = CityOperatorCheckRequest.objects.get(poultry_request=queryset, trash=False)
        #         city.trash = True
        #         city.save()
        #     except:
        #         pass
        #     queryset.trash = True
        #     queryset.save()
        #     if queryset.kill_house_list != None and len(queryset.kill_house_list) > 0:
        #         for item in queryset.kill_house_list:
        #             parts = item.split("(")
        #             name = parts[0].strip()
        #             kill_request = KillRequest.objects.filter(kill_house__name=name,
        #                                                       recive_date__date=queryset.send_date.date(),
        #                                                       trash=False, poultry__isnull=True,
        #                                                       province_state='accepted').first()
        #             if kill_request:
        #                 kill_request.remain_quantity_for_poultry -= queryset.quantity
        #                 kill_request.save()
        #     return Response(queryset.trash, status=status.HTTP_200_OK)
        # else:

        # if ProvinceOperator.objects.filter(user=user).exists():
        #         hatching = queryset.hatching
        #         hatching.left_over += queryset.quantity + queryset.losses
        #         hatching.losses -= queryset.losses
        #         hatching.state = 'pending'
        #         hatching.save()
        try:
            city = CityOperatorCheckRequest.objects.get(poultry_request=queryset, trash=False)
            city.trash = True
            city.save()
        except:
            pass
        queryset.trash = True
        queryset.save()
        if queryset.kill_house_list != None and len(queryset.kill_house_list) > 0:
            for item in queryset.kill_house_list:
                parts = item.split("(")
                name = parts[0].strip()
                kill_request = KillRequest.objects.filter(kill_house__name=name,
                                                          recive_date__date=queryset.send_date.date(),
                                                          trash=False, poultry__isnull=True,
                                                          province_state='accepted').first()
                if kill_request:
                    kill_request.remain_quantity_for_poultry -= queryset.quantity
                    kill_request.save()
        return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)


# ویوست مربوط به ریزجزییات  پرونده مرغدار برای پنل مرغدار و شهرستان و کشتارگاه
class ProcessViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به نمایش ریزجزییات  پرونده مرغدار برای پنل مرغدار و شهرستان و کشتارگاه
    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        process = {}
        process1 = {}
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        poultry_request = PoultryRequest.objects.get(id=int(request.GET['id']), trash=False)
        # date = str(poultry_request.poultry.incubation_date)
        # new_date = date[:19]
        # chicken_date = datetime.datetime.strptime(new_date, '%Y-%m-%d %H:%M:%S')
        kill_date = datetime.datetime.strptime(str(poultry_request.send_date), '%Y-%m-%d %H:%M:%S')
        # age = (kill_date - chicken_date).days
        if ProvinceKillRequest.objects.filter(
                province_request__city_request_Poultry__poultry_request=poultry_request, state='accepted').exists():
            age2 = (poultry_request.send_date - poultry_request.hatching.date).days + 1
        else:
            age2 = (datetime.datetime.now() - poultry_request.hatching.date).days + 1

        file_state = 'pending'
        if poultry_request.province_state == 'pending':
            file_state = 'province_state_pending'

        if ProvinceKillRequest.objects.filter(province_request__poultry_request__id=poultry_request.id).exists():
            if poultry_request.remain_quantity == 0:
                file_state = 'allocated_completed'


        else:
            file_state = 'allocated_pending'

        process.update({"file_state": file_state})
        process.update({"poultry": {
            "poultry_unit_name": poultry_request.poultry.unit_name,
            "breeding_unique_id": poultry_request.poultry.breeding_unique_id,
            "general_order_code": poultry_request.general_order_code,
            "halls": poultry_request.poultry.number_of_halls,
            "tenant": poultry_request.poultry.tenant,
            "has_tenant": poultry_request.poultry.has_tenant,
            "poultry_request_id": poultry_request.id,
            "base_order": poultry_request.poultry.user.base_order,
            "awaiting_payment": poultry_request.awaiting_payment,
            "poultry_request_final_state": poultry_request.final_state,
            "poultry_request_key": poultry_request.key,
            "kill_house_list": poultry_request.kill_house_list,
            "poultry_order_code": poultry_request.order_code,
            "poultry_send_date": poultry_request.send_date,
            "poultry_name": poultry_request.poultry.user.fullname,
            "poultry_mobile": poultry_request.poultry.user.mobile,
            "poultry_city": poultry_request.poultry.address.city.name,
            "poultry_province": poultry_request.poultry.address.province.name,
            "poultry_gis_code": poultry_request.poultry.gis_code,
            'age': age2,
            'chicken_date': None,
            "poultry_quantity": poultry_request.quantity,
            "poultry_first_quantity": poultry_request.first_quantity,
            "poultry_previous_quantity": poultry_request.previous_quantity,
            "poultry_remain_quantity": poultry_request.remain_quantity,
            "poultry_chicken_breed": poultry_request.chicken_breed,
            "poultry_request_losses": poultry_request.losses,
            "poultry_Index_weight": "{} کیلوگرم".format(poultry_request.Index_weight),
            "Index_weight": poultry_request.Index_weight,
            "poultry_register_date": poultry_request.create_date,
            "poultry_auction": poultry_request.auction,
            "sell_type": poultry_request.cell_type,
            "buyer": poultry_request.buyer,
            "clearance_code": poultry_request.clearance_code,

        }
        })
        poultry_hatching = PoultryHatching.objects.filter(key=poultry_request.hatching.key, trash=False)
        if poultry_hatching.count() > 0:
            poultry_hatching = poultry_hatching.last()
            inspections = VetFarmInspection.objects.filter(poultry_hatching=poultry_hatching)
            losses = 0
            if inspections.count() > 0:
                for ins in inspections:
                    if ins.Losses > 0:
                        losses += ins.Losses
                    else:
                        pass

                if losses > 0:
                    process.update({"inspection_losses": losses
                                    })
                    process.update({
                        "inspection_losses_percent": (losses * 100) / poultry_request.hatching.quantity
                    })

            else:
                process.update({"inspection_losses": losses
                                })
                process.update({
                    "inspection_losses_percent": losses
                })

            process.update({"poultry_hatching": {
                "poultry_key": poultry_request.hatching.poultry.key,
                "poultry_hatching_key": poultry_request.hatching.key,
                "poultry_name": poultry_request.hatching.poultry.unit_name,
                "quantity": poultry_request.hatching.quantity,
                "losses": poultry_request.hatching.losses,
                "total_losses_percent": (poultry_request.hatching.losses * 100) / poultry_request.hatching.quantity,
                "poultry_losses_percent": (poultry_request.losses * 100) / poultry_request.hatching.quantity,
                "left_over": poultry_request.hatching.left_over,
                "hall": poultry_request.hatching.hall,
                "date": poultry_request.hatching.date,
                "allow_hatching": poultry_request.hatching.allow_hatching,
                "period": poultry_request.hatching.period,
                "state": poultry_request.hatching.state,
            }
            })
        else:
            process.update({"poultry_hatching": None
                            })

        vetfarm_inspection = VetFarmInspection.objects.filter(vet_farm__poultry=poultry_request.poultry,
                                                              trash=False)
        if vetfarm_inspection.count() > 0:
            vetfarm_inspection = vetfarm_inspection.last()
            process.update({"vetfarm_inspection": {
                "vet_name": vetfarm_inspection.vet_farm.vet.user.fullname,
                "hall": vetfarm_inspection.hall,
                "topic": vetfarm_inspection.topic,
                "description": vetfarm_inspection.description,
                "image": vetfarm_inspection.image,
                "losses": vetfarm_inspection.Losses,
                "longitude": vetfarm_inspection.longitude,
                "latitude": vetfarm_inspection.latitude,
            }
            })
        else:
            process.update({"vetfarm_inspection": None
                            })
        auctions = PoultryRequestAuction.objects.filter(poultry_request=poultry_request,
                                                        state__in=('active', 'inactive'), trash=False).order_by(
            'auction_date')
        if auctions.count() > 0:
            auctions_list = []
            for auction in auctions:
                if auction.state == 'active':
                    index = list(auctions).index(auction) + 1
                    pricing = Pricing.objects.get(id=auction.pricing.id)
                    internal_dict_auction = {
                        "ceiling_price": pricing.ceiling_price,
                        "floor_price": pricing.floor_price,
                        "fee": auction.fee,
                        "hour": auction.hour,
                        "date": auction.auction_date,
                        "index": index,
                        "total_index": auctions.count()
                    }
                    auctions_list.append(internal_dict_auction)
                    process.update({"auctions_list": auctions_list})
                # else:
                #     break


        else:
            process.update({"auctions_list": None})
        kill_house_auctions = KillHouseRequestAction.objects.filter(poultry_request=poultry_request,
                                                                    state='pending',
                                                                    trash=False)
        if kill_house_auctions.count() > 0:
            kill_house_auctions_list = []
            for kill_house_auction in kill_house_auctions:
                internal_dict_kill_house_auction = {
                    "kill_house_name": kill_house_auction.kill_house.name,
                    "fullname": kill_house_auction.kill_house.kill_house_operator.user.fullname,
                    "mobile": kill_house_auction.kill_house.kill_house_operator.user.mobile,
                    "city": kill_house_auction.kill_house.system_address.city.name,
                    "province": kill_house_auction.kill_house.system_address.province.name,
                    "fee": kill_house_auction.fee,
                }
                kill_house_auctions_list.append(internal_dict_kill_house_auction)
                process.update({"kill_house_auctions_list": kill_house_auctions_list})
        else:
            process.update({"kill_house_auctions_list": None})

        kill_house_auction_winner = KillHouseRequestActionWinner.objects.filter(
            kill_house_request_auction__poultry_request=poultry_request, trash=False)
        if kill_house_auction_winner.count() > 0:
            kill_house_auction_winner = kill_house_auction_winner.last()
            process.update({"kill_house_winner": {
                "kill_house_winner_key": kill_house_auction_winner.key,
                "kill_house_name": kill_house_auction_winner.kill_house_request_auction.kill_house.name,
                "kill_house_user_name": kill_house_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.fullname,
                "kill_house_user_mobile": kill_house_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                "kill_house_city": kill_house_auction_winner.kill_house_request_auction.kill_house.system_address.city.name,
                "kill_house_province": kill_house_auction_winner.kill_house_request_auction.kill_house.system_address.province.name,
                "fee": kill_house_auction_winner.fee,
                "quantity": kill_house_auction_winner.quantity
            }
            })
        else:
            process.update({"kill_house_winner": None
                            })

        province_request_auctions = ProvinceRequestAction.objects.filter(poultry_request=poultry_request,
                                                                         state='active', trash=False)
        if province_request_auctions.count() > 0:
            province_request_auction_list = []
            for province_request_auction in province_request_auctions:
                internal_dict_province_request_auction_list = {
                    "fullname": province_request_auction.province_operator_system.user.fullname,
                    "mobile": province_request_auction.province_operator_system.user.mobile,
                    "city": province_request_auction.province_operator_system.user.city.name,
                    "province": province_request_auction.province_operator_system.user.province.name,
                }
                province_request_auction_list.append(internal_dict_province_request_auction_list)
                process.update({"province_request_auction_list": province_request_auction_list})
        else:
            process.update({"province_request_auction_list": None})
        poultry_assignment = PoultryAssignmentInformation.objects.filter(poultry_request=poultry_request,
                                                                         trash=False)

        if poultry_assignment:
            poultry_bar_list = []
            for bar in poultry_assignment:
                internal_poultry_bar = {
                    "poultry_bar_info_key": bar.key,
                    "car_weight_without_load": bar.car_weight_without_load,
                    "car_weight_without_load_image": bar.car_weight_without_load_image,
                    "car_weight_with_load": bar.car_weight_with_load,
                    "car_weight_with_load_image": bar.car_weight_with_load_image,
                    "net_weight": bar.net_weight,
                }
                poultry_bar_list.append(internal_poultry_bar)

            process.update({"poultry_bar_info": poultry_bar_list})
        if not poultry_assignment:
            process.update({"poultry_bar_info": None})

        city = CityOperatorCheckRequest.objects.filter(poultry_request=poultry_request, trash=False)
        if city:
            process.update({"city": {
                "city_operator_name": city[0].city_operator_system.user.fullname,
                "city_operator_mobile": city[0].city_operator_system.user.mobile,
                "city_operator_province": city[0].city_operator_system.address.province.name,
                "city_operator_city": city[0].city_operator_system.address.city.name,
                "city_operator_address": city[0].city_operator_system.address.address,
                "city_operator_national_id": city[0].city_operator_system.user.national_id,
                "city_state": city[0].state,
                "province_accept": city[0].province_accept,
                "accepted_rejected_date": city[0].create_date,
                "city_operator_message": city[0].message,
                "unit_name": city[0].city_operator_system.unit_name,
            }})
        if not city:
            process.update({"city": None})
            # cit = CityUnit.objects.filter(name=poultry_request.poultry.address.city.name, trash=False)
            # if cit.count() > 0:
            #     city_operator = CityOperator.objects.get(address__city=cit[0].city, trash=False)
        city_operator = CityOperator.objects.get(key=poultry_request.city_operator.key, trash=False)
        process.update({"city_operator": {
            "city_operator_name": city_operator.user.fullname,
            "city_operator_mobile": city_operator.user.mobile,
            "city_operator_province": city_operator.address.province.name,
            "city_operator_city": city_operator.address.city.name,
            "city_operator_address": city_operator.address.address,
            "city_operator_national_id": city_operator.user.national_id,
            "unit_name": city_operator.unit_name,
        }})

        province = ProvinceCheckOperatorRequest.objects.filter(poultry_request=poultry_request,
                                                               trash=False)

        if province.count() > 0:
            if 'role' in request.GET:
                if request.GET['role'] == 'Poultry':
                    process.update({"province": {
                        "province_check_request_key": province[0].key,
                        "province_operator_name": province[0].province_operator_system.user.fullname,
                        "province_operator_mobile": province[0].province_operator_system.user.mobile,
                        "province_operator_provinc": province[0].province_operator_system.address.province.name,
                        "province_operator_city": province[0].province_operator_system.address.city.name,
                        "province_operator_address": province[0].province_operator_system.address.address,
                        "province_operator_national_id": province[0].province_operator_system.user.national_id,
                        "province_state": province[0].state,
                        "province_message": province[0].message,
                        "chicken_price": province[0].fee,
                        "accepted_rejected_date": province[0].create_date,
                    }})
                else:

                    process.update({"province": {
                        "province_check_request_key": province[0].key,
                        "province_operator_name": province[0].province_operator_system.user.fullname,
                        "province_operator_mobile": province[0].province_operator_system.user.mobile,
                        "province_operator_provinc": province[0].province_operator_system.address.province.name,
                        "province_operator_city": province[0].province_operator_system.address.city.name,
                        "province_operator_address": province[0].province_operator_system.address.address,
                        "province_operator_national_id": province[0].province_operator_system.user.national_id,
                        "province_state": province[0].state,
                        "province_message": province[0].message,
                        "chicken_price": province[0].fee,
                        "accepted_rejected_date": province[0].create_date,
                    }})

        if not province:
            process.update({"province": None})

        role = Group.objects.get(name='ProvinceOperator')
        province_operator = ProvinceOperator.objects.get(
            address__province__name=poultry_request.poultry.address.province.name,
            user__role=role, trash=False)
        process.update({"province_operator": {
            "province_operator_name": province_operator.user.fullname,
            "province_operator_mobile": province_operator.user.mobile,
            "province_operator_provinc": province_operator.address.province.name,
            "province_operator_city": province_operator.address.city.name,
            "province_operator_address": province_operator.address.address,
            "province_operator_national_id": province_operator.user.national_id,
        }})
        if ProvinceFactorToKillHouseForPoultry.objects.filter(province_check_req=province.last()).exists():
            poultry_factor = ProvinceFactorToKillHouseForPoultry.objects.filter(
                province_check_req=province.last()).last()
            if poultry_factor.bank != None:
                name_of_bank_user_poultry = poultry_factor.bank.name_of_bank_user
                bank_name_poultry = poultry_factor.bank.bank_name
                card_poultry = poultry_factor.bank.card
                shaba_poultry = poultry_factor.bank.shaba
                account_poultry = poultry_factor.bank.account
            else:
                name_of_bank_user_poultry = None
                bank_name_poultry = None
                card_poultry = None
                shaba_poultry = None
                account_poultry = None
            process.update({"poultry_factor": {
                "poultry_factor_key": poultry_factor.key,
                "province_factor_fee": poultry_factor.factor_fee,
                "province_operator": poultry_factor.province_check_req.province_operator_system.user.fullname,
                "province_mobile": poultry_factor.province_check_req.province_operator_system.user.mobile,
                "weight": poultry_factor.total_weight,
                "cost": poultry_factor.total_price,
                "poultry_share_with_profit": poultry_factor.shares,
                "total_amount_char": words(poultry_factor.total_price) + " " + "ریال",
                "name_of_bank_user": name_of_bank_user_poultry,
                "bank_name": bank_name_poultry,
                "card": card_poultry,
                "shaba": shaba_poultry,
                "account": account_poultry,
            }})
        else:
            process.update({"poultry_factor": None})

        if ProvinceFactorToKillHouse.objects.filter(province_check_req=province.last()).exists():
            province_factor = ProvinceFactorToKillHouse.objects.filter(province_check_req=province.last()).last()

            if province_factor.bank != None:
                name_of_bank_user_province_factor = province_factor.bank.name_of_bank_user
                bank_name_province_factor = province_factor.bank.bank_name
                card_province_factor = province_factor.bank.card
                shaba_province_factor = province_factor.bank.shaba
                account_province_factor = province_factor.bank.account
            else:
                name_of_bank_user_province_factor = None
                bank_name_province_factor = None
                card_province_factor = None
                shaba_province_factor = None
                account_province_factor = None

            process.update({"province_factor": {
                "province_factor_key": province_factor.key,
                "province_factor_fee": province_factor.factor_fee,
                "province_operator": province_factor.province_check_req.province_operator_system.user.fullname,
                "province_mobile": province_factor.province_check_req.province_operator_system.user.mobile,
                "weight": province_factor.total_weight,
                "cost": province_factor.total_price,
                "union_share_with_profit": province_factor.shares,
                "total_amount_char": words(province_factor.total_price) + " " + "ریال",
                "name_of_bank_user": name_of_bank_user_province_factor,
                "bank_name": bank_name_province_factor,
                "card": card_province_factor,
                "shaba": shaba_province_factor,
                "account": account_province_factor,
            }})
        else:
            process.update({"province_factor": None})

        if ProvinceImportKillHouseOutFactors.objects.filter(province_check=province.last()).exists():
            payment_out_factors = ProvinceImportKillHouseOutFactors.objects.filter(province_check=province.last())
            interal_factor_list = []
            for payment_out_factor in payment_out_factors:
                internal_dict = {
                    "key": payment_out_factor.key,
                    "amount": payment_out_factor.amount,
                    "image": payment_out_factor.image,
                }
                interal_factor_list.append(internal_dict)
            process.update({"out_factors": interal_factor_list})
        else:
            process.update({"out_factors": None})

        if 'role' in request.GET:
            if request.GET['role'] == 'KillHouse':
                kill_house_operator = KillHouseOperator.objects.filter(user=user, trash=False)
                if kill_house_operator.count() > 0:
                    kill_house_operator = kill_house_operator.last()
                    kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
                    province_kill_reqs = ProvinceKillRequest.objects.filter(
                        province_request__city_request_Poultry__poultry_request=poultry_request,
                        killhouse_user__in=kill_house, trash=False)
            elif request.GET['role'] == 'KillHouseVet':
                vet = Vet.objects.filter(user=user, trash=False)
                if vet.count() > 0:
                    vet = vet.last()
                    kill_house_vet = KillHouseVet.objects.filter(vet=vet)
                    kill_house_vet = kill_house_vet.last()
                    province_kill_reqs = ProvinceKillRequest.objects.filter(
                        province_request__city_request_Poultry__poultry_request=poultry_request,
                        killhouse_user=kill_house_vet.kill_house, trash=False)
            else:
                province_kill_reqs = ProvinceKillRequest.objects.filter(
                    province_request__city_request_Poultry__poultry_request=poultry_request, trash=False)

            if province_kill_reqs.count() > 0:
                state_list = []
                for province_kill_req in province_kill_reqs:
                    state_list.append(province_kill_req.payment_type)
                l1 = set(state_list)
                if len(l1) > 1:
                    process.update({"file_payment_type": "cash_credit"})
                else:
                    process.update({"file_payment_type": state_list[0]})
                province_kill_reqs_list = []
                for province_kill_req in province_kill_reqs:
                    check = KillHouseCheckRequest.objects.filter(province_kill_request=province_kill_req,
                                                                 trash=False)
                    internal_province_kill_dict_infos = {
                        "province_kill_req_key": province_kill_req.key,
                        "payment_type": province_kill_req.payment_type,
                        "payment_dead_line": province_kill_req.payment_dead_line,
                        "kill_req_key": province_kill_req.kill_request.key,
                        "province_kill_req_state": province_kill_req.state,
                        "kill_house_name": province_kill_req.kill_request.kill_house.name,
                        "kill_house_user_name": province_kill_req.kill_request.kill_house.kill_house_operator.user.fullname,
                        "kill_house_user_city": province_kill_req.kill_request.kill_house.kill_house_operator.user.city.name,
                        "kill_house_user_province": province_kill_req.kill_request.kill_house.kill_house_operator.user.province.name,
                        "kill_house_user_national_id": province_kill_req.kill_request.kill_house.kill_house_operator.user.national_id,
                        "kill_house_mobile": province_kill_req.kill_request.kill_house.kill_house_operator.user.mobile,
                        "quantity": province_kill_req.quantity,
                        "time": province_kill_req.kill_request.recive_time,
                        "date": province_kill_req.kill_request.recive_date,
                        "automatic_state": province_kill_req.automatic,
                        "fee": province_kill_req.fee,
                        "province_kill_req_message": province_kill_req.message
                    }

                    kill_house_requests = KillHouseRequest.objects.filter(
                        province_request__city_request_Poultry__poultry_request=poultry_request,
                        province_kill_request=province_kill_req, trash=False)
                    if kill_house_requests.count() > 0:
                        reqs = []
                        for kill_house_request in kill_house_requests:
                            province_req = kill_house_request.province_request
                            internal_dict_infos = {
                                "kill_house_req_key": kill_house_request.key,
                                "payment_type": province_kill_req.payment_type,
                                "province_fee": province_kill_req.fee,
                                "payment_dead_line": province_kill_req.payment_dead_line,
                                "kill_house_vet_state": kill_house_request.vet_state,
                                "kill_req_key": kill_house_request.kill_request.key,
                                "kill_house_check_key": check[0].key,
                                "barcod": kill_house_request.bar_code,
                                "kill_house_state": kill_house_request.state,
                                "kill_house_name": kill_house_request.kill_request.kill_house.name,
                                "kill_house_user_name": kill_house_request.kill_request.kill_house.kill_house_operator.user.fullname,
                                "kill_house_user_province": kill_house_request.kill_request.kill_house.kill_house_operator.user.province.name,
                                "kill_house_user_city": kill_house_request.kill_request.kill_house.kill_house_operator.user.city.name,
                                "kill_house_user_address": kill_house_request.kill_request.kill_house.system_address.address,
                                "kill_house_mobile": kill_house_request.kill_request.kill_house.kill_house_operator.user.mobile,
                                "kill_house_national_id": kill_house_request.kill_request.kill_house.kill_house_operator.user.national_id,
                                "quantity": kill_house_request.quantity,
                                "fee": kill_house_request.province_kill_request.fee,
                                "time": kill_house_request.kill_request.recive_time,
                                "date": kill_house_request.kill_request.recive_date,
                                "cars": kill_house_request.car,
                                "driver_name": kill_house_request.add_car.driver.driver_name,
                                "type_car": kill_house_request.add_car.driver.type_car,
                                "pelak": kill_house_request.add_car.driver.pelak,
                                "clearance_code": kill_house_request.clearance_code,
                                "traffic_code": kill_house_request.traffic_code,
                                "show_kill_house": kill_house_request.show_kill_house,
                                "kill_house_message": kill_house_request.kill_house_message
                            }

                            vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_request,
                                                                       trash=False)
                            if vet_check:
                                internal_dict_infos.update({
                                    "vet_check_info": {
                                        "vet_user": vet_check[0].kill_house_vet.vet.user.fullname,
                                        "vet_user_mobile": vet_check[0].kill_house_vet.vet.user.mobile,
                                        "vet_check_state": vet_check[0].state,
                                        "vet_check_accept_date": vet_check[0].create_date,
                                    }
                                })
                            if not vet_check:
                                internal_dict_infos.update({
                                    "vet_check_info": None
                                })
                            kill_house_assignment = KillHouseAssignmentInformation.objects.filter(
                                kill_house_check__province_kill_request__province_request=province_req,
                                kill_house_request=kill_house_request, trash=False)
                            if kill_house_assignment:
                                internal_dict_infos.update({
                                    "bar_info": {
                                        "kill_house_assignment_key": kill_house_assignment[0].key,
                                        "real_quantity": kill_house_assignment[0].real_quantity,
                                        "kill_house_weight_without_load": kill_house_assignment[
                                            0].car_weight_without_load,
                                        "kill_house_weight_with_load": kill_house_assignment[
                                            0].car_weight_with_load,
                                        "kill_house_image_without_load": kill_house_assignment[
                                            0].car_weight_without_load_image,
                                        "kill_house_image_with_load": kill_house_assignment[
                                            0].car_weight_with_load_image,
                                        "kill_house_net_weight": kill_house_assignment[0].net_weight,
                                        "kill_house_assignment_state": kill_house_assignment[0].state,
                                        "expire_time": kill_house_assignment[0].protest_time,
                                        "kill_house_assignment_message": kill_house_assignment[0].message,
                                        "accept_reject_date": kill_house_assignment[0].modify_date,
                                        "unusual_casualties": kill_house_assignment[0].unusual_casualties,

                                    }
                                })

                                complaint = KillHouseComplaint.objects.filter(bar=kill_house_assignment[0],
                                                                              trash=False)
                                percentage_losses = PercentageOfLosses.objects.all()
                                if percentage_losses.count() > 0:
                                    percentage_losses = percentage_losses.last().percent
                                else:
                                    percentage_losses = None
                                if complaint.count() > 0:
                                    complaint = complaint.last()
                                    check_complaint = CheckUnusualCasualties.objects.filter(complaint=complaint)
                                    if check_complaint.count() > 0:
                                        reviewer = check_complaint.last().role
                                    else:
                                        reviewer = None
                                    internal_dict_infos.update({
                                        "complaint": {
                                            "complaint_key": complaint.key,
                                            "create_date": complaint.create_date,
                                            "title": complaint.title,
                                            "description": complaint.description,
                                            "percent": complaint.percent,
                                            "image": complaint.image,
                                            "state": complaint.state,
                                            "message": complaint.message,
                                            "registrar": complaint.registrar,
                                            "reviewer": reviewer,
                                            "real_weight": kill_house_assignment[0].net_weight,
                                            "losses_weight": kill_house_assignment[0].weight_withs_losses,
                                            "percentage_losses": percentage_losses,
                                        }
                                    })
                                else:
                                    internal_dict_infos.update({
                                        "complaint": None
                                    })

                            if not kill_house_assignment:
                                internal_dict_infos.update({
                                    "bar_info": None
                                })
                                internal_dict_infos.update({
                                    "complaint": None
                                })

                            poultry_factor = ProvinceFactorToKillHouseForPoultry.objects.filter(
                                province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                                trash=False)
                            if poultry_factor.count() > 0:
                                poultry_factor = poultry_factor.last()
                                if poultry_factor.bank != None:
                                    name_of_bank_user = poultry_factor.bank.name_of_bank_user
                                    bank_name = poultry_factor.bank.bank_name
                                    card = poultry_factor.bank.card,
                                    shaba = poultry_factor.bank.shaba,
                                    account = poultry_factor.bank.account,
                                else:
                                    name_of_bank_user = None
                                    bank_name = None
                                    card = None
                                    shaba = None
                                    account = None
                                share_allocation = ShareOfAllocation.objects.all()
                                if share_allocation.count() > 0:
                                    share_allocation = share_allocation.last()
                                    total = share_allocation.total
                                else:
                                    total = 0
                                internal_dict_infos.update({
                                    "province_factor_to_kill_house_for_poultry": {
                                        "province_factor_key": poultry_factor.key,
                                        "province_factor_fee": poultry_factor.factor_fee,
                                        "province_operator": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.province_request.province_operator_system.user.fullname,
                                        "province_mobile": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.province_request.province_operator_system.user.mobile,
                                        "weight": poultry_factor.total_weight,
                                        "bar_code": poultry_factor.factor_bar_code,
                                        "kill_house_name": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.kill_request.kill_house.name,
                                        "kill_house_mobile": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.kill_request.kill_house.kill_house_operator.user.mobile,
                                        "cost": poultry_factor.total_price,
                                        "poultry_share_with_profit": poultry_factor.shares[
                                            'poultryShareWithProfit'],
                                        "total_amount_char": words(poultry_factor.total_price) + " " + "ریال",
                                        "total_share_allocation": poultry_factor.total_weight * total,
                                        "total_share_allocation_char": words(
                                            poultry_factor.total_weight * total) + " " + "ریال",
                                        "name_of_bank_user": name_of_bank_user,
                                        "bank_name": bank_name,
                                        "card": card,
                                        "shaba": shaba,
                                        "account": account,
                                    }
                                })
                            if not poultry_factor:
                                internal_dict_infos.update({
                                    "province_factor_to_kill_house_for_poultry": None
                                })

                            province_factor = ProvinceFactorToKillHouse.objects.filter(
                                province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                                trash=False)
                            if province_factor:
                                if province_factor[0].bank != None:
                                    name_of_bank_user = province_factor[0].bank.name_of_bank_user
                                    bank_name = province_factor[0].bank.bank_name
                                    card = province_factor[0].bank.card,
                                    shaba = province_factor[0].bank.shaba,
                                    account = province_factor[0].bank.account,
                                else:
                                    name_of_bank_user = None
                                    bank_name = None
                                    card = None
                                    shaba = None
                                    account = None
                                share_allocation = ShareOfAllocation.objects.all()
                                if share_allocation.count() > 0:
                                    share_allocation = share_allocation.last()
                                    total = share_allocation.total
                                else:
                                    total = 0

                                if province_factor[0].poultry_factor == None:
                                    poultry_share_with_profit = province_factor[0].shares['poultryShareWithProfit']
                                else:
                                    poultry_share_with_profit = province_factor[0].poultry_factor.total_price

                                internal_dict_infos.update({
                                    "province_factor_to_kill_house": {
                                        "province_factor_key": province_factor[0].key,
                                        "province_factor_fee": province_factor[0].factor_fee,
                                        "province_operator": province_factor[
                                            0].province_check_info.kill_house_assignment.kill_house_check.province_kill_request.province_request.province_operator_system.user.fullname,
                                        "province_mobile": province_factor[
                                            0].province_check_info.kill_house_assignment.kill_house_check.province_kill_request.province_request.province_operator_system.user.mobile,
                                        "weight": province_factor[0].total_weight,
                                        "bar_code": province_factor[0].factor_bar_code,
                                        "kill_house_name": province_factor[
                                            0].province_check_info.kill_house_assignment.kill_house_check.province_kill_request.kill_request.kill_house.name,
                                        "kill_house_mobile": province_factor[
                                            0].province_check_info.kill_house_assignment.kill_house_check.province_kill_request.kill_request.kill_house.kill_house_operator.user.mobile,
                                        "cost": province_factor[0].total_price,
                                        "poultry_share_with_profit": poultry_share_with_profit,
                                        "union_share_with_profit": province_factor[0].shares[
                                            'unionShareWithProfit'],
                                        "total_amount_char": words(province_factor[0].total_price) + " " + "ریال",
                                        "total_share_allocation": province_factor[0].total_weight * total,
                                        "total_share_allocation_char": words(
                                            province_factor[0].total_weight * total) + " " + "ریال",
                                        "name_of_bank_user": name_of_bank_user,
                                        "bank_name": bank_name,
                                        "card": card,
                                        "shaba": shaba,
                                        "account": account,
                                    }
                                })
                            if not province_factor:
                                internal_dict_infos.update({
                                    "province_factor_to_kill_house": None
                                })

                            kill_house_factor_poultry = KillHouseFactorToPoultry.objects.filter(
                                province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                                trash=False)
                            if kill_house_factor_poultry.count():
                                kill_house_factor_poultry = kill_house_factor_poultry.last()
                                internal_dict_infos.update({
                                    "kill_house_factor_to_poultry": {
                                        "kill_house_name": kill_house_request.killhouse_user.name,
                                        "kill_house_user_city": kill_house_request.killhouse_user.system_address.city.name,
                                        "kill_house_user_province": kill_house_request.killhouse_user.system_address.province.name,
                                        "time": kill_house_factor_poultry.create_date,
                                        "payment_code": kill_house_factor_poultry.payment_code,
                                        "factor_image": kill_house_factor_poultry.factor_image,
                                        "factor_key": kill_house_factor_poultry.key,
                                        "factor_state": kill_house_factor_poultry.state,
                                        "total_money": kill_house_factor_poultry.province_factor.total_price,
                                        "factor_message": kill_house_factor_poultry.message
                                    }
                                })
                            if not kill_house_factor_poultry:
                                internal_dict_infos.update({
                                    "kill_house_factor_to_poultry": None
                                })
                            kill_house_factor = KillHouseFactorToProvince.objects.filter(
                                province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                                trash=False)
                            if kill_house_factor:
                                internal_dict_infos.update({
                                    "kill_house_factor_to_province": {
                                        "kill_house_name": kill_house_request.killhouse_user.name,
                                        "kill_house_user_city": kill_house_request.killhouse_user.system_address.city.name,
                                        "kill_house_user_province": kill_house_request.killhouse_user.system_address.province.name,
                                        "time": kill_house_factor[0].create_date,
                                        "payment_code": kill_house_factor[0].payment_code,
                                        "factor_image": kill_house_factor[0].factor_image,
                                        "factor_key": kill_house_factor[0].key,
                                        "factor_state": kill_house_factor[0].state,
                                        "total_money": kill_house_factor[0].province_factor.total_price,
                                        "factor_message": kill_house_factor[0].message
                                    }
                                })
                            if not kill_house_factor:
                                internal_dict_infos.update({
                                    "kill_house_factor_to_province": None
                                })

                            reqs.append(internal_dict_infos)
                        internal_province_kill_dict_infos.update({"kill_house_requests": reqs

                                                                  })
                    if not kill_house_requests:
                        internal_province_kill_dict_infos.update({"kill_house_requests": None

                                                                  })

                    province_kill_reqs_list.append(internal_province_kill_dict_infos)
                process.update({"province_kill_requests": province_kill_reqs_list})

            elif province_kill_reqs.count() == 0:
                process.update({"province_kill_requests": None

                                })
        if 'role' in request.GET:
            if request.GET['role'] == 'KillHouse':
                kill_house_operator = KillHouseOperator.objects.filter(user=user, trash=False)
                if kill_house_operator.count() > 0:
                    kill_house_operator = kill_house_operator.last()
                    kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
                    kill_house_reqs = KillHouseRequest.objects.filter(
                        kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                        killhouse_user__in=kill_house, trash=False)
            elif request.GET['role'] == 'KillHouseVet':
                vet = Vet.objects.filter(user=user, trash=False)
                if vet.count() > 0:
                    vet = vet.last()
                    kill_house_vet = KillHouseVet.objects.filter(vet=vet)
                    kill_house_vet = kill_house_vet.last()
                    kill_house_reqs = KillHouseRequest.objects.filter(
                        kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                        killhouse_user=kill_house_vet.kill_house, trash=False)
            else:
                kill_house_reqs = KillHouseRequest.objects.filter(
                    kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                    trash=False)

            if kill_house_reqs.count() > 0:

                reqs = []
                for kill_house_request in kill_house_reqs:
                    # province_req = kill_house_request.province_request
                    internal_dict_infos = {
                        "kill_house_req_key": kill_house_request.key,
                        "kill_house_vet_state": kill_house_request.vet_state,
                        "order_code": poultry_request.order_code,
                        "barcod": kill_house_request.bar_code,
                        "kill_house_state": kill_house_request.state,
                        "kill_house_name": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.name,
                        "kill_house_user_name": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.fullname,
                        "kill_house_user_province": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.province.name,
                        "kill_house_user_city": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.city.name,
                        "kill_house_user_address": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.system_address.address,
                        "kill_house_mobile": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                        "kill_house_national_id": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.national_id,
                        "quantity": kill_house_request.quantity,
                        # "time": kill_house_request.kill_request.recive_time,
                        # "date": kill_house_request.kill_request.recive_date,
                        "cars": kill_house_request.car,
                        "driver_name": kill_house_request.add_car.driver.driver_name,
                        "type_car": kill_house_request.add_car.driver.type_car,
                        "pelak": kill_house_request.add_car.driver.pelak,
                        "clearance_code": kill_house_request.clearance_code,
                        "traffic_code": kill_house_request.traffic_code,
                        "show_kill_house": kill_house_request.show_kill_house,
                        "kill_house_message": kill_house_request.kill_house_message
                    }

                    vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_request, trash=False)
                    if vet_check:
                        internal_dict_infos.update({
                            "vet_check_info": {
                                "vet_user": vet_check[0].kill_house_vet.vet.user.fullname,
                                "vet_user_mobile": vet_check[0].kill_house_vet.vet.user.mobile,
                                "vet_check_state": vet_check[0].state,
                                "vet_check_accept_date": vet_check[0].create_date,
                            }
                        })
                    if not vet_check:
                        internal_dict_infos.update({
                            "vet_check_info": None
                        })
                    kill_house_assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request=kill_house_request, trash=False)
                    if kill_house_assignment:
                        internal_dict_infos.update({
                            "bar_info": {
                                "kill_house_assignment_key": kill_house_assignment[0].key,
                                "real_quantity": kill_house_assignment[0].real_quantity,
                                "kill_house_weight_without_load": kill_house_assignment[0].car_weight_without_load,
                                "kill_house_weight_with_load": kill_house_assignment[0].car_weight_with_load,
                                "kill_house_image_without_load": kill_house_assignment[
                                    0].car_weight_without_load_image,
                                "kill_house_image_with_load": kill_house_assignment[0].car_weight_with_load_image,
                                "kill_house_net_weight": kill_house_assignment[0].net_weight,
                                "expire_time": kill_house_assignment[0].protest_time,
                                "kill_house_assignment_state": kill_house_assignment[0].state,
                                "kill_house_assignment_message": kill_house_assignment[0].message,
                                "accept_reject_date": kill_house_assignment[0].modify_date

                            }
                        })
                        complaint = KillHouseComplaint.objects.filter(bar=kill_house_assignment[0], trash=False)
                        if complaint.count() > 0:
                            complaint = complaint.last()
                            internal_dict_infos.update({
                                "complaint": {
                                    "complaint_key": complaint.key,
                                    "title": complaint.title,
                                    "description": complaint.description,
                                    "percent": complaint.percent,
                                    "image": complaint.image,
                                    "state": complaint.state,
                                    "message": complaint.message,
                                }
                            })
                        else:
                            internal_dict_infos.update({
                                "complaint": None
                            })

                    if not kill_house_assignment:
                        internal_dict_infos.update({
                            "bar_info": None
                        })
                        internal_dict_infos.update({
                            "complaint": None
                        })
                    poultry_factor = ProvinceFactorToKillHouseForPoultry.objects.filter(
                        province_check_info__kill_house_assignment__kill_house_request__kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                        province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                        trash=False)
                    if poultry_factor.count() > 0:
                        poultry_factor = poultry_factor.last()
                        if poultry_factor.bank != None:
                            name_of_bank_user = poultry_factor.bank.name_of_bank_user
                            bank_name = poultry_factor.bank.bank_name
                            card = poultry_factor.bank.card,
                            shaba = poultry_factor.bank.shaba,
                            account = poultry_factor.bank.account,
                        else:
                            name_of_bank_user = None
                            bank_name = None
                            card = None
                            shaba = None
                            account = None
                        share_allocation = ShareOfAllocation.objects.all()
                        if share_allocation.count() > 0:
                            share_allocation = share_allocation.last()
                            total = share_allocation.total
                        else:
                            total = 0
                        internal_dict_infos.update({
                            "province_factor_to_kill_house_for_poultry": {
                                "province_factor_key": poultry_factor.key,
                                "province_factor_fee": poultry_factor.factor_fee,
                                "province_operator": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.province_request.province_operator_system.user.fullname,
                                "province_mobile": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.province_request.province_operator_system.user.mobile,
                                "weight": poultry_factor.total_weight,
                                "bar_code": poultry_factor.factor_bar_code,
                                "kill_house_name": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.kill_request.kill_house.name,
                                "kill_house_mobile": poultry_factor.province_check_info.kill_house_assignment.kill_house_check.province_kill_request.kill_request.kill_house.kill_house_operator.user.mobile,
                                "cost": poultry_factor.total_price,
                                "poultry_share_with_profit": poultry_factor.shares[
                                    'poultryShareWithProfit'],
                                "total_amount_char": words(poultry_factor.total_price) + " " + "ریال",
                                "total_share_allocation": poultry_factor.total_weight * total,
                                "total_share_allocation_char": words(
                                    poultry_factor.total_weight * total) + " " + "ریال",
                                "name_of_bank_user": name_of_bank_user,
                                "bank_name": bank_name,
                                "card": card,
                                "shaba": shaba,
                                "account": account,
                            }
                        })
                    if not poultry_factor:
                        internal_dict_infos.update({
                            "province_factor_to_kill_house_for_poultry": None
                        })
                    province_factor = ProvinceFactorToKillHouse.objects.filter(
                        province_check_info__kill_house_assignment__kill_house_request__kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                        province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                        trash=False)
                    if province_factor:
                        if province_factor[0].bank != None:
                            name_of_bank_user = province_factor[0].bank.name_of_bank_user
                            bank_name = province_factor[0].bank.bank_name
                            card = province_factor[0].bank.card,
                            shaba = province_factor[0].bank.shaba,
                            account = province_factor[0].bank.account,
                        else:
                            name_of_bank_user = None
                            bank_name = None
                            card = None
                            shaba = None
                            account = None
                        share_allocation = ShareOfAllocation.objects.all()
                        if share_allocation.count() > 0:
                            share_allocation = share_allocation.last()
                            total = share_allocation.total
                        else:
                            total = 0
                        if province_factor[0].poultry_factor == None:
                            poultry_share_with_profit = province_factor[0].shares['poultryShareWithProfit']
                        else:
                            poultry_share_with_profit = province_factor[0].poultry_factor.total_price
                        province_operator = province_factor[0].province_check_info.province_operator
                        internal_dict_infos.update({
                            "province_factor_to_kill_house": {
                                "province_factor_key": province_factor[0].key,
                                "province_factor_fee": province_factor[0].factor_fee,
                                "province_operator": province_operator.user.fullname,
                                "province_mobile": province_operator.user.mobile,
                                "weight": province_factor[0].total_weight,
                                "bar_code": province_factor[0].factor_bar_code,
                                "kill_house_name": province_factor[
                                    0].province_check_info.kill_house_assignment.kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.name,
                                "kill_house_mobile": province_factor[
                                    0].province_check_info.kill_house_assignment.kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                                "cost": province_factor[0].total_price,
                                "poultry_share_with_profit": poultry_share_with_profit,
                                "union_share_with_profit": province_factor[0].shares['unionShareWithProfit'],
                                "total_amount_char": words(province_factor[0].total_price) + " " + "ریال",
                                "total_share_allocation": province_factor[0].total_weight * total,
                                "total_share_allocation_char": words(
                                    province_factor[0].total_weight * total) + " " + "ریال",
                                "name_of_bank_user": name_of_bank_user,
                                "bank_name": bank_name,
                                "card": card,
                                "shaba": shaba,
                                "account": account,

                            }
                        })
                    if not province_factor:
                        internal_dict_infos.update({
                            "province_factor_to_kill_house": None
                        })

                    kill_house_factor_poultry = KillHouseFactorToPoultry.objects.filter(
                        province_factor__province_check_info__kill_house_assignment__kill_house_request__kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                        province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                        trash=False)
                    if kill_house_factor_poultry.count():
                        kill_house_factor_poultry = kill_house_factor_poultry.last()
                        internal_dict_infos.update({
                            "kill_house_factor_to_poultry": {
                                "kill_house_name": kill_house_request.killhouse_user.name,
                                "kill_house_user_city": kill_house_request.killhouse_user.system_address.city.name,
                                "kill_house_user_province": kill_house_request.killhouse_user.system_address.province.name,
                                "time": kill_house_factor_poultry.create_date,
                                "payment_code": kill_house_factor_poultry.payment_code,
                                "factor_image": kill_house_factor_poultry.factor_image,
                                "factor_key": kill_house_factor_poultry.key,
                                "factor_state": kill_house_factor_poultry.state,
                                "total_money": kill_house_factor_poultry.province_factor.total_price,
                                "factor_message": kill_house_factor_poultry.message
                            }
                        })
                    if not kill_house_factor_poultry:
                        internal_dict_infos.update({
                            "kill_house_factor_to_poultry": None
                        })
                    kill_house_factor = KillHouseFactorToProvince.objects.filter(
                        province_factor__province_check_info__kill_house_assignment__kill_house_request__kill_house_request_auction_winner__kill_house_request_auction__poultry_request=poultry_request,
                        province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request,
                        trash=False)
                    if kill_house_factor:
                        internal_dict_infos.update({
                            "kill_house_factor_to_province": {
                                "kill_house_name": kill_house_request.killhouse_user.name,
                                "kill_house_user_city": kill_house_request.killhouse_user.system_address.city.name,
                                "kill_house_user_province": kill_house_request.killhouse_user.system_address.province.name,
                                "time": kill_house_factor[0].create_date,
                                "payment_code": kill_house_factor[0].payment_code,
                                "factor_image": kill_house_factor[0].factor_image,
                                "factor_key": kill_house_factor[0].key,
                                "total_money": kill_house_factor[0].province_factor.total_price,
                                "factor_state": kill_house_factor[0].state,
                                "factor_message": kill_house_factor[0].message
                            }
                        })
                    if not kill_house_factor:
                        internal_dict_infos.update({
                            "kill_house_factor_to_province": None
                        })

                    reqs.append(internal_dict_infos)
                process.update({"auction": reqs})

            elif kill_house_reqs.count() > 0:
                process.update({"auction": None})

        allocation = DepositAllocation.objects.filter(poultry=poultry_request, trash=False)
        if allocation.count() > 0:
            if request.GET['role'] == 'Poultry':
                if poultry_request.poultry.user_bank_info != None:
                    poultry_bank_info = poultry_request.poultry.user_bank_info.name_of_bank_user
                    poultry_bank_name = poultry_request.poultry.user_bank_info.bank_name
                    poultry_card_number = poultry_request.poultry.user_bank_info.card
                    poultry_shaba = poultry_request.poultry.user_bank_info.shaba

                else:
                    poultry_bank_info = None
                    poultry_bank_name = None
                    poultry_card_number = None
                    poultry_shaba = None

                process.update({"allocation": {"allocation_key": allocation[0].key,
                                               "poultry_share_digit": allocation[0].poultry_share,
                                               "poultry_share_char": words(
                                                   allocation[0].poultry_share) + " " + 'ریال',
                                               "poultry_share_payment": allocation[0].poultry_share_payment,
                                               "poultry_remaining": (allocation[0].poultry_share - allocation[
                                                   0].poultry_share_payment),
                                               "poultry_payment_documents": allocation[
                                                   0].poultry_share_payment_info,
                                               "poultry_bank_info": poultry_bank_info,
                                               "poultry_bank_name": poultry_bank_name,
                                               "poultry_card_number": poultry_card_number,
                                               "poultry_shaba": poultry_shaba,
                                               "poultry_image": allocation[0].poultry_image,

                                               }})
            elif request.GET['role'] == 'CityOperator':
                if city_operator.user_bank_info != None:
                    city_bank_info = city_operator.user_bank_info.name_of_bank_user
                    city_bank_name = city_operator.user_bank_info.bank_name
                    city_card_number = city_operator.user_bank_info.card
                    city_shaba = city_operator.user_bank_info.shaba
                else:
                    city_bank_info = None
                    city_bank_name = None
                    city_card_number = None
                    city_shaba = None
                process.update({"allocation": {"allocation_key": allocation[0].key,
                                               "city_share_digit": allocation[0].city_share,
                                               "city_share_char": words(
                                                   allocation[0].city_share) + " " + 'ریال',
                                               "city_share_payment": allocation[0].city_share_payment,
                                               "city_share_remaining": (
                                                       allocation[0].city_share - allocation[0].city_share_payment),
                                               "city_payment_documents": allocation[0].city_share_payment_info,
                                               "city_image": allocation[0].city_image,
                                               "city_bank_info": city_bank_info,
                                               "city_bank_name": city_bank_name,
                                               "city_card_number": city_card_number,
                                               "city_shaba": city_shaba,
                                               }})
            else:
                process.update({"allocation": None})

        if not allocation:
            process.update({"allocation": None})

        province_incpector = PovinceInspector.objects.filter(poultry_request=poultry_request, trash=False)
        if province_incpector:
            process.update(
                {"province_incpector": {"inspector_name": province_incpector[0].inspector_operator.user.fullname,
                                        "state": province_incpector[0].state,
                                        "message": province_incpector[0].message,
                                        "accept-reject-date": province_incpector[0].create_date, }})
        if not province_incpector:
            province_name = poultry_request.poultry.address.province.name
            inspector = InspectorOperator.objects.get(address__province__name=province_name, trash=False)
            process.update({"province_incpector": {"province_incpector": None,
                                                   "state": 'pending',
                                                   "inspector_name": inspector.user.fullname,
                                                   "inspector_mobile": inspector.user.mobile,
                                                   "inspector_address": inspector.address.province.name}})
        process1.update({"process": process})

        return Response(process1, status=status.HTTP_200_OK)


# ویوست مربوط به ثبت و نمایش و ... مستاجر مرغداری
class PoultryRequestAuctionViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequestAuction.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryRequestAuction


# ویوست مربوط به وارد کردن اطلاعات بار توسط مرغدار
class PoultryAssignmentInformationViewSet(viewsets.ModelViewSet):
    queryset = PoultryAssignmentInformation.objects.all()
    serializer_class = PoultryAssignmentInformationSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به وارد کردن اطلاعات بار توسط مرغدار
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        poultry = PoultryRequest.objects.get(key=request.data['key'], trash=False)
        car_without_load_image = request.data['car_without_load_image']
        car_with_load_image = request.data['car_with_load_image']
        request.data.pop('key')
        request.data.pop('car_without_load_image')
        request.data.pop('car_with_load_image')
        pic = []
        pic.append(car_without_load_image)
        pic.append(car_with_load_image)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            poultry_assignment_info = serializer.create(validated_data=request.data)
            poultry_assignment_info.poultry_request = poultry
            for p in pic:
                if p == car_without_load_image:
                    poultry_assignment_info.car_weight_without_load_image = send_image_to_server(p)
                else:
                    poultry_assignment_info.car_weight_with_load_image = send_image_to_server(p)
            poultry_assignment_info.save()
            assignment_info_serializer = self.serializer_class(poultry_assignment_info)
            return Response(assignment_info_serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

    # تابع مربوط به ویرایش اطلاعات بار وارد شده توسط مرغدار
    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        poultry_assignment = PoultryAssignmentInformation.objects.get(key__exact=request.data["key"], trash=False)
        request.data.pop('key')
        try:
            if request.data['car_without_load_image'] == "":
                car_without_load_image = None

            else:
                car_without_load_image = request.data['car_without_load_image']
                request.data.pop('car_without_load_image')

        except:
            car_without_load_image = None

        try:
            if request.data['car_with_load_image'] == "":
                car_with_load_image = None

            else:
                car_with_load_image = request.data['car_with_load_image']
                request.data.pop('car_with_load_image')

        except:
            car_with_load_image = None

        if car_without_load_image:
            poultry_assignment.car_weight_without_load_image = send_image_to_server(car_without_load_image)

        if car_with_load_image:
            poultry_assignment.car_weight_with_load_image = send_image_to_server(car_with_load_image)

        poultry_assignment.save()
        serializer = self.serializer_class(poultry_assignment)
        serializer.update(instance=poultry_assignment, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به سرچ درخواست مرغدار
class PoultryRequestSearchViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)

        if 'type' in request.GET:
            if request.GET['type'] == 'fullname':
                queryset = PoultryRequest.objects.filter(user__fullname=request.GET['value'], trash=False)
                serializer = PoultryRequestSerializer(queryset, many=True)
                return Response(serializer.data, status=status.HTTP_200_OK)

            elif request.GET['type'] == 'mobile':
                queryset = PoultryRequest.objects.filter(user__mobile=request.GET['value'], trash=False)
                serializer = PoultryRequestSerializer(queryset, many=True)
                return Response(serializer.data, status=status.HTTP_200_OK)

            elif request.GET['type'] == 'gis_code':
                queryset = PoultryRequest.objects.filter(user__gis_code=request.GET['value'], trash=False)
                serializer = PoultryRequestSerializer(queryset, many=True)
                return Response(serializer.data, status=status.HTTP_200_OK)

            elif request.GET['type'] == 'order_code':
                queryset = PoultryRequest.objects.get(order_code=int(request.GET['value']), trash=False)
                serializer = PoultryRequestSerializer(queryset)
                return Response(serializer.data, status=status.HTTP_200_OK)

            elif request.GET['type'] == 'bar_code':
                poultry = KillHouseRequest.objects.get(
                    bar_code=int(request.GET['value'])).province_request.city_request_Poultry.poultry_request
                queryset = PoultryRequest.objects.get(key=poultry.key, trash=False)
                serializer = PoultryRequestSerializer(queryset)
                return Response(serializer.data, status=status.HTTP_200_OK)

            elif request.GET['type'] == 'city':
                queryset = PoultryRequest.objects.filter(user__address__city=request.GET['value'], trash=False)
                serializer = PoultryRequestSerializer(queryset, many=True)
                return Response(serializer.data, status=status.HTTP_200_OK)

            elif request.GET['type'] == 'province':
                queryset = PoultryRequest.objects.filter(user__address__province=request.GET['value'], trash=False)
                serializer = PoultryRequestSerializer(queryset, many=True)
                return Response(serializer.data, status=status.HTTP_200_OK)

            return Response({"msg": "Enter 'Type' In Get Parameters"}, status=status.HTTP_403_FORBIDDEN)


# تابع برای کنسل کردن اتوماتیک درخواست بورسی مرغدار طبق شرایط خاص
@api_view(["POST"])
@csrf_exempt
@permission_classes([AllowAny])
def Cancel_Poultry_Exchange_request(request):
    for req in PoultryRequestExchange.objects.all():
        if (req.send_date - req.hatching_date).days > 65:
            req.trash = True
            req.save()
    return Response("ok")


def Check_Poultry_Auction_request():
    reqs = PoultryRequest.objects.filter(auction=True, final_state='pending', trash=False).order_by('send_date')
    for req in reqs:
        now = datetime.datetime.now()
        kill_house_auction = KillHouseRequestAction.objects.filter(poultry_request=req, trash=False).order_by('fee')
        auction = PoultryRequestAuction.objects.filter(poultry_request=req, state='active', trash=False)
        if auction.count() > 0:
            auction = auction.last()
            if now.year >= auction.auction_date.year and now.month >= auction.auction_date.month and now.day >= auction.auction_date.day and now.hour >= auction.auction_date.hour and now.minute >= auction.auction_date.minute:
                if kill_house_auction.count() > 0:
                    kill_house_auction = kill_house_auction.last()
                    kill_house_auction_win = KillHouseRequestActionWinner(
                        kill_house_request_auction=kill_house_auction,
                        fee=kill_house_auction.fee,
                        quantity=req.quantity
                    )
                    kill_house_auction_win.save()
                    req.auction = False
                    req.save()
                    auction.state = 'complete'
                    auction.save()
                    kill_house_auction.state = 'accepted'
                    kill_house_auction.save()
                    kill_house_aucs = KillHouseRequestAction.objects.filter(poultry_request=req, state='pending',
                                                                            trash=False)
                    for kill_house_auc in kill_house_aucs:
                        kill_house_auc.state = 'unaccepted'
                        kill_house_auc.save()
                    auctions = PoultryRequestAuction.objects.filter(poultry_request=req, state='inactive',
                                                                    trash=False)
                    for auc in auctions:
                        auc.state = 'complete'
                        auc.save()

                else:

                    auction.state = 'complete'
                    auction.save()
                    auctions = PoultryRequestAuction.objects.filter(poultry_request=req, state='inactive',
                                                                    trash=False).order_by(
                        'auction_date')
                    if auctions.count() > 0:
                        for auction in auctions:
                            auction.state = 'active'
                            auction.save()
                            break
                    else:
                        if req.union == True:
                            req.auction = False
                            req.save()
                            city_operator_check_request = CityOperatorCheckRequest.objects.get(poultry_request=req,
                                                                                               trash=False)
                            city_operator_check_request.show_province = True
                            city_operator_check_request.save()

    return Response({"result": "system checked"}, status=status.HTTP_200_OK)


@api_view(["POST"])
@csrf_exempt
@permission_classes([AllowAny])
def Check_Poultry_Auction_request_front(request):
    reqs = PoultryRequest.objects.filter(auction=True, final_state='pending', trash=False).order_by('send_date')
    for req in reqs:
        now = datetime.datetime.now()
        kill_house_auction = KillHouseRequestAction.objects.filter(poultry_request=req, trash=False).order_by('fee')
        auction = PoultryRequestAuction.objects.filter(poultry_request=req, state='active', trash=False)
        if auction.count() > 0:
            auction = auction.last()
            if now.year >= auction.auction_date.year and now.month >= auction.auction_date.month and now.day >= auction.auction_date.day and now.hour >= auction.auction_date.hour and now.minute >= auction.auction_date.minute:
                if kill_house_auction.count() > 0:
                    kill_house_auction = kill_house_auction.last()
                    kill_house_auction_win = KillHouseRequestActionWinner(
                        kill_house_request_auction=kill_house_auction,
                        fee=kill_house_auction.fee,
                        quantity=req.quantity
                    )
                    kill_house_auction_win.save()
                    req.auction = False
                    req.save()
                    auction.state = 'complete'
                    auction.save()
                    kill_house_auction.state = 'accepted'
                    kill_house_auction.save()
                    kill_house_aucs = KillHouseRequestAction.objects.filter(poultry_request=req, state='pending',
                                                                            trash=False)
                    for kill_house_auc in kill_house_aucs:
                        kill_house_auc.state = 'unaccepted'
                        kill_house_auc.save()
                    auctions = PoultryRequestAuction.objects.filter(poultry_request=req, state='inactive',
                                                                    trash=False)
                    for auc in auctions:
                        auc.state = 'complete'
                        auc.save()
                else:

                    auction.state = 'complete'
                    auction.save()
                    auctions = PoultryRequestAuction.objects.filter(poultry_request=req, state='inactive',
                                                                    trash=False).order_by(
                        'auction_date')
                    if auctions.count() > 0:
                        for auction in auctions:
                            auction.state = 'active'
                            auction.save()
                            break
                    else:
                        if req.union == True:
                            req.auction = False
                            req.save()
                            city_operator_check_request = CityOperatorCheckRequest.objects.get(poultry_request=req,
                                                                                               trash=False)
                            city_operator_check_request.show_province = True
                            city_operator_check_request.save()

    return Response({"result": "system checked"}, status=status.HTTP_200_OK)


class Chicken_informationViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    serializer_class = PoultryHatchingSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)

        poultry_list = []
        quantity_list = []

        now = datetime.datetime.now().date()

        poultryhatchings = PoultryHatching.objects.filter(state='pending', trash=False)
        if poultryhatchings.count() > 0:
            if 'age1' in request.GET:
                if 'age2' in request.GET:
                    for poultryhatching in poultryhatchings:
                        if int(request.GET['age1']) <= (now - poultryhatching.date.date()).days + 1 and (
                                now - poultryhatching.date.date()).days + 1 <= int(request.GET['age2']):
                            quantity_list.append(poultryhatching.quantity)

                            internal_dict = {
                                "full_name": poultryhatching.poultry.user.fullname,
                                "mobile": poultryhatching.poultry.user.mobile,
                                "city": poultryhatching.poultry.user.city.name,
                                "province": poultryhatching.poultry.user.province.name,
                                "unit_name": poultryhatching.poultry.unit_name,
                                "breeding_unique_id": poultryhatching.poultry.breeding_unique_id,
                                "quantity": quantity_list,
                            }
                    poultry_list.append(internal_dict)
                else:
                    for poultryhatching in poultryhatchings:
                        if (now - poultryhatching.date.date()).days + 1 == int(request.GET['age1']):
                            internal_dict = {
                                "full_name": poultryhatching.poultry.user.fullname,
                                "mobile": poultryhatching.poultry.user.mobile,
                                "city": poultryhatching.poultry.user.city.name,
                                "province": poultryhatching.poultry.user.province.name,
                                "unit_name": poultryhatching.poultry.unit_name,
                                "breeding_unique_id": poultryhatching.poultry.breeding_unique_id,
                                "quantity": poultryhatching.quantity,
                            }
                            poultry_list.append(internal_dict)

                return Response(poultry_list, status=status.HTTP_200_OK)


class SingleAgeHatchingStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):

        now = timezone.now().date()
        ages_list = []
        hatching_list = []
        hatches = PoultryHatching.objects.filter(state='pending', allow_hatching='pending', archive=False
                                                 , trash=False).order_by(
            '-date')
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                hatchs = hatches.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                hatchs = hatches.filter(poultry__address__city=user.city)
            else:
                hatchs = hatches
        else:
            hatchs = hatches
        for hatch in hatchs:
            if (now - hatch.date.date()).days + 1 not in ages_list:
                ages_list.append((now - hatch.date.date()).days + 1)

        # age_difference = ExpressionWrapper(now - F('date'), output_field=DurationField())
        # hatchs = hatchs.annotate(age_difference=age_difference)
        for age_list in ages_list:
            quantity = 0
            losses = 0
            for hatch in hatchs:
                age = (now - hatch.date.date()).days + 1
                if age == age_list:
                    quantity += hatch.left_over
                    losses += hatch.losses
            hatching_list.append({
                "type": age_list,
                "quantity": quantity,
                "losses": losses,
            })
        return Response(hatching_list, status=status.HTTP_200_OK)


class DoughnutHatchingStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):

        year = datetime.datetime.now().year
        total = 0
        city_list = []
        hatching_list = []
        hatchings_list = []
        hatchingss_lists = PoultryHatching.objects.filter(state='pending', allow_hatching='pending',
                                                          archive=False).order_by(
            '-date')
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                hatchingss_list = hatchingss_lists.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                hatchingss_list = hatchingss_lists.filter(poultry__address__city=user.city)
            else:
                hatchingss_list = hatchingss_lists
        else:
            hatchingss_list = hatchingss_lists
        for hatchingss in hatchingss_list:
            if (jdatetime.datetime.fromgregorian(year=hatchingss.date.year, month=hatchingss.date.month,
                                                 day=hatchingss.date.day)).month == int(request.GET['month']):
                hatchings_list.append(hatchingss)
                total += hatchingss.quantity
                if hatchingss.poultry.address.city not in city_list:
                    city_list.append(hatchingss.poultry.address.city)

        for city in city_list:
            quantity = 0
            for hatch in hatchings_list:
                if hatch.poultry.address.city == city:
                    quantity += hatch.quantity
            hatching_list.append({
                "city": city.name,
                "percent": round((quantity / total) * 100, 2),
                "quantity": quantity,
            })

        return Response(hatching_list, status=status.HTTP_200_OK)


class DoughnutHatchingLeftOverStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):

        year = datetime.datetime.now().year
        total = 0
        city_list = []
        hatching_list = []
        hatchings_list = []
        hatchingss_lists = PoultryHatching.objects.filter(state='pending', allow_hatching='pending',
                                                          archive=False).order_by(
            '-date')
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                hatchingss_list = hatchingss_lists.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                hatchingss_list = hatchingss_lists.filter(poultry__address__city=user.city)
            else:
                hatchingss_list = hatchingss_lists
        else:
            hatchingss_list = hatchingss_lists
        for hatchingss in hatchingss_list:
            if (jdatetime.datetime.fromgregorian(year=hatchingss.date.year, month=hatchingss.date.month,
                                                 day=hatchingss.date.day)).month == int(request.GET['month']):
                hatchings_list.append(hatchingss)
                total += hatchingss.left_over
                if hatchingss.poultry.address.city not in city_list:
                    city_list.append(hatchingss.poultry.address.city)

        for city in city_list:
            quantity = 0
            for hatch in hatchings_list:
                if hatch.poultry.address.city == city:
                    quantity += hatch.left_over
            hatching_list.append({
                "city": city.name,
                "percent": round((quantity / total) * 100, 2),
                "quantity": quantity,
            })

        return Response(hatching_list, status=status.HTTP_200_OK)


class HatchingStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):
        # user = SystemUserProfile.objects.get(user=request.user)
        now = timezone.now().date()
        age_ranges = [
            (1, 5), (6, 10), (11, 15), (16, 20), (21, 25), (26, 30),
            (31, 35), (36, 40), (41, 45), (46, 50), (51, 55), (56, 60), (61, 65), (66, 70), (71, 75), (76, 80),
            (81, 85), (86, 90), (91, 95), (96, 100)
        ]

        age_ranges_dict = {f"{start}_{end}": {"quantity": 0, "losses": 0} for start, end in age_ranges}

        hatches = PoultryHatching.objects.filter(state='pending', allow_hatching='pending', archive=False,
                                                 trash=False).order_by(
            'date')

        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                hatchs = hatches.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                hatchs = hatches.filter(poultry__address__city=user.city)
            else:
                hatchs = hatches
        else:
            hatchs = hatches
        for hatch in hatchs:
            age = (now - hatch.date.date()).days + 1
            for age_range, range_data in age_ranges_dict.items():
                start_age, end_age = map(int, age_range.split('_'))
                if start_age <= age <= end_age:
                    range_data["quantity"] += hatch.left_over
                    range_data["losses"] += hatch.losses

        information_list = [{"type": age_range, **data} for age_range, data in age_ranges_dict.items()]

        return Response(information_list)


class PoultryRequestProcessDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):

        poultry_request_quantity = 0
        poultry_request_index_weight = 0
        poultry_quantity = 0
        poultry_list = []
        now = datetime.datetime.now().date()
        poultry_reqs = PoultryRequest.objects.filter(state_process='accepted', province_state='accepted',
                                                     archive=False, send_date__year=now.year,
                                                     send_date__month=now.month, send_date__day=now.day,
                                                     trash=False).select_related(
            'poultry').only('poultry', 'quantity', 'Index_weight')
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                poultry_requests = poultry_reqs.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                poultry_requests = poultry_reqs.filter(poultry__address__city=user.city)
            else:
                poultry_requests = poultry_reqs
        else:
            poultry_requests = poultry_reqs
        for poultry_request in poultry_requests:
            if poultry_request.poultry not in poultry_list:
                poultry_list.append(poultry_request.poultry)

            poultry_request_quantity += poultry_request.quantity
            poultry_request_index_weight += round(poultry_request.quantity * poultry_request.Index_weight)
            poultry_quantity = len(poultry_list)

        # province_kill_requests_list = ProvinceKillRequest.objects.filter(state='accepted', trash=False).select_related(
        #     'province_request__poultry_request', 'kill_request__kill_house').only(
        #     'province_request__poultry_request__Index_weight', 'quantity', 'kill_request__kill_house')
        #
        # province_kill_requests = [
        #     province_kill_request_list for province_kill_request_list in province_kill_requests_list
        #     if date1 <= province_kill_request_list.kill_request.recive_date.date() <= date2
        # ]
        # for province_kill_request in province_kill_requests:
        #     if province_kill_request.kill_request.kill_house not in kill_house_list:
        #         kill_house_list.append(province_kill_request.kill_request.kill_house)
        #     province_kill_request_index_weight += province_kill_request.quantity * province_kill_request.province_request.poultry_request.Index_weight
        #     province_kill_request_quantity += province_kill_request.quantity
        #     kill_house_quantity = len(kill_house_list)
        #
        # kill_house_requests_list = KillHouseRequest.objects.filter(trash=False).select_related(
        #     'province_kill_request__province_request__poultry_request', 'kill_request').only(
        #     'province_kill_request__province_request__poultry_request__Index_weight', 'kill_request', 'quantity',
        #     'vet_state')
        #
        # kill_house_requests = [
        #     kill_house_request_list for kill_house_request_list in kill_house_requests_list
        #     if date1 <= kill_house_request_list.kill_request.recive_date.date() <= date2
        # ]
        # for kill_house_request in kill_house_requests:
        #     kill_house_assignment_information = KillHouseAssignmentInformation.objects.filter(
        #         kill_house_request=kill_house_request, trash=False).only('net_weight').last()
        #     if kill_house_assignment_information:
        #         kill_house_request_weight += kill_house_assignment_information.net_weight
        #     else:
        #
        #         kill_house_request_weight += kill_house_request.quantity * kill_house_request.province_kill_request.province_request.poultry_request.Index_weight
        #     if kill_house_request.clearance_code != None:
        #         clearance_code_counter += 1
        #     if kill_house_request.vet_state == 'accepted':
        #         vet_state_counter += 1
        #     kill_house_request_quantity += kill_house_request.quantity
        return Response({
            "poultry_quantity": poultry_quantity,
            "poultry_request_quantity": poultry_request_quantity,
            "poultry_request_index_weight": poultry_request_index_weight,
            # "province_kill_request_quantity": province_kill_request_quantity,
            # "province_kill_request_index_weight": province_kill_request_index_weight,
            # "kill_house_quantity": kill_house_quantity,
            # "clearance_code_counter": clearance_code_counter,
            # "kill_house_request_quantity": kill_house_request_quantity,
            # "kill_house_request_weight": kill_house_request_weight,
            # "vet_state_counter": vet_state_counter,
        })


class ProvinceKillRequestProcessDashboardViewSet(viewsets.ModelViewSet):
    queryset = ProvinceKillRequest.objects.all()
    permission_classes = [AllowAny]
    serializer_class = ProvinceKillRequestSerializer

    def list(self, request, *args, **kwargs):

        province_kill_request_quantity = 0
        province_kill_request_index_weight = 0
        kill_house_quantity = 0
        kill_house_list = []
        now = datetime.datetime.now().date()

        province_kill_reqs = ProvinceKillRequest.objects.filter(state__in=('accepted', 'pending'),
                                                                kill_request__recive_date__year=now.year,
                                                                kill_request__recive_date__month=now.month,
                                                                kill_request__recive_date__day=now.day,
                                                                trash=False).select_related(
            'province_request__poultry_request', 'kill_request__kill_house').only(
            'province_request__poultry_request__Index_weight', 'quantity', 'kill_request__kill_house')

        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                province_kill_requests = province_kill_reqs.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                province_kill_requests = province_kill_reqs.filter(
                    province_request__poultry_request__poultry__address__city=user.city)
            else:
                province_kill_requests = province_kill_reqs
        else:
            province_kill_requests = province_kill_reqs

        for province_kill_request in province_kill_requests:
            if province_kill_request.kill_request.kill_house not in kill_house_list:
                kill_house_list.append(province_kill_request.kill_request.kill_house)
            province_kill_request_index_weight += province_kill_request.main_quantity * province_kill_request.province_request.poultry_request.Index_weight
            province_kill_request_quantity += province_kill_request.main_quantity
            kill_house_quantity = len(kill_house_list)
        return Response({
            "province_kill_request_quantity": province_kill_request_quantity,
            "province_kill_request_index_weight": province_kill_request_index_weight,
            "kill_house_quantity": kill_house_quantity,
        })


class KillHouseRequestVetFarmProcessDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    permission_classes = [AllowAny]
    serializer_class = KillHouseRequestSerializer

    def list(self, request, *args, **kwargs):

        kill_house_request_quantity = 0
        kill_house_request_weight = 0
        clearance_code_counter = 0
        now = datetime.datetime.now().date()

        kill_house_reqs = KillHouseRequest.objects.filter(kill_request__recive_date__year=now.year,
                                                          kill_request__recive_date__month=now.month,
                                                          kill_request__recive_date__day=now.day,
                                                          trash=False).select_related(
            'province_kill_request__province_request__poultry_request', 'kill_request').only(
            'province_kill_request__province_request__poultry_request__Index_weight', 'kill_request', 'quantity',
            'vet_state', 'clearance_code')
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                kill_house_requests = kill_house_reqs.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                kill_house_requests = kill_house_reqs.filter(
                    province_request__poultry_request__poultry__address__city=user.city)
            else:
                kill_house_requests = kill_house_reqs
        else:
            kill_house_requests = kill_house_reqs

        for kill_house_request in kill_house_requests:
            kill_house_assignment_information = KillHouseAssignmentInformation.objects.filter(
                kill_house_request=kill_house_request, trash=False).only('net_weight').last()
            if kill_house_assignment_information:
                kill_house_request_weight += kill_house_assignment_information.net_weight
            else:

                kill_house_request_weight += kill_house_request.quantity * kill_house_request.province_kill_request.province_request.poultry_request.Index_weight
            if kill_house_request.clearance_code != None:
                clearance_code_counter += 1
            kill_house_request_quantity += kill_house_request.quantity
        return Response({
            "kill_house_quantity": kill_house_request_quantity,
            "clearance_code_counter": clearance_code_counter,
            "kill_house_request_weight": kill_house_request_weight,
        })


class KillHouseRequestVetProcessDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    permission_classes = [AllowAny]
    serializer_class = KillHouseRequestSerializer

    def list(self, request, *args, **kwargs):

        kill_house_request_quantity = 0
        kill_house_request_weight = 0
        vet_check_counter = 0
        now = datetime.datetime.now().date()

        kill_house_reqs = KillHouseRequest.objects.filter(kill_request__recive_date__year=now.year,
                                                          kill_request__recive_date__month=now.month,
                                                          kill_request__recive_date__day=now.day,
                                                          trash=False, vet_state='accepted').select_related(
            'province_kill_request__province_request__poultry_request', 'kill_request').only(
            'province_kill_request__province_request__poultry_request__Index_weight', 'kill_request', 'quantity',
            'vet_state')

        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(user=request.user)
                city_operator = CityOperator.objects.get(trash=False, user=user)
                kill_house_requests = kill_house_reqs.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                kill_house_requests = kill_house_reqs.filter(
                    province_request__poultry_request__poultry__address__city=user.city)
            else:
                kill_house_requests = kill_house_reqs
        else:
            kill_house_requests = kill_house_reqs

        for kill_house_request in kill_house_requests:
            kill_house_assignment_information = KillHouseAssignmentInformation.objects.filter(
                kill_house_request=kill_house_request, trash=False).only('net_weight').last()
            if kill_house_assignment_information:
                kill_house_request_weight += kill_house_assignment_information.net_weight
            else:

                kill_house_request_weight += kill_house_request.quantity * kill_house_request.province_kill_request.province_request.poultry_request.Index_weight
            if kill_house_request.vet_state == 'accepted':
                vet_check_counter += 1
            kill_house_request_quantity += kill_house_request.quantity
        return Response({
            "kill_house_quantity": kill_house_request_quantity,
            "vet_check_counter": vet_check_counter,
            "kill_house_request_weight": kill_house_request_weight,
        })


class TotalPoultryRequestStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryRequestSerializer

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        accepted_poultry_request_quantity = 0
        accepted_kill_house_request_quantity = 0
        poultry_reqs = PoultryRequest.objects.filter(state_process__in=('pending', 'accepted'),
                                                     province_state__in=('pending', 'accepted'),
                                                     trash=False).only(
            'quantity', 'province_state',
            'state_process')
        kill_house_reqs = KillHouseRequest.objects.filter(trash=False).only('quantity', 'vet_state')

        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user=user)
                poultry_requests = poultry_reqs.filter(poultry__city_operator=city_operator.unit_name)
                kill_house_requests = kill_house_reqs.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                poultry_requests = poultry_reqs.filter(poultry__address__city=user.city)
                kill_house_requests = kill_house_reqs.filter(
                    province_request__poultry_request__poultry__address__city=user.city)

            else:
                poultry_requests = poultry_reqs
                kill_house_requests = kill_house_reqs
        else:
            poultry_requests = poultry_reqs
            kill_house_requests = kill_house_reqs
        total_poultry_request_quantity = poultry_requests.aggregate(total_quantity=Sum('quantity')).get(
            'total_quantity', 0)
        for poultry_request in poultry_requests:
            if poultry_request.state_process == 'accepted' and poultry_request.province_state == 'accepted' and poultry_request.archive == False:
                accepted_poultry_request_quantity += poultry_request.quantity
        total_kill_house_request_quantity = kill_house_requests.aggregate(total_quantity=Sum('quantity')).get(
            'total_quantity', 0)
        for kill_house_request in kill_house_requests:
            if kill_house_request.vet_state == 'accepted':
                accepted_kill_house_request_quantity += kill_house_request.quantity
        return Response({
            "total_poultry_request_quantity": total_poultry_request_quantity,
            "accepted_poultry_request_quantity": accepted_poultry_request_quantity,
            "total_kill_house_request_quantity": total_kill_house_request_quantity,
            "accepted_kill_house_request_quantity": accepted_kill_house_request_quantity,
        })


class TotalFilePoultryRequestStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    permission_classes = [AllowAny]
    serializer_class = PoultryRequestSerializer

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        accepted_poultry_request_quantity = 0
        rejected_poultry_request_quantity = 0
        archive_poultry_request_quantity = 0
        poultry_reqs = PoultryRequest.objects.filter(trash=False).only('quantity', 'province_state',
                                                                       'state_process', 'archive',
                                                                       'final_state')
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user=user)
                poultry_requests = poultry_reqs.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                poultry_requests = poultry_reqs.filter(poultry__address__city=user.city)
            else:
                poultry_requests = poultry_reqs
        else:
            poultry_requests = poultry_reqs
        for poultry_request in poultry_requests:
            if poultry_request.state_process == 'accepted' and poultry_request.province_state == 'accepted' and poultry_request.archive == False:
                accepted_poultry_request_quantity += 1
            if poultry_request.province_state == 'rejected' or poultry_request.state_process == 'rejected':
                rejected_poultry_request_quantity += 1
            if poultry_request.archive == True:
                archive_poultry_request_quantity += 1

        return Response({
            "total_poultry_request_quantity": poultry_requests.count(),
            "accepted_poultry_request_quantity": accepted_poultry_request_quantity,
            "rejected_poultry_request_quantity": rejected_poultry_request_quantity,
            "archive_poultry_request_quantity": archive_poultry_request_quantity,
        })


class TotalPoultryHatchingStatisticsDashboardViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingSerializer
    filterset_class = PoultryManageFilterSet

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        poultreis = Poultry.objects.filter(trash=False).select_related('user', 'address__province', 'address__city')
        if 'role' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user)
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user=user)
                poultrys = poultreis.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                poultrys = poultreis.filter(poultry__user__city=user.city)
            else:
                poultrys = poultreis
        else:
            poultrys = poultreis
        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                poultrys = poultreis.filter(
                    build_query(self.filterset_class, value)
                )
        all_period = 0
        all_total_quantity = 0
        all_hatching_pending = 0
        all_total_quantity_poultry_hatching_pending = 0
        all_total_left_over_poultry_hatching_pending = 0
        all_kill_request = 0
        all_kill_request_quantity = 0
        all_all_weight_loss = 0
        len_werhouse_enter = 0
        for poultry in poultrys:
            poultry_hatching = PoultryHatching.objects.filter(poultry=poultry, trash=False).only('quantity', 'left_over'
                                                                                                 )
            if poultry_hatching:

                poultry_hatching_pending = poultry_hatching.filter(state='pending', allow_hatching='pending',
                                                                   archive=False).last()
                if poultry_hatching_pending:
                    all_hatching_pending += 1
                if poultry_hatching_pending:
                    period = poultry_hatching_pending.period
                else:
                    period = poultry_hatching.last().period
                all_period += period
                poultry_hatching_pending1 = poultry_hatching.filter(state='pending', allow_hatching='pending',
                                                                    archive=False)
                total_quantity = \
                    poultry_hatching.aggregate(total=Sum('quantity'))[
                        'total'] or 0
                total_quantity_poultry_hatching_pending = \
                    poultry_hatching_pending1.aggregate(total=Sum('quantity'))[
                        'total'] or 0
                total_left_over_poultry_hatching_pending = \
                    poultry_hatching_pending1.aggregate(total=Sum('left_over'))[
                        'total'] or 0
                all_total_quantity += total_quantity
                all_total_quantity_poultry_hatching_pending += total_quantity_poultry_hatching_pending
                all_total_left_over_poultry_hatching_pending += total_left_over_poultry_hatching_pending
                poultry_request = PoultryRequest.objects.filter(trash=False, poultry=poultry,
                                                                state_process__in=('accepted', 'pending'),
                                                                province_state__in=('accepted', 'pending')).only(
                    'quantity', 'Index_weight')
                kill_request = KillHouseRequest.objects.filter(trash=False,
                                                               province_request__poultry_request__in=poultry_request).only(
                    'accepted_real_quantity', 'accepted_real_weight')

                all_kill_request += len(kill_request)
                kill_request_quantity = kill_request.aggregate(
                    total=Sum('accepted_real_quantity'))[
                                            'total'] or 0
                all_kill_request_quantity += kill_request_quantity

                werhouse_enter = kill_request.filter(ware_house_confirmation=True).only(
                    'ware_house_accepted_real_quantity',
                    'ware_house_accepted_real_weight',
                    'weight_loss')

                all_weight_loss = werhouse_enter.aggregate(
                    total_quantity=Sum('weight_loss')).get(
                    'total_quantity', 0) or 0
                all_all_weight_loss += all_weight_loss
                len_werhouse_enter += len(werhouse_enter)

        return Response({
            "poultryCounts": len(poultrys),
            "allPeriod": all_period,
            "allTotalQuantity": all_total_quantity,
            "hatchingPending": all_hatching_pending,
            "totalQuantityPoultryHatchingPending": all_total_quantity_poultry_hatching_pending,
            "totalLeftOverPoultryHatchingPending": all_total_left_over_poultry_hatching_pending,
            "allKillRequest": all_kill_request,
            "allKillRequestQuantity": all_kill_request_quantity,
            "percentLoss": round(int(all_all_weight_loss) / len_werhouse_enter, 2) if len_werhouse_enter > 0 else 0,
        })


# test
class Chart_DashbourdViewSet(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryHatchingSerializer

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        poultry_hatching = {}
        price_dict = {}
        price_list = []
        poultry_requests = {}
        kill_house_requests = {}
        operators = {}
        prices = {}
        file = {}
        box = {}
        total_users = 0
        number_of_users = 0
        number_of_operators = 0
        chicken_price = 0
        celling_chicken_price = 0
        floor_chicken_price = 0
        total_users = 0
        total_hatching = 0
        total_lossess = 0
        real_hatching = 0
        total_list = []
        killcapacity = 0
        poultryquentity = 0

        now = datetime.datetime.now().date()
        quantity_1_5 = 0
        quantity_1_5_losses = 0
        quantity_5_10 = 0
        quantity_5_10_losses = 0
        quantity_10_15 = 0
        quantity_10_15_losses = 0
        quantity_15_20 = 0
        quantity_15_20_losses = 0

        quantity_20_25 = 0
        quantity_20_25_losses = 0
        quantity_25_30 = 0
        quantity_25_30_losses = 0
        quantity_30_35 = 0
        quantity_30_35_losses = 0
        quantity_35_40 = 0
        quantity_35_40_losses = 0
        quantity_40_45 = 0
        quantity_40_45_losses = 0
        quantity_45_50 = 0
        quantity_45_50_losses = 0
        quantity_50_55 = 0
        quantity_50_55_losses = 0
        quantity_55_60 = 0
        quantity_55_60_losses = 0

        killreques_10 = 0
        killreques_20 = 0
        killreques_30 = 0
        killreques_40 = 0
        killreques_50 = 0
        killreques_60 = 0

        if 'city' in request.GET:
            hatchs = PoultryHatching.objects.filter(state='pending',
                                                    poultry__address__city__name=request.GET['city'],
                                                    poultry__address__province=user.province)

        elif 'breed' in request.GET:
            hatchs = PoultryHatching.objects.filter(state='pending', chicken_breed=request.GET['breed'],
                                                    poultry__address__province=user.province)
        else:
            hatchs = PoultryHatching.objects.filter(state='pending', poultry__address__province=user.province)

        if hatchs.count() > 0:

            for hatch in hatchs:
                age = (now - hatch.date.date()).days + 1
                if age >= 1 and age <= 5:
                    quantity_1_5 += hatch.quantity
                    quantity_1_5_losses += hatch.losses

                elif age >= 5 and age <= 10:
                    quantity_5_10 += hatch.quantity
                    quantity_5_10_losses += hatch.losses

                elif age >= 10 and age <= 15:
                    quantity_10_15 += hatch.quantity
                    quantity_10_15_losses += hatch.losses

                elif age >= 15 and age <= 20:
                    quantity_15_20 += hatch.quantity
                    quantity_15_20_losses += hatch.losses

                elif age >= 20 and age <= 25:
                    quantity_20_25 += hatch.quantity
                    quantity_20_25_losses += hatch.losses


                elif age >= 25 and age <= 30:
                    quantity_25_30 += hatch.quantity
                    quantity_25_30_losses += hatch.losses

                elif age >= 30 and age <= 35:
                    quantity_30_35 += hatch.quantity
                    quantity_30_35_losses += hatch.losses

                elif age >= 35 and age <= 40:
                    quantity_35_40 += hatch.quantity
                    quantity_35_40_losses += hatch.losses

                elif age >= 40 and age <= 45:
                    quantity_40_45 += hatch.quantity
                    quantity_40_45_losses += hatch.losses

                elif age >= 45 and age <= 50:
                    quantity_45_50 += hatch.quantity
                    quantity_45_50_losses += hatch.losses

                elif age >= 50 and age <= 55:
                    quantity_50_55 += hatch.quantity
                    quantity_50_55_losses += hatch.losses

                elif age >= 55 and age <= 60:
                    quantity_55_60 += hatch.quantity
                    quantity_55_60_losses += hatch.losses
            information_list = [
                {"type": "1_5", "quantity": quantity_1_5, "losses": quantity_1_5_losses},
                {"type": "5_10", "quantity": quantity_5_10, "losses": quantity_5_10_losses},
                {"type": "10_15", "quantity": quantity_10_15, "losses": quantity_10_15_losses},
                {"type": "15_20", "quantity": quantity_15_20, "losses": quantity_15_20_losses},
                {"type": "20_25", "quantity": quantity_20_25, "losses": quantity_20_25_losses},
                {"type": "25_30", "quantity": quantity_25_30, "losses": quantity_25_30_losses},
                {"type": "30_35", "quantity": quantity_30_35, "losses": quantity_30_35_losses},
                {"type": "35_40", "quantity": quantity_35_40, "losses": quantity_35_40_losses},
                {"type": "40_45", "quantity": quantity_40_45, "losses": quantity_40_45_losses},
                {"type": "45_50", "quantity": quantity_45_50, "losses": quantity_45_50_losses},
                {"type": "50_55", "quantity": quantity_50_55, "losses": quantity_5_10_losses},
                {"type": "55_60", "quantity": quantity_55_60, "losses": quantity_55_60_losses},

            ]
        else:
            information_list = []

        poultry_hatching.update({"poultry_hatching": information_list})

        total_list.append(poultry_hatching)

        pricing = Pricing.objects.all()
        price_internal_dict = {}
        for price in pricing:
            inter_dict = {
                "price": price.live_chicken_price,
                "date": price.date
            }
            price_list.append(inter_dict)
            inter_dict = {}
        price_internal_dict.update({"price_list": price_list})
        total_list.append(price_internal_dict)

        poultry = Poultry.objects.filter(user__province=user.province)
        city_operator = CityOperator.objects.filter(user__province=user.province)
        province_operator = ProvinceOperator.objects.filter(user__province=user.province,
                                                            user__role__name='ProvinceOperator')
        financial_operator = Poultry.objects.filter(user__province=user.province,
                                                    user__role__name='ProvinceFinancial')
        inspector_operator = InspectorOperator.objects.filter(user__province=user.province)
        killhouse_operator = KillHouseOperator.objects.filter(user__province=user.province)
        driver = KillHouseDriver.objects.filter(user__province=user.province)
        vet = Vet.objects.filter(user__province=user.province)
        killhouse_vet = KillHouseVet.objects.filter(vet__user__province=user.province)
        total_users = poultry.count() + city_operator.count() + province_operator.count() + financial_operator.count() + inspector_operator.count() + killhouse_operator.count() + vet.count() + driver.count()
        number_of_users = poultry.count() + killhouse_operator.count() + vet.count() + driver.count()
        number_of_operators = city_operator.count() + province_operator.count() + financial_operator.count() + inspector_operator.count()

        poultry_reqs = PoultryRequest.objects.filter(poultry__address__province=user.province)
        files_count = []
        active = 0
        archive = 0
        rejected = 0
        if poultry_reqs.count() > 0:

            for poultry_req in poultry_reqs:
                if poultry_req.final_state == 'pending':
                    active += 1
                if poultry_req.final_state == 'archive':
                    archive += 1
                if poultry_req.state_process == 'rejected' or poultry_req.province_state == 'rejected':
                    rejected += 1
        poultyry_hachting = PoultryHatching.objects.filter(state='pending',
                                                           poultry__address__province=user.province)
        if poultyry_hachting.count() > 0:
            for hatching in poultyry_hachting:
                total_hatching += hatching.quantity
                total_lossess += hatching.losses
                real_hatching = total_hatching - total_lossess

        pricies = Pricing.objects.all()

        if pricies.count() > 0:
            price = pricies.last()
            chicken_price = price.live_chicken_price
            celling_chicken_price = price.ceiling_price
            floor_chicken_price = price.floor_price

        poultryrequests = PoultryRequest.objects.filter(state_process='accepted')

        if poultryrequests.count() > 0:
            for poultryrequest in poultryrequests:
                poultryquentity += poultryrequest.quantity

        box.update({"box": {"total_users": total_users, "number_of_users": number_of_users,
                            "number_of_operators": number_of_operators, "number_of_active_files": active,
                            "number_of_archive_files": archive, "number_of_rejected_files": rejected,
                            "total_hatching": total_hatching, "total_lossess": total_lossess,
                            "real_hatching": real_hatching, "price": chicken_price,
                            "floor_price": floor_chicken_price, "celling_price": celling_chicken_price,
                            "killcapacity": killcapacity, "poultryquentity": poultryquentity}})
        total_list.append(box)

        return Response(total_list, status=status.HTTP_200_OK)


class PoultryRequestInformation(viewsets.ModelViewSet):
    queryset = PoultryHatching.objects.all()
    serializer_class = PoultryHatchingSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        poultry_hatchings = PoultryHatching.objects.filter(state='pending', trash=False)
        l = []

        for hatch in poultry_hatchings:
            if PoultryRequest.objects.filter(hatching_id=hatch.id).exists():
                inter_dict = {
                    "period": hatch.period,
                    "breed": hatch.chicken_breed,
                    "hatching_date": hatch.create_date,
                    "losses": hatch.losses
                }
                l.append(inter_dict)
        return Response(l, status=status.HTTP_200_OK)


class TotalPoultryRequestQuantityForCitryViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        city_operator = CityOperator.objects.get(user=SystemUserProfile.objects.get(user=request.user))
        poultry_list = []
        total_quantity = 0
        first_quantity = 0
        accepted_quantity = 0
        city_accepted_quantity = 0
        allocated_quantity = 0
        kill_request_quantity = 0
        rejected_quantity = 0
        waiting_quantity = 0
        assignableQuantity = 0
        quantity_of_45 = 0
        now = datetime.datetime.strptime(request.GET['date'],
                                         '%Y-%m-%d').date() if 'date' in request.GET else datetime.datetime.now().date()

        hatchings = PoultryHatching.objects.filter(trash=False, allow_hatching='pending', archive=False)
        if hatchings.count() > 0:

            for hatcing in hatchings:
                if (now - hatcing.date.date()).days + 1 <= 65 and (now - hatcing.date.date()).days + 1 >= 45:
                    quantity_of_45 += hatcing.left_over

        poultry_requests = PoultryRequest.objects.filter(final_state='pending', city_operator=city_operator,
                                                         trash=False,
                                                         out=False, send_date__year=now.year,
                                                         send_date__month=now.month, send_date__day=now.day
                                                         )

        for poultry_request in poultry_requests:
            if poultry_request.province_state == 'accepted' or poultry_request.province_state == 'pending':
                total_quantity += poultry_request.quantity
                first_quantity += poultry_request.first_quantity
                if poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(poultry_request.poultry)
            if poultry_request.state_process == 'accepted':
                city_accepted_quantity += poultry_request.quantity
                if poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(poultry_request.poultry)

            if poultry_request.province_state == 'accepted':
                accepted_quantity += poultry_request.quantity
                assignableQuantity += poultry_request.remain_quantity
                province_kill_reqs = ProvinceKillRequest.objects.filter(
                    province_request__poultry_request=poultry_request,
                    trash=False, state__in=('pending', 'accepted'))
                if province_kill_reqs.count() > 0:
                    for province_kill_req in province_kill_reqs:
                        allocated_quantity += province_kill_req.main_quantity
                if poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(poultry_request.poultry)

            if poultry_request.province_state == 'rejected' or poultry_request.state_process == 'rejected':
                rejected_quantity += poultry_request.quantity
                if poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(poultry_request.poultry)

            if poultry_request.province_state == 'pending':
                if poultry_request.state_process == 'rejected':
                    continue
                else:
                    waiting_quantity += poultry_request.quantity
                if poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(poultry_request.poultry)

        dict1 = {
            "total_quantity": total_quantity,
            "first_quantity": first_quantity,
            "accepted_quantity": accepted_quantity,
            "city_accepted_quantity": city_accepted_quantity,
            "allocated_quantity": allocated_quantity,
            "kill_request_quantity": kill_request_quantity,
            "rejected_quantity": rejected_quantity,
            "waiting_quantity": waiting_quantity,
            "assignableQuantity": assignableQuantity,
            "quantity_of_45": quantity_of_45

        }
        return Response(dict1, status=status.HTTP_200_OK)


class TotalPoultryRequestQuantityViewSet(viewsets.ModelViewSet):
    queryset = TotalPoultryRequestQuantity.objects.all()
    serializer_class = TotalPoultryRequestQuantitySerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به ویرایش مرغداری
    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        now = datetime.datetime.now().date()
        total_poultry_request_quantity = TotalPoultryRequestQuantity.objects.get(key=request.data["key"],
                                                                                 trash=False)
        request.data.pop('key')
        for kill_house in KillHouse.objects.filter(system_address__province=user.province):
            percentage = KillHousePercentage.objects.get(kill_house=kill_house)
            percentage.quantity = percentage.percent / 100 * int(request.data['input_quantity'])
            percentage.save()
            kill_req = KillRequest.objects.filter(recive_date__year=now.year, recive_date__month=now.month,
                                                  recive_date__day=now.day, kill_house=kill_house)
            if kill_req.count() > 0:
                kill_req = kill_req.last()
                kill_req.kill_capacity = percentage.quantity
                kill_req.remain_quantity += percentage.quantity - kill_req.remain_quantity
                kill_req.save()
        serializer = self.serializer_class(total_poultry_request_quantity)
        serializer.update(instance=total_poultry_request_quantity, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    #  تابع مربوط به نمایش مرغداری
    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        poultry_list = []
        total_quantity = 0
        first_quantity = 0
        accepted_quantity = 0
        city_accepted_quantity = 0
        allocated_quantity = 0
        returned_quantity = 0
        direct_buying_quantity = 0
        kill_request_quantity = 0
        rejected_quantity = 0
        waiting_quantity = 0
        assignableQuantity = 0
        quantity_of_45 = 0
        if 'date' in request.GET:
            now = datetime.datetime.strptime(request.GET['date'], '%Y-%m-%d').date()
        else:
            now = datetime.datetime.now().date()

        hatchings = PoultryHatching.objects.filter(trash=False, allow_hatching='pending',
                                                   archive=False)

        if hatchings:
            for hatcing in hatchings:
                if (now - hatcing.date.date()).days + 1 <= 80:
                    if (now - hatcing.date.date()).days + 1 >= 45:
                        quantity_of_45 += hatcing.left_over

        poultry_requests = PoultryRequest.objects.filter(
            # final_state='pending',
            # province_state__in=('accepted', 'pending'),
            poultry__address__province=user.province, trash=False,
            out=False,
            # direct_buying=False,
            send_date__year=now.year, send_date__month=now.month,
            send_date__day=now.day)
        for poultry_request in poultry_requests:
            total_quantity += poultry_request.quantity
            first_quantity += poultry_request.first_quantity
            if poultry_request.poultry in poultry_list:
                pass
            else:
                poultry_list.append(poultry_request.poultry)
        city_accepted_poultry_requests = PoultryRequest.objects.filter(final_state='pending',
                                                                       state_process='accepted',
                                                                       poultry__address__province=user.province,
                                                                       trash=False,
                                                                       out=False,
                                                                       direct_buying=False,
                                                                       send_date__year=now.year,
                                                                       send_date__month=now.month,
                                                                       send_date__day=now.day)

        if city_accepted_poultry_requests.count() > 0:
            for city_accepted_poultry_request in city_accepted_poultry_requests:
                city_accepted_quantity += city_accepted_poultry_request.quantity
                if city_accepted_poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(city_accepted_poultry_request.poultry)

        accepted_poultry_requests = PoultryRequest.objects.filter(final_state='pending',
                                                                  province_state='accepted',
                                                                  poultry__address__province=user.province,
                                                                  trash=False,
                                                                  out=False,
                                                                  direct_buying=False,
                                                                  send_date__year=now.year,
                                                                  send_date__month=now.month,
                                                                  send_date__day=now.day)

        if accepted_poultry_requests.count() > 0:
            for accepted_poultry_request in accepted_poultry_requests:
                accepted_quantity += accepted_poultry_request.quantity
                assignableQuantity += accepted_poultry_request.remain_quantity
                if accepted_poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(accepted_poultry_request.poultry)

        rejected_requests = PoultryRequest.objects.filter(
            Q(province_state='rejected') | Q(state_process='rejected'),
            final_state='pending',
            poultry__address__province=user.province,
            trash=False,
            out=False,
            direct_buying=False,
            send_date__year=now.year,
            send_date__month=now.month,
            send_date__day=now.day)

        if rejected_requests.count() > 0:
            for rejected_request in rejected_requests:
                rejected_quantity += rejected_request.quantity
                if rejected_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(rejected_request.poultry)
        waiting_requests = PoultryRequest.objects.filter(final_state='pending',
                                                         province_state='pending',
                                                         poultry__address__province=user.province,
                                                         trash=False,
                                                         out=False,
                                                         direct_buying=False,
                                                         send_date__year=now.year,
                                                         send_date__month=now.month,
                                                         send_date__day=now.day)

        if waiting_requests.count() > 0:
            for waiting_request in waiting_requests:
                if waiting_request.state_process == 'rejected':
                    continue
                else:
                    waiting_quantity += waiting_request.quantity
                if waiting_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(waiting_request.poultry)

        allocated_poultry_requests = PoultryRequest.objects.filter(final_state='pending',
                                                                   province_state='accepted',
                                                                   poultry__address__province=user.province,
                                                                   trash=False,
                                                                   out=False,
                                                                   direct_buying=False,
                                                                   send_date__year=now.year,
                                                                   send_date__month=now.month,
                                                                   send_date__day=now.day)
        if allocated_poultry_requests.count() > 0:
            for allocated_poultry_request in allocated_poultry_requests:
                if allocated_poultry_request.poultry in poultry_list:
                    pass
                else:
                    poultry_list.append(allocated_poultry_request.poultry)
                province_kill_reqs = ProvinceKillRequest.objects.filter(
                    province_request__poultry_request=allocated_poultry_request,
                    trash=False, state__in=('pending', 'accepted'))
                if province_kill_reqs.count() > 0:
                    for province_kill_req in province_kill_reqs:
                        if province_kill_req.return_to_province == False:
                            allocated_quantity += province_kill_req.main_quantity
                        else:
                            returned_quantity += province_kill_req.main_quantity

        direct_buying_poultry_requests = PoultryRequest.objects.filter(

            poultry__address__province=user.province,
            trash=False,
            out=False,
            direct_buying=True,
            send_date__year=now.year,
            send_date__month=now.month,
            send_date__day=now.day)
        if direct_buying_poultry_requests.count() > 0:
            for direct in direct_buying_poultry_requests:
                direct_buying_quantity += direct.quantity

        total_poultry_request_quantity = TotalPoultryRequestQuantity.objects.filter(create_date__year=now.year,
                                                                                    create_date__month=now.month,
                                                                                    create_date__day=now.day)
        if total_poultry_request_quantity.count() > 0:
            total_poultry_request_quantity = total_poultry_request_quantity.last()
            total_poultry_request_quantity.quantity = total_quantity
            total_poultry_request_quantity.accepted_quantity = accepted_quantity
            total_poultry_request_quantity.allocated_quantity = allocated_quantity
            total_poultry_request_quantity.returned_quantity = returned_quantity
            total_poultry_request_quantity.city_accepted_quantity = city_accepted_quantity
            total_poultry_request_quantity.first_quantity = first_quantity
            total_poultry_request_quantity.rejected_quantity = rejected_quantity
            total_poultry_request_quantity.waiting_quantity = waiting_quantity
            total_poultry_request_quantity.direct_buying_quantity = direct_buying_quantity
            total_poultry_request_quantity.age_up_45 = quantity_of_45
            total_poultry_request_quantity.save()
        else:
            total_poultry_request_quantity = TotalPoultryRequestQuantity(
                quantity=total_quantity,
                accepted_quantity=accepted_quantity,
                allocated_quantity=allocated_quantity,
                returned_quantity=returned_quantity,
                city_accepted_quantity=city_accepted_quantity,
                first_quantity=first_quantity,
                rejected_quantity=rejected_quantity,
                waiting_quantity=waiting_quantity,
                direct_buying_quantity=direct_buying_quantity,
                age_up_45=quantity_of_45,
            )
            total_poultry_request_quantity.save()
        percentage = KillHousePercentage.objects.filter(percent__gt=0)
        kill_reqs = KillRequest.objects.filter(recive_date__year=now.year, recive_date__month=now.month,
                                               recive_date__day=now.day, trash=False)
        if kill_reqs.count() > 0:
            for kill_req in kill_reqs:
                kill_request_quantity += kill_req.kill_capacity

        total_poultry_request_quantity.kill_requests_quantity = kill_request_quantity
        total_poultry_request_quantity.number_of_kill_house = percentage.count()
        total_poultry_request_quantity.number_of_poultry = len(poultry_list)
        total_poultry_request_quantity.assignableQuantity = assignableQuantity
        total_poultry_request_quantity.save()
        serializer = self.serializer_class(total_poultry_request_quantity)
        return Response(serializer.data)


class PoultryRequestWeightViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        # user = SystemUserProfile.objects.get(user=request.user)
        # # refresh(request.user.id)
        # weight_list = []
        # average = 0
        # now = datetime.datetime.now().date()
        # poultry_requests = PoultryRequest.objects.filter(final_state='pending',
        #                                                  province_state__in=('accepted', 'pending'),
        #                                                  poultry__address__province=user.province)
        # # poultry_requests = PoultryRequest.objects.filter(final_state='pending',
        # #                                                  province_state__in=('accepted', 'pending'),
        # #                                                  send_date__year=now.year, send_date__month=now.month,
        # #                                                  send_date__day=now.day,
        # #                                                  poultry__address__province=user.province)
        # if poultry_requests.count() > 0:
        #
        #     for poultry_request in poultry_requests:
        #         total_quantity = poultry_request.quantity
        #
        #         province_kill_reqs = ProvinceKillRequest.objects.filter(
        #             province_request__poultry_request=poultry_request)
        #         if province_kill_reqs.count() > 0:
        #             for province_kill_req in province_kill_reqs:
        #                 total_quantity -= province_kill_req.main_quantity
        #         if total_quantity > 0:
        #             weight_list.append(poultry_request.Index_weight)
        #     for weight in weight_list:
        #         average += weight
        #     average = average / 1
        weight_list = [3.2, 3.2, 2.5, 2.9, 3.1]
        return Response({'list': weight_list, 'ave': 3613.2})
        # return Response({'list': weight_list, 'ave': round(average, 2)})


class BarsForKillHouseViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    serializer_class = PoultryRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
            'system_address__province').first()
        if kill_house.killer == True:
            percentage = KillHousePercentage.objects.get(kill_house=kill_house, trash=False)
            kill_house_vet = KillHouseVet.objects.filter(kill_house=percentage.kill_house_for_killer,
                                                         trash=False).select_related(
                'vet__user').last()
        else:
            kill_house_vet = KillHouseVet.objects.filter(kill_house=kill_house, trash=False).select_related(
                'vet__user').last()
        kill_house_req_dict = {}
        kill_house_req_list = []

        now = datetime.datetime.now().date()
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        # date = date - timedelta(days=1)
        # if 'freezing' in request.GET:
        #     freezing = True
        #     # freezing = False if user.province.name == 'مركزی' else True
        #
        #     queryset = PoultryRequest.objects.filter(
        #         poultry__address__province=kill_house.system_address.province,
        #         final_state__in=('pending', 'archive'),
        #         trash=False, out=False,
        #         send_date__date=date,
        #         freezing=freezing
        #
        #     ).select_related('poultry', 'poultry__user', 'poultry__address__city').order_by('-send_date')
        # else:
        queryset = PoultryRequest.objects.filter(
            poultry__address__province=kill_house.system_address.province,
            final_state__in=('pending', 'archive'),
            trash=False, out=False,
            send_date__date__gte=date1, send_date__date__lte=date2,

        ).select_related('poultry', 'poultry__user', 'poultry__address__city').order_by('-send_date')

        if len(queryset) > 0:
            for poultry_req in queryset:
                vet_farm = VetFarm.objects.filter(poultry=poultry_req.poultry).select_related('vet__user').last()
                if vet_farm:
                    vet_name = vet_farm.vet.user.fullname
                    vet_mobile = vet_farm.vet.user.mobile
                else:
                    vet_name = None
                    vet_mobile = None
                if request.GET['type'] == 'entered':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        province_kill_request__province_request__poultry_request=poultry_req,
                        ware_house_confirmation=True, trash=False).select_related(
                        'kill_request__kill_house__kill_house_operator__user', 'add_car__driver',
                        'kill_request__kill_house')
                else:

                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        province_kill_request__province_request__poultry_request=poultry_req,
                        ware_house_confirmation=False).select_related(
                        'kill_request__kill_house__kill_house_operator__user', 'add_car__driver',
                        'kill_request__kill_house')
                if kill_house_requests:
                    for kill_house_request in kill_house_requests:
                        weight_loss = kill_house_request.accepted_real_weight - kill_house_request.ware_house_accepted_real_weight if kill_house_request.ware_house_accepted_real_weight > 0 else 0
                        if weight_loss < 0:
                            weight_loss = weight_loss * -1
                        total_weight_loss = (
                                                    weight_loss / kill_house_request.accepted_real_weight) * 100 if weight_loss != 0 else 0
                        # kill_house_request.weight_loss = total_weight_loss
                        # kill_house_request.save()
                        vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_request)
                        if vet_check.count() > 0:
                            vet_check_state = vet_check.last().state
                        else:
                            vet_check_state = 'pending'
                        assignment = KillHouseAssignmentInformation.objects.filter(
                            kill_house_request=kill_house_request).last()
                        if assignment:
                            assignment_state = 'accepted'
                            assignment_real_quantity = kill_house_request.accepted_real_quantity
                            assignment_net_weight = kill_house_request.accepted_real_weight

                        else:
                            if kill_house_request.vet_state == 'pending':
                                assignment_state = 'pending'
                            else:
                                assignment_state = 'no_state'
                            assignment_real_quantity = kill_house_request.accepted_real_quantity
                            assignment_net_weight = kill_house_request.accepted_real_weight
                        exclusive_killer = None
                        if kill_house_request.killer != None:
                            exclusive_killer = {
                                "killer_name": kill_house_request.killer.name,
                                "killer_mobile": kill_house_request.killer.kill_house_operator.user.mobile,
                                "killer_fullname": kill_house_request.killer.kill_house_operator.user.fullname,
                            }

                        kill_house_req_dict.update({
                            "poultry_req_order_code": poultry_req.order_code,
                            "poultry_name": poultry_req.poultry.unit_name,
                            "poultry_user_name": poultry_req.poultry.user.fullname,
                            "poultry_mobile": poultry_req.poultry.user.mobile,
                            "poultry_city": poultry_req.poultry.address.city.name,
                            "chicken_breed": poultry_req.chicken_breed,
                            "date": poultry_req.send_date,
                            "freezing": poultry_req.freezing,
                            "clearance_code": kill_house_request.clearance_code,
                            "traffic_code": kill_house_request.traffic_code,
                            "kill_house_request_key": kill_house_request.key,
                            "ware_house_accepted_real_quantity": kill_house_request.ware_house_accepted_real_quantity,
                            "ware_house_accepted_real_weight": kill_house_request.ware_house_accepted_real_weight,
                            "bar_code": kill_house_request.bar_code,
                            "health_code": kill_house_request.add_car.driver.health_code,
                            "vet_name": vet_name,
                            "vet_mobile": vet_mobile,
                            "kill_house_vet_name": kill_house_vet.vet.user.fullname,
                            "kill_house_vet_mobile": kill_house_vet.vet.user.mobile,
                            "driver_name": kill_house_request.add_car.driver.driver_name,
                            "driver_mobile": kill_house_request.add_car.driver.driver_mobile,
                            "kill_house_name": kill_house_request.killhouse_user.name,
                            "type_car": kill_house_request.add_car.driver.type_car,
                            "killer": exclusive_killer,
                            "vet_check_state": vet_check_state,
                            "assignment_state": assignment_state,
                            "kill_house_request_quantity": kill_house_request.quantity,
                            "assignment_real_quantity": assignment_real_quantity,
                            "assignment_net_weight": assignment_net_weight,
                            "weight_loss": round(total_weight_loss, 1),
                            "input_loss": kill_house_request.weight_loss,

                        })
                        kill_house_req_list.append(kill_house_req_dict)
                        kill_house_req_dict = {}

        return Response(kill_house_req_list, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def city_operator_for_poultry(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    list1 = []

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i == 0:
            continue
        try:
            poultry = Poultry.objects.get(breeding_unique_id=row[3], trash=False)
            poultry.city_operator = row[5]
            poultry.save()
        except:
            dict1 = {
                "name": row[4],
                "breeding": row[3]
            }
            list1.append(dict1)
            continue
    return Response(list1)


@api_view(["POST"])
@permission_classes([TokenHasReadWriteScope])
@csrf_exempt
def archive_hatching(request):
    user = SystemUserProfile.objects.get(user=request.user)
    if request.data['role'] == 'ProvinceOperator':
        return Response({'result': 'شما دسترسی لازم را ندارید!'},
                        status=status.HTTP_403_FORBIDDEN)
    now = datetime.datetime.now().date()
    date = (datetime.datetime(year=now.year, month=now.month, day=now.day, hour=23, minute=59,
                              second=59) - timedelta(
        days=int(request.data['age'])))
    poultry_hatching = PoultryHatching.objects.filter(date__lte=date, trash=False, allow_hatching='pending',
                                                      archive=False)
    for hatching in poultry_hatching:
        if hatching.left_over > (hatching.quantity * percent_of_losses):
            hatching.violation = True
        hatching.allow_hatching = 'True'
        hatching.state = 'complete'
        hatching.archive = True
        hatching.archive_date = datetime.datetime.now()
        if hatching.first_date_input_archive is None:
            hatching.first_date_input_archive = datetime.datetime.now()
        else:
            hatching.second_date_input_archive = datetime.datetime.now()
        hatching.input_archiver = user.fullname
        hatching.last_change = {
            "date": str(datetime.datetime.now()),
            "full_name": user.fullname,
            "role": request.data['role'],
            "type": "automatic-archive"
        }
        hatching.save()
    return Response({"msg": f"تعداد {poultry_hatching.count()} جوجه ریزی بایگانی شد."}, status=status.HTTP_200_OK)


class LastUpdateViewSet(viewsets.ModelViewSet):
    queryset = LastUpdate.objects.first()
    serializer_class = LastUpdateSerializer
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        if 'type' in request.GET:
            if request.GET['type'] == 'poultry_hatching':
                update = LastUpdate.objects.first().update_date
                # ser_deta=self.serializer_class(update).data
                return Response(update)

        return Response({"result": "you havnt type in url params"}, status=status.HTTP_403_FORBIDDEN)


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

    def update(self, request, *args, **kwargs):
        poultry_tenant = self.queryset.get(trash=False, key=request.data['tenant_key'])
        system_user_profile = SystemUserProfile.objects.get(trash=False, key=poultry_tenant.user.key)
        first_mobile_number = system_user_profile.mobile
        second_mobile_number = request.data['mobile']
        poultry_tenant.breeding_unique_id = request.data['breeding_unique_id']
        system_user_profile.last_name = request.data['last_name']
        system_user_profile.first_name = request.data['first_name']
        system_user_profile.fullname = request.data['first_name'] + ' ' + request.data['last_name']
        system_user_profile.national_id = request.data['national_id']
        if first_mobile_number != second_mobile_number:
            if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
                return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                status=status.HTTP_403_FORBIDDEN)
            data = {
                "first_mobile_number": first_mobile_number,
                "second_mobile_number": second_mobile_number,
            }
            req = requests.post(
                url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                data=data,
                verify=False
            )
            if req.status_code == 200:
                second_mobile_number = second_mobile_number
                user = User.objects.get(id=system_user_profile.user.id)
                user.username = second_mobile_number
                user.save()
                system_user_profile.mobile = second_mobile_number
        poultry_tenant.save()
        system_user_profile.save()
        return Response('poultry tenant successfully update!', status=status.HTTP_201_CREATED)


class GeneralStatisticsdashboardForCasesViewSet(viewsets.ViewSet):
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request):
        date1 = datetime.datetime.strptime(request.GET['date1'],
                                           '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(request.GET['date2'],
                                           '%Y-%m-%d').date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        poultry_requests = PoultryRequest.objects.filter(trash=False,
                                                         send_date__date__gte=date1,
                                                         send_date__date__lte=date2).order_by('send_date')

        if request.GET['role'] in ['CityCommerce', 'CityVet', 'CityPoultry', 'CityJahad']:
            poultry_requests = poultry_requests.filter(poultry__address__city=user.city)

        elif request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            poultry_requests = poultry_requests.filter(poultry__city_operator=city_operator.unit_name)
        else:
            poultry_requests = poultry_requests
        poultry = poultry_requests.values('poultry').distinct().count()
        poultry_requests_quantity = poultry_requests.aggregate(total=Sum('quantity'))['total'] or 0
        poultry_requests_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))['total'] or 0
        out_poultry_request = poultry_requests.filter(out=True)
        out_poultry_request_quantity = poultry_requests.aggregate(total=Sum('quantity'))['total'] or 0
        out_poultry_request_weight = poultry_requests.aggregate(total=Sum(F('quantity') * F('Index_weight')))[
                                         'total'] or 0
        province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
                                                                    return_to_province=False,
                                                                    province_request__poultry_request__in=poultry_requests)
        province_kill_requests_quantity = province_kill_requests.aggregate(total=Sum('main_quantity'))['total'] or 0
        province_kill_requests_weight = province_kill_requests.aggregate(
            total=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight')))['total'] or 0
        province_kill_requests_buyers = province_kill_requests.values('killhouse_user').distinct().count()
        kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                              province_kill_request__in=province_kill_requests)
        kill_house_request_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
        kill_house_request_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
        kill_house_requests_with_quarantine_code = kill_house_requests.filter(clearance_code__isnull=False)
        kill_house_requests_with_quarantine_code_quantity = \
            kill_house_requests_with_quarantine_code.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
        kill_house_requests_with_quarantine_code_weight = \
            kill_house_requests_with_quarantine_code.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
        kill_house_requests_without_quarantine_code = kill_house_requests.filter(clearance_code__isnull=True)
        kill_house_requests_without_quarantine_code_quantity = \
            kill_house_requests_without_quarantine_code.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
        kill_house_requests_without_quarantine_code_weight = \
            kill_house_requests_without_quarantine_code.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
        kill_house_requests_with_kill_house_vet_accepted = kill_house_requests.filter(vet_state='accepted')
        kill_house_requests_with_kill_house_vet_accepted_quantity = \
            kill_house_requests_with_kill_house_vet_accepted.aggregate(total=Sum('accepted_real_quantity'))[
                'total'] or 0
        kill_house_requests_with_kill_house_vet_accepted_weight = \
            kill_house_requests_with_kill_house_vet_accepted.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
        kill_house_requests_without_kill_house_vet_accepted = kill_house_requests.filter(vet_state='pending')
        kill_house_requests_without_kill_house_vet_accepted_quantity = \
            kill_house_requests_without_kill_house_vet_accepted.aggregate(total=Sum('accepted_real_quantity'))[
                'total'] or 0
        kill_house_requests_without_kill_house_vet_accepted_weight = \
            kill_house_requests_without_kill_house_vet_accepted.aggregate(total=Sum('accepted_real_weight'))[
                'total'] or 0
        kill_house_requests_with_kill_house_assignment = kill_house_requests.filter(
            assignment_state_archive='True')
        kill_house_requests_with_kill_house_assignment_quantity = \
            kill_house_requests_with_kill_house_assignment.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
        kill_house_requests_with_kill_house_assignment_weight = \
            kill_house_requests_with_kill_house_assignment.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
        kill_house_requests_without_kill_house_assignment = kill_house_requests.filter(
            assignment_state_archive='True')
        kill_house_requests_without_kill_house_assignment_quantity = \
            kill_house_requests_without_kill_house_assignment.aggregate(total=Sum('accepted_real_quantity'))[
                'total'] or 0
        kill_house_requests_without_kill_house_assignment_weight = \
            kill_house_requests_without_kill_house_assignment.aggregate(total=Sum('accepted_real_weight'))['total'] or 0

        return Response(
            {
                "poultry_requests": len(poultry_requests),
                "poultry": poultry,
                "poultry_requests_quantity": poultry_requests_quantity,
                "poultry_requests_weight": poultry_requests_weight,
                "out_poultry_request": len(out_poultry_request),
                "out_poultry_request_quantity": out_poultry_request_quantity,
                "out_poultry_request_weight": out_poultry_request_weight,
                "province_kill_requests": len(province_kill_requests),
                "province_kill_requests_quantity": province_kill_requests_quantity,
                "province_kill_requests_weight": province_kill_requests_weight,
                "province_kill_requests_buyers": province_kill_requests_buyers,
                "kill_house_requests": len(kill_house_requests),
                "kill_house_request_quantity": kill_house_request_quantity,
                "kill_house_request_weight": kill_house_request_weight,
                "kill_house_requests_with_quarantine_code": len(kill_house_requests_with_quarantine_code),
                "kill_house_requests_with_quarantine_code_quantity": kill_house_requests_with_quarantine_code_quantity,
                "kill_house_requests_with_quarantine_code_weight": kill_house_requests_with_quarantine_code_weight,
                "kill_house_requests_without_quarantine_code": len(kill_house_requests_without_quarantine_code),
                "kill_house_requests_without_quarantine_code_quantity": kill_house_requests_without_quarantine_code_quantity,
                "kill_house_requests_without_quarantine_code_weight": kill_house_requests_without_quarantine_code_weight,
                "kill_house_requests_with_kill_house_vet_accepted": len(
                    kill_house_requests_with_kill_house_vet_accepted),
                "kill_house_requests_with_kill_house_vet_accepted_quantity": kill_house_requests_with_kill_house_vet_accepted_quantity,
                "kill_house_requests_with_kill_house_vet_accepted_weight": kill_house_requests_with_kill_house_vet_accepted_weight,
                "kill_house_requests_without_kill_house_vet_accepted": len(
                    kill_house_requests_without_kill_house_vet_accepted),
                "kill_house_requests_without_kill_house_vet_accepted_quantity": kill_house_requests_without_kill_house_vet_accepted_quantity,
                "kill_house_requests_without_kill_house_vet_accepted_weight": kill_house_requests_without_kill_house_vet_accepted_weight,
                "kill_house_requests_with_kill_house_assignment": len(kill_house_requests_with_kill_house_assignment),
                "kill_house_requests_with_kill_house_assignment_quantity": kill_house_requests_with_kill_house_assignment_quantity,
                "kill_house_requests_with_kill_house_assignment_weight": kill_house_requests_with_kill_house_assignment_weight,
                "kill_house_requests_without_kill_house_assignment": len(
                    kill_house_requests_without_kill_house_assignment),
                "kill_house_requests_without_kill_house_assignment_quantity": kill_house_requests_without_kill_house_assignment_quantity,
                "kill_house_requests_without_kill_house_assignment_weight": kill_house_requests_without_kill_house_assignment_weight,
            })


def archive_poultry_hatching_with_cron_job():
    hatching = PoultryHatching.objects.filter(Q(left_over=0) | Q(chicken_age__gt=80), trash=False,
                                              allow_hatching='pending',
                                              state='pending', archive=False).only('allow_hatching',
                                                                                   'left_over', 'quantity', 'state',
                                                                                   'archive')
    now_date = datetime.datetime.now()
    for hatch in hatching:
        if hatch.left_over > (hatch.quantity * percent_of_losses):
            hatch.violation = True
        hatch.allow_hatching = 'True'
        hatch.state = 'complete'
        hatch.archive = True
        hatch.archive_date = datetime.datetime.now()
        if hatch.first_date_input_archive is None:
            hatch.first_date_input_archive = now_date
        else:
            hatch.second_date_input_archive = now_date
        hatch.input_archiver = 'automatic-archive'
        hatch.last_change = {
            "date": str(now_date),
            "full_name": 'automatic-archive',
            "role": 'automatic-archive1',
            "type": "automatic-archive"
        }
        hatch.save()


def archive_poultry_hatching_with_archive_percent_cron_job():
    now_date = datetime.datetime.now()
    archive_percent = HatchingArchivePercent.objects.filter(trash=False, active=True).first()
    if archive_percent:
        hatchings = PoultryHatching.objects.filter(
            state='pending',
            archive=False,
            allow_hatching='pending',
            trash=False,
        ).annotate(
            allowed_left_over=ExpressionWrapper(
                F('quantity') * (archive_percent.percent / 100),
                output_field=FloatField()
            )
        ).filter(
            left_over__lte=F('allowed_left_over')
        )

        Poultry.objects.filter(
            id__in=hatchings.values_list('poultry__id', flat=True), order_limit=True
        ).update(order_limit=False)
        for hatching in hatchings:
            if hatching.left_over > (hatching.quantity * percent_of_losses):
                hatching.violation = True
            hatching.allow_hatching = 'True'
            hatching.state = 'complete'
            hatching.archive = True
            hatching.unknown = False
            hatching.archive_date = datetime.datetime.now()
            if hatching.first_date_input_archive is None:
                hatching.first_date_input_archive = now_date
            else:
                hatching.second_date_input_archive = now_date
            hatching.input_archiver = 'automatic-archive'
            hatching.last_change = {
                "date": str(now_date),
                "full_name": 'automatic-archive',
                "role": 'automatic-archive1',
                "type": "automatic-archive"
            }
            hatching.save()


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def archive_poultry_hatching_with_archive_percent(request):
    now_date = datetime.datetime.now()
    archive_percent = HatchingArchivePercent.objects.filter(trash=False, active=True).first()
    if archive_percent:
        hatchings = PoultryHatching.objects.filter(
            state='pending',
            archive=False,
            allow_hatching='pending',
            trash=False,
        ).annotate(
            allowed_left_over=ExpressionWrapper(
                F('quantity') * (archive_percent.percent / 100),
                output_field=FloatField()
            )
        ).filter(
            left_over__lte=F('allowed_left_over')
        )

        Poultry.objects.filter(
            id__in=hatchings.values_list('poultry__id', flat=True), order_limit=True
        ).update(order_limit=False)
        for hatching in hatchings:
            hatching.allow_hatching = 'True'
            hatching.state = 'complete'
            hatching.archive = True
            hatching.unknown = False
            hatching.archive_date = datetime.datetime.now()
            if hatching.first_date_input_archive is None:
                hatching.first_date_input_archive = now_date
            else:
                hatching.second_date_input_archive = now_date
            hatching.input_archiver = 'automatic-archive'
            hatching.last_change = {
                "date": str(now_date),
                "full_name": 'automatic-archive',
                "role": 'automatic-archive1',
                "type": "automatic-archive"
            }
            hatching.save()


class PoultryLocationViewSet(viewsets.ModelViewSet):
    queryset = Poultry.objects.filter(
        trash=False,
        Long__isnull=False
    ).select_related(
        'user', 'address', 'address__city'
    ).only(
        'id', 'unit_name', 'Lat', 'Long',
        'user__fullname', 'user__mobile',
        'address__address', 'address__city__name', 'breeding_unique_id'
    ).prefetch_related(
        Prefetch('poultry_hatching_user',
                 queryset=PoultryHatching.objects.filter(
                     state__in=('pending', 'complete'),
                     archive=False,
                     allow_hatching='pending',
                     trash=False
                 ).only(
                     'left_over', 'chicken_age', 'date',
                     'licence_number',
                     'poultry_id', 'killed_quantity', 'total_losses'
                 )
                 )
    )
    serializer_class = PoultryLocationSerializer
    permission_classes = [AllowAny]
    filter_backends = [DjangoFilterBackend]
    filterset_class = PoultryManageFilterSet

    @staticmethod
    def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
        radius = 6378137.0

        dlat = math.radians(lat2 - lat1)
        dlon = math.radians(lon2 - lon1)
        lat1_rad = math.radians(lat1)
        lat2_rad = math.radians(lat2)

        a = math.sin(dlat / 2) ** 2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2) ** 2
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
        return radius * c

    def filter_nearby_poultries(self, poultries: List[Dict], center_lat: float, center_lon: float, radius: float) -> \
            List[Dict]:
        nearby_poultries = [
            poultry for poultry in poultries
            if self.haversine_distance(center_lat, center_lon, poultry['Lat'], poultry['Long']) <= radius
        ]
        return nearby_poultries

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        value = request.GET.get('value')
        if value:
            if value != 'undefined' and value.strip():
                queryset = queryset.filter(
                    build_query(self.filterset_class, value)
                )
        serializer = self.get_serializer(queryset, many=True)
        data = serializer.data

        center_lat = request.query_params.get('center_lat')
        center_lon = request.query_params.get('center_lon')
        radius = request.query_params.get('radius')

        if center_lat and center_lon and radius:
            try:
                center_lat = float(center_lat)
                center_lon = float(center_lon)
                radius = float(radius)

                if radius > 100:
                    radius_meters = radius
                else:
                    radius_meters = radius * 1000

                data = self.filter_nearby_poultries(data, center_lat, center_lon, radius_meters)
            except (ValueError, TypeError):
                pass

        return Response(data)


class DashboardOutProvincePoultryRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestoutProvinceSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardPoultryRequestFilterSet

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        state = request.GET.get('state')
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        if request.GET['role'] == 'VetFarm':
            vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
            poultries = Poultry.objects.filter(
                pk__in=vet_farms.values('poultry')
            )
            if state == 'pending':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    poultry__in=poultries, send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    poultry__in=poultries, send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True),
                    poultry__in=poultries, send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    trash=False).order_by('-send_date')

        elif request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            if state == 'pending':

                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    poultry__city_operator=city_operator.unit_name,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    poultry__city_operator=city_operator.unit_name,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:

                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True),
                    poultry__city_operator=city_operator.unit_name,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    trash=False).order_by('-send_date')

        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            if state == 'pending':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    poultry__address__city=user.city,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    poultry__address__city=user.city,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:

                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True),
                    poultry__address__city=user.city,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                    out=True,
                    trash=False).order_by('-send_date')

        else:
            if request.GET['state'] == 'pending':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                          wage_pay=False),
                    send_date__date__gte=date1,
                    send_date__date__lte=date2, out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')

            elif state == 'accepted':
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                      wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                         has_wage=False, wage_pay=False),
                    send_date__date__gte=date1,
                    send_date__date__lte=date2, out=True,
                    out_province_request_cancel=False,
                    trash=False).order_by('-send_date')
            else:
                poultry_requests = PoultryRequest.objects.filter(
                    Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                      wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                             province_state='rejected',
                                                                             final_state='archive',
                                                                             has_wage=False, wage_pay=False,
                                                                             out_province_request_cancel=False) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                        state_process='pending', province_state='pending', final_state='pending',
                        has_wage=True, wage_pay=False, out_province_request_cancel=True) | Q(
                        state_process='accepted', province_state='accepted', final_state='archive',
                        has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                        state_process='accepted', province_state='accepted', final_state='archive',
                        has_wage=True, wage_pay=False, out_province_request_cancel=True),
                    send_date__date__gte=date1,
                    send_date__date__lte=date2, out=True,
                    trash=False).order_by('-send_date')
        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                poultry_requests = poultry_requests.filter(
                    build_query(self.filterset_class, value)
                )

        index_weight = poultry_requests.aggregate(total=Sum('Index_weight'))[
                           'total'] or 0
        quantity = poultry_requests.aggregate(total=Sum('quantity'))[
                       'total'] or 0
        has_code = len(poultry_requests.filter(quarantine_code__isnull=False))
        hasnt_code = len(poultry_requests.filter(quarantine_code__isnull=True))
        hatching = poultry_requests.values_list('hatching__id', flat=True).distinct()
        hatchings = PoultryHatching.objects.filter(trash=False, id__in=hatching)
        left_over = hatchings.aggregate(total=Sum('left_over'))[
                        'total'] or 0
        quantity_hatching = hatchings.aggregate(total=Sum('quantity'))[
                                'total'] or 0
        poultry_request_aggregates = poultry_requests.aggregate(
            total_weight=Sum(F('quantity') * F('Index_weight')),
        )
        dict1 = {
            'lenBar': len(poultry_requests),
            'indexWeight': round(index_weight / len(poultry_requests) if len(poultry_requests) > 0 else 0),
            'quantity': quantity,
            # 'weight': int(quantity * index_weight),
            'weight': poultry_request_aggregates['total_weight'] or 0,
            'hasCode': has_code,
            'hasntCode': hasnt_code,
            'leftOver': left_over,
            'hatchingQuantity': quantity_hatching,

        }
        return Response(dict1, status=status.HTTP_200_OK)


class ParentCompanyDashboardOutProvincePoultryRequestViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.filter(out=True, trash=False)
    serializer_class = PoultryRequestoutProvinceSerializer
    permission_classes = [AllowAny]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardPoultryRequestFilterSet

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        state = request.GET.get('state')
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if request.GET['state'] == 'pending':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                      wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')

        elif state == 'accepted':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
        else:
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                  wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                         province_state='rejected',
                                                                         final_state='archive',
                                                                         has_wage=False, wage_pay=False,
                                                                         out_province_request_cancel=False) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=True, wage_pay=False, out_province_request_cancel=True) | Q(
                    state_process='accepted', province_state='accepted', final_state='archive',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True) | Q(
                    state_process='accepted', province_state='accepted', final_state='archive',
                    has_wage=True, wage_pay=False, out_province_request_cancel=True),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                trash=False).order_by('-send_date')
        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                poultry_requests = poultry_requests.filter(
                    build_query(self.filterset_class, value)
                )

        index_weight = poultry_requests.aggregate(total=Sum('Index_weight'))[
                           'total'] or 0
        quantity = poultry_requests.aggregate(total=Sum('quantity'))[
                       'total'] or 0
        has_code = len(poultry_requests.filter(quarantine_code__isnull=False))
        hasnt_code = len(poultry_requests.filter(quarantine_code__isnull=True))
        hatching = poultry_requests.values_list('hatching__id', flat=True).distinct()
        hatchings = PoultryHatching.objects.filter(trash=False, id__in=hatching)
        left_over = hatchings.aggregate(total=Sum('left_over'))[
                        'total'] or 0
        quantity_hatching = hatchings.aggregate(total=Sum('quantity'))[
                                'total'] or 0
        dict1 = {
            'lenBar': len(poultry_requests),
            'indexWeight': round(index_weight / len(poultry_requests) if len(poultry_requests) > 0 else 0),
            'quantity': quantity,
            'weight': int(quantity * index_weight),
            'hasCode': has_code,
            'hasntCode': hasnt_code,
            'leftOver': left_over,
            'hatchingQuantity': quantity_hatching,

        }
        return Response(dict1, status=status.HTTP_200_OK)


class DashboardChainAllocationViewSet(viewsets.ModelViewSet):
    queryset = ChainAllocation.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ChainAllocationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainAllocationFilterSet
    filterset_fields = [
        'poultry_hatching__poultry__breeding_unique_id',
        'poultry_hatching__poultry__user__mobile',
        'poultry_hatching__poultry__user__fullname',
        'poultry_hatching__poultry__user__first_name',
        'poultry_hatching__poultry__user__last_name',
        'poultry_hatching__poultry__unit_name',
        'chain_company__name',

    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if request.GET['role'] == "ChainCompany":
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(chain_company__user=user, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True)).order_by('-id')
            else:
                chain_allocations = ChainAllocation.objects.filter(chain_company__user=user, date__date__gte=date1,
                                                                   date__date__lte=date2,
                                                                   state__in=('accepted', 'pending'),
                                                                   trash=False).order_by('-id')
        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(poultry_hatching__poultry__address__city=user.city,
                                                                   date__date__gte=date1, date__date__lte=date2,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True)).order_by('-id')
            else:

                chain_allocations = ChainAllocation.objects.filter(poultry_hatching__poultry__address__city=user.city,
                                                                   date__date__gte=date1, date__date__lte=date2,
                                                                   state='accepted',
                                                                   trash=False).order_by('-id')
        elif request.GET['role'] == "CityOperator":
            city_operator = CityOperator.objects.get(user=user, trash=False)
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(
                    poultry_hatching__poultry__city_operator=city_operator.unit_name, date__date__gte=date1,
                    date__date__lte=date2,
                    state__in=('rejected', 'deleted'),
                    trash__in=(False, True)).order_by('-id')
            else:
                chain_allocations = ChainAllocation.objects.filter(
                    poultry_hatching__poultry__city_operator=city_operator.unit_name, date__date__gte=date1,
                    date__date__lte=date2,
                    state__in=('accepted', 'pending'),
                    trash=False).order_by('-id')

        elif request.GET['role'] == "VetFarm":
            vet = Vet.objects.get(user=user, trash=False)
            poultry_ids = VetFarm.objects.filter(vet=vet, trash=False).select_related('poultry').only(
                'poultry').values_list('poultry', flat=True).distinct()
            poultry = Poultry.objects.filter(id__in=poultry_ids)
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   poultry_hatching__poultry__in=poultry,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True)).order_by('-id')
            else:

                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   poultry_hatching__poultry__in=poultry,
                                                                   state='accepted',
                                                                   trash=False).order_by('-id')
        else:
            if 'state' in request.GET:
                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   state__in=('rejected', 'deleted'),
                                                                   trash__in=(False, True)).order_by('-id')
            else:
                chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                   state__in=('accepted', 'pending'),
                                                                   trash=False).order_by('-id')

        index_weight = chain_allocations.aggregate(total=Sum('index_weight'))[
                           'total'] or 0
        weight = chain_allocations.aggregate(total=Sum('weight'))[
                     'total'] or 0
        quantity = chain_allocations.aggregate(total=Sum('quantity'))[
                       'total'] or 0
        has_code = len(chain_allocations.filter(quarantine_code__isnull=False))
        hasnt_code = len(chain_allocations.filter(quarantine_code__isnull=True))

        dict1 = {
            'lenBar': len(chain_allocations),
            'indexWeight': round(index_weight / len(chain_allocations) if len(chain_allocations) > 0 else 0),
            'quantity': quantity,
            'weight': int(weight),
            'hasCode': has_code,
            'hasntCode': hasnt_code,

        }
        return Response(dict1, status=status.HTTP_200_OK)


class ParentCompanyDashboardChainAllocationViewSet(viewsets.ModelViewSet):
    queryset = ChainAllocation.objects.all()
    permission_classes = [AllowAny]
    serializer_class = ChainAllocationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ChainAllocationFilterSet
    filterset_fields = [
        'poultry_hatching__poultry__breeding_unique_id',
        'poultry_hatching__poultry__user__mobile',
        'poultry_hatching__poultry__user__fullname',
        'poultry_hatching__poultry__user__first_name',
        'poultry_hatching__poultry__user__last_name',
        'poultry_hatching__poultry__unit_name',
        'chain_company__name',

    ]

    def list(self, request, *args, **kwargs):
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if 'state' in request.GET:
            chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                               state__in=('rejected', 'deleted'),
                                                               trash__in=(False, True)).order_by('-id')
        else:
            chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                               state__in=('accepted', 'pending'),
                                                               trash=False).order_by('-id')

        index_weight = chain_allocations.aggregate(total=Sum('index_weight'))[
                           'total'] or 0
        weight = chain_allocations.aggregate(total=Sum('weight'))[
                     'total'] or 0
        quantity = chain_allocations.aggregate(total=Sum('quantity'))[
                       'total'] or 0
        has_code = len(chain_allocations.filter(quarantine_code__isnull=False))
        hasnt_code = len(chain_allocations.filter(quarantine_code__isnull=True))

        dict1 = {
            'lenBar': len(chain_allocations),
            'indexWeight': round(index_weight / len(chain_allocations) if len(chain_allocations) > 0 else 0),
            'quantity': quantity,
            'weight': int(weight),
            'hasCode': has_code,
            'hasntCode': hasnt_code,

        }
        return Response(dict1, status=status.HTTP_200_OK)


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

    def list(self, request, *args, **kwargs):
        poultreis = Poultry.objects.filter(trash=False).select_related('user', 'address__province', 'address__city')
        if 'role' in request.GET:
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user=user)
                poultrys = poultreis.filter(poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                poultrys = poultreis.filter(poultry__user__city=user.city)
            else:
                poultrys = poultreis
        else:
            poultrys = poultreis
        all_hatching_pending = 0
        all_total_quantity = 0
        all_poultry_request = 0
        all_kill_request = 0
        all_kill_request_quantity = 0
        all_kill_request_weight = 0
        all_kill_request_has_assigment = 0
        all_kill_request_quantity_assigment = 0
        all_kill_request_weight_assigment = 0
        all_total_quantity_poultry_hatching_pending = 0
        all_total_left_over_poultry_hatching_pending = 0
        all_total_quantity_poultry_request = 0
        all_len_out_poultry_request = 0
        all_total_out_quantity_poultry_request = 0
        all_total_out_weight_poultry_request = 0
        all_period = 0
        len_werhouse_enter = 0
        all_werhouse_enter_quantity = 0
        all_werhouse_enter_weight = 0
        all_all_weight_loss = 0
        for poultry in poultrys:
            user_mobile = poultry.user.mobile if poultry.user else '-'
            user_name = poultry.user.fullname if poultry.user else '-'
            city_operator = poultry.city_operator if poultry.city_operator else '-'
            health_certificate_number = poultry.health_certificate_number if poultry.health_certificate_number else '-'
            epidemiological_code = poultry.epidemiological_code if poultry.epidemiological_code else '-'
            vet_farm = VetFarm.objects.filter(poultry=poultry, trash=False).select_related('vet__user').last()
            vet_name = '-'
            mobile_vet = '-'
            if vet_farm:
                vet_name = vet_farm.vet.user.fullname
                mobile_vet = vet_farm.vet.user.mobile
            poultry_hatching = PoultryHatching.objects.filter(poultry=poultry, trash=False).only('quantity', 'left_over'
                                                                                                 )

            if poultry_hatching:

                poultry_hatching_pending = poultry_hatching.filter(state='pending', allow_hatching='pending',
                                                                   archive=False).last()
                if poultry_hatching_pending:
                    all_hatching_pending += 1
                hatching = 'ندارد' if not poultry_hatching_pending else f'دارد'

                if poultry_hatching_pending:
                    period = poultry_hatching_pending.period
                else:
                    period = poultry_hatching.last().period
                all_period += period
                poultry_hatching_pending1 = poultry_hatching.filter(state='pending', allow_hatching='pending',
                                                                    archive=False)
                total_quantity = \
                    poultry_hatching.aggregate(total=Sum('quantity'))[
                        'total'] or 0
                total_quantity_poultry_hatching_pending = \
                    poultry_hatching_pending1.aggregate(total=Sum('quantity'))[
                        'total'] or 0
                total_left_over_poultry_hatching_pending = \
                    poultry_hatching_pending1.aggregate(total=Sum('left_over'))[
                        'total'] or 0
                all_total_quantity += total_quantity
                all_total_quantity_poultry_hatching_pending += total_quantity_poultry_hatching_pending
                all_total_left_over_poultry_hatching_pending += total_left_over_poultry_hatching_pending
                poultry_request = PoultryRequest.objects.filter(trash=False, poultry=poultry,
                                                                state_process__in=('accepted', 'pending'),
                                                                province_state__in=('accepted', 'pending')).only(
                    'quantity', 'Index_weight')
                kill_request = KillHouseRequest.objects.filter(trash=False,
                                                               province_request__poultry_request__in=poultry_request).only(
                    'accepted_real_quantity', 'accepted_real_weight')

                out_poultry_request = poultry_request.filter(out=True, out_province_request_cancel=False).only(
                    'quantity', 'Index_weight'
                )
                total_out_quantity_poultry_request = \
                    out_poultry_request.aggregate(total=Sum('quantity'))[
                        'total'] or 0
                total_out_weight_poultry_request = \
                    out_poultry_request.aggregate(total=Sum(F('quantity') * F('Index_weight')))[
                        'total'] or 0

                all_total_out_quantity_poultry_request += total_out_quantity_poultry_request
                all_total_out_weight_poultry_request += total_out_weight_poultry_request
                all_len_out_poultry_request += len(out_poultry_request)
                total_quantity_poultry_request = \
                    poultry_request.aggregate(total=Sum('quantity'))[
                        'total'] or 0
                all_total_quantity_poultry_request += total_quantity_poultry_request
                all_poultry_request += len(poultry_request)
                all_kill_request += len(kill_request)
                kill_request_quantity = kill_request.aggregate(
                    total=Sum('accepted_real_quantity'))[
                                            'total'] or 0
                all_kill_request_quantity += kill_request_quantity
                kill_request_weight = kill_request.aggregate(
                    total=Sum('accepted_real_weight'))[
                                          'total'] or 0
                all_kill_request_weight += int(kill_request_weight)
                kill_request_has_assigment = kill_request.filter(assignment_state_archive='True').only(
                    'accepted_real_quantity', 'accepted_real_weight')

                all_kill_request_has_assigment += len(kill_request_has_assigment)

                kill_request_quantity_assigment = kill_request_has_assigment.aggregate(
                    total=Sum('accepted_real_quantity'))[
                                                      'total'] or 0
                all_kill_request_quantity_assigment += kill_request_quantity_assigment
                kill_request_weight_assigment = kill_request_has_assigment.aggregate(
                    total=Sum('accepted_real_weight'))[
                                                    'total'] or 0
                all_kill_request_weight_assigment += int(kill_request_weight_assigment)

                werhouse_enter = kill_request.filter(ware_house_confirmation=True).only(
                    'ware_house_accepted_real_quantity',
                    'ware_house_accepted_real_weight',
                    'weight_loss')
                werhouse_enter_quantity = werhouse_enter.aggregate(
                    total=Sum('ware_house_accepted_real_quantity'))[
                                              'total'] or 0
                werhouse_enter_weight = werhouse_enter.aggregate(
                    total=Sum('ware_house_accepted_real_weight'))[
                                            'total'] or 0
                all_weight_loss = werhouse_enter.aggregate(
                    total_quantity=Sum('weight_loss')).get(
                    'total_quantity', 0) or 0
                all_all_weight_loss += all_weight_loss

                all_weight_loss = round(int(all_weight_loss) / len(werhouse_enter), 2) if len(werhouse_enter) > 0 else 0

                len_werhouse_enter += len(werhouse_enter)
                all_werhouse_enter_quantity += werhouse_enter_quantity
                all_werhouse_enter_weight += int(werhouse_enter_weight)
                list1 = [
                    poultry.unit_name,
                    user_name,
                    user_mobile,
                    poultry.breeding_unique_id,
                    epidemiological_code,
                    health_certificate_number,
                    poultry.number_of_halls,
                    poultry.total_capacity,
                    poultry.user.province.name + '/' + poultry.user.city.name if poultry.user.city and poultry.user.province is not None else '-',
                    city_operator,
                    vet_name + '/' + mobile_vet,
                    hatching,
                    period,
                    total_quantity,
                    round(total_quantity / period) if period > 0 else 0,
                    len(poultry_request),
                    total_quantity_poultry_request,
                    len(kill_request),
                    kill_request_quantity,
                    int(kill_request_weight),
                    round(kill_request_weight / kill_request_quantity, 1) if kill_request_weight > 0 else 0,
                    len(kill_request_has_assigment),
                    kill_request_quantity_assigment,
                    int(kill_request_weight_assigment),
                    round(kill_request_weight_assigment / kill_request_quantity_assigment,
                          1) if kill_request_weight_assigment > 0 else 0,
                    len(out_poultry_request),
                    total_out_quantity_poultry_request,
                    int(total_out_weight_poultry_request),
                    str(round(total_out_weight_poultry_request / total_out_quantity_poultry_request,
                              1)) if total_out_quantity_poultry_request > 0 else 0,

                    len(werhouse_enter),
                    werhouse_enter_quantity,
                    int(werhouse_enter_weight),
                    f'%{all_weight_loss}',

                ]

        value_header_list = [
            all_period,
            all_total_quantity,
            all_hatching_pending,
            all_total_quantity_poultry_hatching_pending,
            all_total_left_over_poultry_hatching_pending,
            all_poultry_request,
            all_total_quantity_poultry_request,
            all_kill_request,
            all_kill_request_quantity,
            all_kill_request_weight,
            (round(all_kill_request_weight / all_kill_request_quantity, 1)) if all_kill_request_quantity > 0 else 0,

            all_kill_request_has_assigment,
            all_kill_request_quantity_assigment,
            all_kill_request_weight_assigment,
            str(round(all_kill_request_weight_assigment / all_kill_request_quantity_assigment,
                      1)) if all_kill_request_quantity_assigment > 0 else 0,

            all_len_out_poultry_request,
            all_total_out_quantity_poultry_request,
            int(all_total_out_weight_poultry_request),
            str(round(all_total_out_weight_poultry_request / all_total_out_quantity_poultry_request,
                      1)) if all_total_out_quantity_poultry_request > 0 else 0,
            len_werhouse_enter,
            all_werhouse_enter_quantity,
            all_werhouse_enter_weight,
            f'%{round(int(all_all_weight_loss) / len_werhouse_enter, 2) if len_werhouse_enter > 0 else 0}',

        ]


class GetAllPoultryViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET.get('role')
        min_age = int(request.GET.get('min_age', 0))
        max_age = int(request.GET.get('max_age', min_age))

        filters = {
            'allow_hatching': 'pending',
            'left_over__gt': 0,
            'state': 'pending',
            'archive': False,
            'trash': False
        }

        if role == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            filters['poultry__city_operator'] = city_operator.unit_name
        elif role == 'Poultry':
            filters['poultry__user'] = user
        elif role == 'PoultryScience':
            poultry_science = PoultryScience.objects.filter(user=user).values_list('poultry__id', flat=True).distinct()
            filters['poultry__id__in'] = poultry_science

        if 'chain' in request.GET:
            if request.GET['chain'] == 'true' or request.GET['chain']:
                filters['InteractTypeName'] = 'در مشارکت با زنجیره'
        poultry_hatchings = PoultryHatching.objects.filter(**filters).values(
            'poultry', 'has_chain_company', 'key'
        ).annotate(
            last_hatching_remain_quantity=Max('left_over')
        )

        age_range = ChickenAgeRange.objects.filter(trash=False).first()
        if 'min_age' in request.GET or 'direct_buying' in request.GET:
            if age_range and age_range.active:
                poultry_hatchings = poultry_hatchings.filter(chicken_age__range=(age_range.minimum, age_range.maximum))
            elif min_age:
                poultry_hatchings = poultry_hatchings.filter(chicken_age__range=(min_age, max_age))

        poultry_remain_dict = {
            poultry_hatching['poultry']: {
                'last_hatching_remain_quantity': poultry_hatching['last_hatching_remain_quantity'],
                'chain_company': {
                    "chain_company": poultry_hatching['has_chain_company'],
                    "hatching_key": poultry_hatching['key'],
                },
                'allow_sell_free': ProvinceAllowPoultrySellFree.objects.filter(
                    poultry_id=poultry_hatching['poultry']
                ).values_list('allow', flat=True).first() or False
            }
            for poultry_hatching in poultry_hatchings
        }

        poultry = Poultry.objects.filter(id__in=poultry_remain_dict.keys()).select_related('user', 'address').order_by(
            'id')
        serializer = GetAllPoultrySerializer(poultry, many=True, context={'poultry_remain_dict': poultry_remain_dict})
        return Response(serializer.data, status=status.HTTP_200_OK)


class PoultryPredictionViewSet(viewsets.ModelViewSet):
    queryset = PoultryPrediction.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryPredictionSerializer


class HatchingIncreaseRequestViewSet(viewsets.ModelViewSet):
    queryset = HatchingIncreaseRequest.objects.all()
    serializer_class = HatchingIncreaseRequestSerializer
    permission_classes = [TokenHasReadWriteScope]
    filterset_class = HatchingIncreaseRequestFilterSet
    pagination_class = CustomPagination

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        query = HatchingIncreaseRequest.objects.filter(trash=False).order_by('-date')
        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                query = query.filter(
                    build_query(self.filterset_class, value)
                )
        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        page = self.paginate_queryset(query)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)
        ser_data = self.serializer_class(query, many=True)
        return Response(ser_data.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(trash=False, user=request.user)
        hatching_key = request.data["hatching_key"]
        hatching = PoultryHatching.objects.get(trash=False, key=hatching_key)
        request.data.pop('hatching_key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            hatching_increase = serializer.create(validated_data=request.data)
            hatching_increase.hatching = hatching
            hatching_increase.registerer_name = user.fullname
            hatching_increase.registerer_mobile = user.mobile
            hatching_increase.hatching_left_over = hatching.left_over
            hatching_increase.hatching_quantity = hatching.quantity
            hatching_increase.hatching_losses = hatching.total_losses
            hatching_increase.hatching_kill_quantity = hatching.killed_quantity
            hatching_increase.save()
            calculate_hatching_increase(hatching)

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status.HTTP_403_FORBIDDEN)

    def update(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(trash=False, user=request.user)

        data = request.data
        query = HatchingIncreaseRequest.objects.get(trash=False, key=data['key'])
        query.quantity = data['quantity']
        query.message = data['message']
        query.registerer_name = user.fullname
        query.registerer_mobile = user.mobile
        query.registerer_role = data['role']
        query.date = datetime.datetime.now()
        query.save()
        calculate_hatching_increase(query.hatching)
        return Response({"result": "با موفقیت انجام شد."}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        query = HatchingIncreaseRequest.objects.get(trash=False, key=request.GET['key'])
        hatching = query.hatching
        if hatching.left_over < query.quantity:
            return Response({'result': 'به علت کم بودن حجم مانده در سالن اجازه حذف ندارید!'},
                            status=status.HTTP_403_FORBIDDEN)
        query.trash = True
        query.save()
        calculate_hatching_increase(hatching)
        return Response({"result": "با موفقیت انجام شد."}, status=status.HTTP_200_OK)


class ChickenCommissionPricesViewSet(viewsets.ModelViewSet):
    queryset = ChickenCommissionPrices.objects.all()
    serializer_class = ChickenCommissionPricesSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination

    def list(self, request, *args, **kwargs):
        ChickenCommissionPrices.objects.get_or_create(date__date=datetime.date.today(),
                                                      defaults={'date': datetime.datetime.now(),
                                                                'kill_house_price': kill_house_price})
        create_update_chicken_commission_prices()
        query = ChickenCommissionPrices.objects.filter(trash=False).order_by('-date')
        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        page = self.paginate_queryset(query)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)
        ser_data = self.serializer_class(query, many=True)
        return Response(ser_data.data, status=status.HTTP_200_OK)


class GetAllPoultryFoIncreaseHatchingViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET.get('role')
        min_age = int(request.GET.get('min_age', 0))
        max_age = int(request.GET.get('max_age', min_age))

        filters = {
            'allow_hatching': 'pending',
            'state': 'pending',
            'archive': False,
            'trash': False
        }

        if role == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            filters['poultry__city_operator'] = city_operator.unit_name
        elif role == 'Poultry':
            filters['poultry__user'] = user
        if 'chain' in request.GET:
            if request.GET['chain'] == 'true' or request.GET['chain']:
                filters['InteractTypeName'] = 'در مشارکت با زنجیره'
        poultry_hatchings = PoultryHatching.objects.filter(**filters).values(
            'poultry', 'has_chain_company', 'key'
        ).annotate(
            last_hatching_remain_quantity=Max('left_over')
        )

        age_range = ChickenAgeRange.objects.filter(trash=False).first()
        if 'min_age' in request.GET or 'direct_buying' in request.GET:
            if age_range and age_range.active:
                poultry_hatchings = poultry_hatchings.filter(chicken_age__range=(age_range.minimum, age_range.maximum))
            elif min_age:
                poultry_hatchings = poultry_hatchings.filter(chicken_age__range=(min_age, max_age))

        poultry_remain_dict = {
            poultry_hatching['poultry']: {
                'last_hatching_remain_quantity': poultry_hatching['last_hatching_remain_quantity'],
                'chain_company': {
                    "chain_company": poultry_hatching['has_chain_company'],
                    "hatching_key": poultry_hatching['key'],
                },
                'allow_sell_free': ProvinceAllowPoultrySellFree.objects.filter(
                    poultry_id=poultry_hatching['poultry']
                ).values_list('allow', flat=True).first() or False
            }
            for poultry_hatching in poultry_hatchings
        }

        poultry = Poultry.objects.filter(id__in=poultry_remain_dict.keys()).select_related('user', 'address').order_by(
            'id')
        serializer = GetAllPoultrySerializer(poultry, many=True, context={'poultry_remain_dict': poultry_remain_dict})
        return Response(serializer.data, status=status.HTTP_200_OK)


class PoultryRequestQuarantineCodeViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequestQuarantineCode.objects.all()
    serializer_class = PoultryRequestQuarantineCodeSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        poultry_request_key = request.GET.get('poultry_request_key')
        codes = PoultryRequestQuarantineCode.objects.filter(poultry_request__key=poultry_request_key,
                                                            trash=False).order_by('id')
        serializer = self.serializer_class(codes, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        poultry_request = PoultryRequest.objects.get(key=request.data['poultry_request_key'])
        request.data.pop('poultry_request_key')

        if PoultryRequestQuarantineCode.objects.filter(quarantine_code=request.data['quarantine_code'],
                                                       trash=False).exists():
            return Response({"result": "این کد قبلا وارد شده است!"}, status=status.HTTP_403_FORBIDDEN)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            code = serializer.create(validated_data=request.data)
            code.registrar = user.fullname
            code.register_date = datetime.datetime.now()
            code.poultry_request = poultry_request
            code.save()
            get_gid_poultry_request_quarantine_code(code.id)

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    def update(self, request, pk=None, *args, **kwargs):
        code_key = request.data.pop('request_code_key')

        code = PoultryRequestQuarantineCode.objects.get(key=code_key)

        if 'quarantine_code' in request.data.keys():
            if code.quarantine_code != request.data['quarantine_code']:
                if PoultryRequestQuarantineCode.objects.filter(
                        quarantine_code=request.data['quarantine_code'], trash=False).exists():
                    return Response({"result": "این کد قبلا وارد شده است!"}, status=status.HTTP_403_FORBIDDEN)

        serializer = self.serializer_class(code)
        serializer.update(instance=code, validated_data=request.data)
        get_gid_poultry_request_quarantine_code(code.id)

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

    def destroy(self, request, *args, **kwargs):
        code_key = request.GET.get('request_code_key')
        code = PoultryRequestQuarantineCode.objects.get(key=code_key)
        code.trash = True
        code.save()
        return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)


class EvacuationHatchingDetailViewSet(viewsets.ModelViewSet):
    queryset = EvacuationHatchingDetail.objects.filter(trash=False)
    serializer_class = EvacuationHatchingDetailSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = EvacuationHatchingDetailFilterSet
    filterset_fields = [
        'hatching__key',
        'hatching__poultry__breeding_unique_id',
        'PartIdCode',
        'RequestId',
        'MoReportId',
        'ReportType',
        'ReportStatus',
        'GoodCount',
        'IsDeleted',
        'IsPersisted',
        'AllowInsert',
        'AllowUpdate',
        'ExternalId',
        'StringId',
    ]


class HatchingDetailView(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        hatching = PoultryHatching.objects.filter(
            trash=False,
            key=request.GET['key']
        ).select_related('poultry').first()
        ser_data = PoultryHatchingForDetailsSerializer(hatching).data
        kill_requests = KillHouseRequest.objects.filter(
            trash=False,
            province_request__poultry_request__hatching=hatching,
            ware_house_confirmation=True
        ).select_related(
            'killhouse_user',
            'killer',
            'province_request',
            'province_request__poultry_request',
            'kill_request'
        ).order_by('-create_date')
        ser_data_kill_request = KillHouseRequestForHatchingDetailSerializer(kill_requests, many=True).data

        poultry_requests = PoultryRequest.objects.filter(hatching=hatching, trash=False,
                                                         state_process__in=('pending', 'accepted'),
                                                         province_state__in=('pending', 'accepted'), out=True,
                                                         out_province_request_cancel=False,
                                                         temporary_trash=False,
                                                         temporary_deleted=False)

        ser_data_poultry_request = PoultryRequestForHatchingDetailSerializer(poultry_requests, many=True).data

        chain_allocation = ChainAllocation.objects.filter(trash=False, state='accepted', poultry_hatching=hatching)
        ser_data_chain_allocation = ChainAllocationForHatchingDetailSerializer(chain_allocation, many=True).data

        bar_diffrent_requests = BarDifferenceRequest.objects.filter(trash=False, hatching=hatching,
                                                                    state='accepted').order_by('-id')
        bar_diffrent_requests_serializer_data = BarDifferenceRequestSerializer(bar_diffrent_requests, many=True).data

        evacuation_reports = []
        if hatching:
            details_qs = hatching.evacuation_details.filter(trash=False).order_by('-ReportDate', '-create_date')
            evacuation_reports = EvacuationHatchingDetailSerializer(details_qs, many=True).data

        date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                           '%Y-%m-%d').date() if 'date1' in request.GET else None
        date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                           '%Y-%m-%d').date() if 'date1' in request.GET else None

        poultry_hatching_licence_number = hatching.licence_number
        response = requests.post(
            f'https://rsibackend.rasadyar.com/app/send_different_bar_with_licence_number/?'
            f'licence_number={poultry_hatching_licence_number}'
            f'&date1={date1}&date2={date2}',
            headers={'Content-Type': 'application/json'}
        )

        kill_requests_non_receipt = KillHouseRequest.objects.filter(
            trash=False,
            province_request__poultry_request__hatching=hatching,
            non_receipt=True, main_non_receipt=True
        ).select_related(
            'killhouse_user',
            'killer',
            'province_request',
            'province_request__poultry_request',
            'kill_request'
        ).order_by('-create_date')
        ser_data_non_receipt_kill_request = KillHouseRequestForHatchingDetailSerializer(kill_requests_non_receipt,
                                                                                        many=True).data
        filters = {
            'archive_wage': False,
            'state__in': ('pending', 'accepted'),
            'first_car_allocated_quantity': 0,
            'return_to_province': False
        }
        return_province_kill_requests = ProvinceKillRequest.objects.filter(
            trash=True, return_trash=True, **filters,
            province_request__poultry_request__hatching=hatching).order_by('id')
        return_province_kill_requests_serializer = ReturnProvinceKillRequestSerializer(return_province_kill_requests,
                                                                                       many=True).data

        kill_house_requests_return = KillHouseRequest.objects.filter(
            trash=True, return_trash=True,
            province_request__poultry_request__hatching=hatching)
        kill_house_requests_return_serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests_return,
                                                                                           many=True).data

        bar_requests = BarDifferenceRequest.objects.filter(trash=False,
                                                           state='accepted').order_by('id')
        bar_request_serilizer = BarDifferenceRequestSerializer(bar_requests, many=True).data

        hatching_increase = HatchingIncreaseRequest.objects.filter(trash=False).order_by('-date')
        hatching_increase_serilizer = HatchingIncreaseRequestSerializer(hatching_increase, many=True).data
        result = {
            **ser_data,
            "bars": ser_data_kill_request,
            'outBars': ser_data_poultry_request,
            'chainAllocation': ser_data_chain_allocation,
            "differentBars": response.json(),
            "nonReceipt": ser_data_non_receipt_kill_request,
            "returnProvinceRequest": return_province_kill_requests_serializer,
            "returnKillHouseRequest": kill_house_requests_return_serializer,
            "killingDifference": bar_request_serilizer,
            "hatchingIncrease": hatching_increase_serilizer,
            "bar_diffrent_requets": bar_diffrent_requests_serializer_data,
            "evacuation_reports": evacuation_reports,
        }
        return Response(result)


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def bulk_test_data(request):
    count = int(request.query_params.get('count', 1000000))  # پیش‌فرض 1 میلیون

    result = []
    for i in range(count):
        data = {
            "id": i + 1,
            "unit_name": 'nn',
            "Lat": 34.88681445023634 + random.uniform(-0.1, 0.1),
            "Long": 48.32817003380081 + random.uniform(-0.1, 0.1),
            "user": {
                "fullname": 'sdfsd',
                "mobile": 'sdfsd'
            },
            "hatching": [
                {
                    "quantity": random.randint(10000, 50000),
                    "left_over": random.randint(10000, 50000),
                    "period": random.randint(1, 30),
                    "chicken_age": random.randint(1, 100),
                    "date": (datetime.datetime.now() - timedelta(days=random.randint(1, 365))).isoformat(),
                    "violation": random.choice([True, False]),
                    "archive": False,
                    "licence_number": str(random.randint(1000000000, 9999999999)),
                    "samasat_discharge_percentage": random.randint(0, 100),
                    "chicken_breed": random.choice(["آربراکرز (آپلاس)", "راس", "کاب", "هوبارد"]),
                    "total_killed_weight": round(random.uniform(0, 1000), 2),
                    "killed_quantity": random.randint(0, 1000),
                    "PersonTypeName": random.choice(["حقیقی", "حقوقی"]),
                    "InteractTypeName": random.choice(["مالک", "مستأجر"]),
                    "UnionTypeName": random.choice(["تعاونی", "خصوصی", "دولتی"]),
                    "CertId": str(random.randint(100000000000, 999999999999))
                }
            ],
            "address": {
                "city": {
                    "name": 'همدان'
                },
                "address": 'sdasdasdasd'
            },
            "breeding_unique_id": str(random.randint(100000000000, 999999999999))
        }
        result.append(data)

    return Response(result)


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def get_hatching_for_bazrasi(request):
    active = request.GET['active']
    poultry = Poultry.objects.filter(trash=False, breeding_unique_id=request.GET['code']).first()
    if poultry:
        poultry_hatching = PoultryHatching.objects.filter(trash=False, poultry=poultry).order_by('id')
        if active == 'true':
            poultry_hatching = poultry_hatching.filter(state='pending', allow_hatching='pending', archive=False)
        else:
            poultry_hatching = poultry_hatching.filter(archive=True).last()
            poultry_hatching = [poultry_hatching] if poultry_hatching else []
        ser_data = PoultryHatchingForBazrasiSerializer(poultry_hatching, many=True).data
        return Response(ser_data, status.HTTP_200_OK)
    return Response({'result': "مرغدار وجود ندارد!"}, status.HTTP_403_FORBIDDEN)


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def get_poultry_for_bazrasi(request):
    breeding_unique_id = request.GET.get('code') or request.GET.get('breeding_unique_id')

    if not breeding_unique_id:
        return Response({'result': "شناسه یکتا مرغدار ارسال نشده است!"}, status=status.HTTP_400_BAD_REQUEST)

    poultry = Poultry.objects.filter(
        trash=False,
        breeding_unique_id=breeding_unique_id
    ).select_related(
        'user', 'address', 'address__city', 'address__province'
    ).first()

    if not poultry:
        return Response({'result': "مرغدار وجود ندارد!"}, status=status.HTTP_404_NOT_FOUND)

    active_hatchings = PoultryHatching.objects.filter(
        trash=False,
        poultry=poultry,
        state='pending',
        allow_hatching='pending',
        archive=False
    ).select_related(
        'chain_company', 'poultry'
    ).order_by('id')

    poultry_serializer = PoultryDetailForPoultryAndHatchingForPoultryScienceSerializer(poultry)
    hatchings_serializer = PoultryHatchingForPoultryAndHatchingForPoultryScienceSerializer(active_hatchings, many=True)

    result = {
        'poultry': poultry_serializer.data,
        'active_hatchings': hatchings_serializer.data
    }

    return Response(result, status=status.HTTP_200_OK)


class PoultryRequestForDirectBuyingViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = PoultryRequestForDirectBuyingSerializer
    filterset_class = PoultryRequestDirectBuyingFilterSet
    pagination_class = CustomPagination

    def get_queryset(self):
        user = SystemUserProfile.objects.select_related("user").get(user=self.request.user, trash=False)
        role = self.request.GET.get('role')
        date1, date2 = self.request.GET.get('date1'), self.request.GET.get('date2')
        now = datetime.datetime.now()

        categories = {c.name: c for c in IndexWeightCategory.objects.filter(trash=False).only('name')}
        light, average, heavy = categories.get("سبک"), categories.get("متوسط"), categories.get("سنگین")

        show_market = ShowMarketRequest.objects.filter(trash=False, allow=True).first()
        now_time = now.time().replace(second=0, microsecond=0)

        filters = Q(
            state_process='accepted',
            province_state='accepted',
            temporary_trash=False,
            trash=False,
            out=False,
            final_state='pending',
            market=True
        )

        if date1 and date2:
            filters &= Q(send_date__date__gte=date1, send_date__date__lte=date2)
        else:
            filters &= Q(send_date__date=now.date())

        queryset = PoultryRequest.objects.select_related(
            "poultry__user__city",
            "hatching"
        ).filter(filters)

        if role == "KillHouse" and show_market:
            kill_house = KillHouse.objects.filter(trash=False, kill_house_operator__user=user).first()
            if not (
                    kill_house and kill_house.market_buying and show_market.start_time < now_time < show_market.end_time):
                return PoultryRequest.objects.none()

        breed = self.request.GET.get('breed')
        city = self.request.GET.get('city')
        remain = self.request.GET.get('remain')
        min_amount = self.request.GET.get('min_amount')
        max_amount = self.request.GET.get('max_amount')
        weight = self.request.GET.get('weight')
        min_age = self.request.GET.get('min_age')
        max_age = self.request.GET.get('max_age')
        value = self.request.GET.get('value')
        search = self.request.GET.get('search')

        if breed:
            queryset = queryset.filter(chicken_breed__in=breed.split(','))
        if city:
            queryset = queryset.filter(poultry__user__city__name__in=city.split(','))
        if remain == 'true':
            queryset = queryset.filter(remain_quantity__gt=0)
        if min_amount:
            queryset = queryset.filter(amount__gte=min_amount)
        if max_amount:
            queryset = queryset.filter(amount__lte=max_amount)

        if weight and (light and average and heavy):
            if weight == 'سبک':
                queryset = queryset.filter(Index_weight__gte=light.min_value, Index_weight__lt=light.max_value)
            elif weight == 'متوسط':
                queryset = queryset.filter(Index_weight__gte=average.min_value, Index_weight__lt=average.max_value)
            elif weight == 'سنگین':
                queryset = queryset.filter(Index_weight__gte=heavy.min_value, Index_weight__lte=heavy.max_value)

        if min_age:
            queryset = queryset.filter(hatching__chicken_age__gte=min_age)
        if max_age:
            queryset = queryset.filter(hatching__chicken_age__lte=max_age)

        if value and search == 'filter' and value.strip() and value != 'undefined':
            queryset = queryset.filter(build_query(self.filterset_class, value))

        return queryset

    def get(self, request):
        queryset = self.get_queryset()

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

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

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


class PoultryHatchingForDirectBuyingViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        result = None
        hatching = PoultryHatching.objects.get(key=request.GET['hatching_key'])
        poultry_requests = PoultryRequest.objects.filter(hatching=hatching, state_process__in=('pending', 'accepted'),
                                                         province_state__in=('pending', 'accepted'), trash=False,
                                                         temporary_trash=False,
                                                         out=False).order_by('send_date')
        poultry_requests_info = poultry_requests.aggregate(
            avg_weight=Avg('Index_weight'),
            min_age=Min('killing_age'),
            max_age=Max('killing_age')
        )

        kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                              province_request__poultry_request__in=poultry_requests)
        kill_house_requests_info = kill_house_requests.aggregate(
            avg_weight_losse=Avg('weight_loss')
        )
        completed_bars = kill_house_requests.filter(assignment_state_archive='True')
        receive_bars_percent = (
                                       completed_bars.count() / kill_house_requests.count()) * 100 if kill_house_requests else 0

        if poultry_requests:
            result = {
                'min_age': poultry_requests_info['min_age'] or 1,
                'max_age': poultry_requests_info['max_age'] or 1,
                'now_age': hatching.chicken_age,
                'avg_weight': round(poultry_requests_info['avg_weight'] or 0, 2) or 0,
                'avg_weight_losse': round(kill_house_requests_info['avg_weight_losse'] or 0, 2) or 0,
                'receive_bars_percent': round(receive_bars_percent, 2),
            }

        return Response(result, status=status.HTTP_200_OK)


class PoultryHatchingChartForDirectBuyingViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        user = SystemUserProfile.objects.get(user=self.request.user, trash=False)
        today = datetime.date.today()
        now = datetime.datetime.now()
        role = request.GET.get('role')
        show_market = ShowMarketRequest.objects.filter(trash=False, allow=True).first()
        now_time = now.time().replace(second=0, microsecond=0)
        index_weight_category = IndexWeightCategory.objects.filter(trash=False).order_by('id')
        light = index_weight_category.filter(name='سبک').first()
        average = index_weight_category.filter(name='متوسط').first()
        heavy = index_weight_category.filter(name='سنگین').first()
        light_min_value = light.min_value
        light_max_value = light.max_value
        average_min_value = average.min_value
        average_max_value = average.max_value
        heavy_min_value = heavy.min_value
        heavy_max_value = heavy.max_value
        if show_market and role == 'KillHouse':
            kill_house = KillHouse.objects.filter(trash=False, kill_house_operator__user=user).first()

            if show_market.start_time < \
                    now_time < show_market.end_time:
                if kill_house.market_buying:

                    queryset = (
                        PoultryRequest.objects.filter(
                            send_date__date=today,
                            state_process='accepted',
                            province_state='accepted',
                            temporary_trash=False,
                            trash=False,
                            out=False,
                            final_state='pending',
                            market=True,
                        )
                            .values("poultry__user__city__name")
                            .annotate(
                            total_quantity=Sum('quantity'),
                            light_quantity=Sum(
                                Case(
                                    When(Q(Index_weight__gte=light_min_value, Index_weight__lt=light_max_value),
                                         then="quantity"),
                                    output_field=IntegerField(),
                                )
                            ),
                            average_quantity=Sum(
                                Case(
                                    When(Q(Index_weight__gte=average_min_value, Index_weight__lt=average_max_value),
                                         then="quantity"),
                                    output_field=IntegerField(),
                                )
                            ),
                            heavy_quantity=Sum(
                                Case(
                                    When(Q(Index_weight__gte=heavy_min_value, Index_weight__lt=heavy_max_value),
                                         then="quantity"),
                                    output_field=IntegerField(),
                                )
                            ),
                        )
                    )

                    result = [
                        {
                            "city": row["poultry__user__city__name"],
                            "total_quantity": row["total_quantity"] or 0,
                            "category": [
                                {
                                    "name": light.name,
                                    "min_value": light.min_value,
                                    "max_value": light.max_value,
                                    "quantity": row['light_quantity'] or 0,
                                },
                                {
                                    "name": average.name,
                                    "min_value": average.min_value,
                                    "max_value": average.max_value,
                                    "quantity": row['average_quantity'] or 0,
                                },
                                {
                                    "name": heavy.name,
                                    "min_value": heavy.min_value,
                                    "max_value": heavy.max_value,
                                    "quantity": row['heavy_quantity'] or 0,
                                }
                            ]
                        }
                        for row in queryset
                    ]

                else:
                    result = []

            else:
                result = []
        else:
            queryset = (
                PoultryRequest.objects.filter(
                    send_date__date=today,
                    state_process='accepted',
                    province_state='accepted',
                    temporary_trash=False,
                    trash=False,
                    out=False,
                    final_state='pending',
                    market=True,
                )
                    .values("poultry__user__city__name")
                    .annotate(
                    total_quantity=Sum('quantity'),
                    light_quantity=Sum(
                        Case(
                            When(Q(Index_weight__gte=light_min_value, Index_weight__lt=light_max_value),
                                 then="quantity"),
                            output_field=IntegerField(),
                        )
                    ),
                    average_quantity=Sum(
                        Case(
                            When(Q(Index_weight__gte=average_min_value, Index_weight__lt=average_max_value),
                                 then="quantity"),
                            output_field=IntegerField(),
                        )
                    ),
                    heavy_quantity=Sum(
                        Case(
                            When(Q(Index_weight__gte=heavy_min_value, Index_weight__lt=heavy_max_value),
                                 then="quantity"),
                            output_field=IntegerField(),
                        )
                    ),
                )
            )

            result = [
                {
                    "city": row["poultry__user__city__name"],
                    "total_quantity": row["total_quantity"] or 0,
                    "category": [
                        {
                            "name": light.name,
                            "min_value": light.min_value,
                            "max_value": light.max_value,
                            "quantity": row['light_quantity'] or 0,
                        },
                        {
                            "name": average.name,
                            "min_value": average.min_value,
                            "max_value": average.max_value,
                            "quantity": row['average_quantity'] or 0,
                        },
                        {
                            "name": heavy.name,
                            "min_value": heavy.min_value,
                            "max_value": heavy.max_value,
                            "quantity": row['heavy_quantity'] or 0,
                        }
                    ]
                }
                for row in queryset
            ]

        return Response(result, status=status.HTTP_200_OK)


class ManagementHatchingAgeRangeViewSet(viewsets.ModelViewSet):
    queryset = ManagementHatchingAgeRange.objects.all().order_by('from_age')
    serializer_class = ManagementHatchingAgeRangeSerializer
    permission_classes = [TokenHasReadWriteScope]
