# import random
import random
import string
import threading
from datetime import datetime, timedelta

import jdatetime
import requests
from django.contrib.auth.models import User, Group
from django.db.models import Case, When, Avg
from django.http import JsonResponse, HttpResponse
from django.http import QueryDict
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django_filters.rest_framework import DjangoFilterBackend
from oauth2_provider.contrib.rest_framework import (
    TokenHasReadWriteScope,
)
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import permission_classes, api_view
from rest_framework.generics import GenericAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from authentication.arvan_image.arvan_storage import upload_object_resize
from authentication.models import UserProfile, SystemUserProfile, City, Province, SystemAddress
from authentication.serializer.serializer import SystemUserProfileSerializer
from authentication.sms_management import kill_request_province_sms, province_kill_request_to_kill_house_sms, \
    kill_request_delete_province_sms, province_kill_request_accept_sms, document_discrepancy_sms, export_code_sms, \
    car_allocation_vet_farm_sms, delete_car_allocation_vet_farm_sms, send_sms_for_bar_difference_request, \
    confirm_price_poultry_request_direct_buying_sms, send_sms_fro_kill_request_market, send_sms_for_sale_bar
from authentication.views import ARTA_URL_CHANGE_MOBILE_NUMBER
from bot_eata import bot_eitaa_for_each_province_kill_request, bot_eitaa_for_each_delete_province_kill_request, \
    send_single_bar_to_eitaa
from deposit_id import market_code_state
from general_urls import base_url_sms, base_url_for_sms_report
from panel.KillHouse.helpers import kill_house_requests_product_warehousing, kill_house_free_buying_product_warehousing, \
    kill_house_free_sale_product_warehousing, get_finance_info, generate_unique_bar_code, \
    send_ticket_for_bar_difference_request, market_poultry_request_remain_quantity, market_kill_request_share_quantity, \
    calculate_governmental_quota, check_kill_house_remain_limitation_weight
from panel.KillHouse.serializers import (
    KillHouseSerializer,
    KillHouseRequestSerializer,
    KillRequestSerializer,
    KillHouseAssignmentInformationSerializer,
    KillHouseCheckRequestSerializer,
    KillHouseADDCARSerializer,
    VetSerializer,
    VetCheckRequestSerializer,
    ProvinceKillRequestSerializer,
    KillHouseRequestExchangeSerializer,
    KillHouseRequestExchangeReserveSerializer,
    KillHouseRequestExchangeAddCarSerializer,
    KillHouseDriverSerializer,
    KillHouseOperatorSerializer,

    KillHouseRequestActionSerializer,

    KillHouseRequestActionWinnerSerializer, DriverRequestCancelSerializer, KillHouseVetSerializer,
    KillHouseComplaintSerializer, CheckKillHouseComplaintSerializer, CheckUnusualCasualtiesSerializer,
    KillHousePercentageSerializer, KillHouseAssignmentImagesSerializer, KillRequestFactorSerializer,
    KillRequestFactorPaymentSerializer, AutomaticKillRequestSerializer, KillHouseCreditorsSerializer,
    KillHouseAllowVetSerializer, KillHouseWareHouseSerializer, KillHouseFreeBarInformationSerializer,
    KillHouseRequestForBarManagementSerializer, ProvinceKillRequestProvinceWageSerializer,
    KillHouseForProvinceWageSerializer, KillHouseforPurchaseRequestSerializer, KillHousePurchaseRequestSerializer,
    KillHouseForAutomaticStewardAllocationSerializer, KillHouseForTotalReportAutomaticStewardAllocationSerializer,
    PoultryRequestLetterForProvinceVetSerializer,
    ProvinceKillRequestForKillingInformationDiscrepancyReportSerializer, KillHouseRequestForDiffrentBarInfoSerializer,
    PoultryRequestForTotalInformationSerializer, PoultryRequestForTotalInformationInTableSerializer,
    KillHouseWareHouseForDailyBroadCastOInDetailsSerializer, KillHouseAssignmentInformationForCompletedLoadsSerializer,
    KillHouseFreeSaleBarInformationSerializer, KillHouseWageForTotalDashbordSerializer,
    KillHouseForProvinceWageWithDateSerializer, SlaughterHouseTransactionSerializer, KillHouseWageSerializer,
    KillHouseForFreeBarWageSerializer, KillHouseForFreeBarWageWithDateSerializer,
    KillHouseForTotalProvinceWageTransactionSerializer, KillHouseForTotalProvinceWageTransactionWithDAteSerializer,
    KillHouseForKillHouseRequestWageWithDateSerializer, KillHouseForKillHouseRequestWageSerializer,
    KillHouseFreeBarInformationForWageTotalSerializer,
    TotalWageInformationKillHouseExclusiveKillerSerializer, KillHouseLetterForProvinceSerializer,
    PoultryRequestoutProvinceSerializer, BarDocumentStatusSerializer, GeneralKillHouseSerializer,
    VetKillHouseSerializer, VetFarmListSerializer, KillHouseForKillHouseVetKillHouseSerializer,
    KillHouseForFreeSaleBarInformationViewSetSerializer,
    KillHouseForFreeSaleBarInformationViewSetWithDateSerializer, KillHouseForNewWageInormationSerializer,
    KillHouseRequestForInputBarsSerializer, PosKillHouseSerializer, KillHouseForProvinceWareHouseDashboardSerializer,
    ParentCompanyKillHouseForNewWageInormationSerializer, KillHouseForColdHouseSerializer,
    KillHouseColdHousesSerializer, BarDifferenceRequestSerializer, distributionKillHouseSerializer,
    KillHouseForPerformanceDashboardSerializer, DirectBuyingPaymentSerializer, KillRequestForDirectBuyingSerializer,
    ProvinceKillRequestForDirectBuyingSerializer, KillHouseForCommonlyUsedSerializer, KillHouseMarketInfoSerializer,
    KillHouseForColdHouseAllocationSerializer, KillHouseForSegmentationSerializer,
    KillHouseComparativeInformationSerializer, KillRequestForDirectBuyingTrueSerializer,
    ReturnProvinceKillRequestSerializer, TotalKillHouseRemainWeightViewSetSerializer,
    TotalKillHouseWarehouseArchiveDashboardSerializer, PspKillHouseSerializer
)
from panel.ProvinceOperator.serializers import ProvinceFactorToKillHouseSerializer, StewardAllocationSerializer
from panel.ProvinceOperator.views import ARVAN_Kill_house_Factor_URL
from panel.ReportingPanel.helper import kill_house_request_filterset_fields, \
    poultry_request_new_fields
from panel.ReportingPanel.views import get_gid_out_province
from panel.VetFarm.serializers import VetFarmSerializer
from panel.admin import PROJECT_API_KEY
from panel.filterset import KillHouseDriverFilterSet, VetFilterSet, KillHouseRequestFilterSet, \
    ProvinceKillRequestFilterSet, KillHouseFilterSet, KillRequestFilterSet, PoultryRequestFilterSet, \
    KillHouseFreeBarInformationFilterSet, DashboardEnterLoadInformationFilterSet, \
    DashboardKillHouseFreeBarInformationFilterSet, VetFarmAndKillHouseFilterSet, ProvinceKillRequestNewFilterSet, \
    DashboardKillRequestFilterSet, KillHouseFreeSaleBarInformationFilterSet, \
    BarDifferenceRequestFilterSet, DirectBuyingPaymentFilterSet, ReturnProvinceKillRequestFilterSet
from panel.helper import build_query
from panel.models import (
    KillHouse,
    KillHouseRequest,
    KillRequest,
    ProvinceCheckOperatorRequest,
    KillHouseCheckRequest,
    KillHouseAssignmentInformation,
    ProvinceFactorToKillHouse,
    KillHouseADDCAR,
    Vet,
    VetCheckRequest,
    ProvinceKillRequest,
    KillHouseRequestExchange,
    KillHouseRequestExchangeReserve,
    PoultryRequestExchange,
    KillHouseRequestExchangeAddCar,
    PoultryRequest,
    KillHouseDriver,
    KillHouseOperator,
    VetFarm,
    KillHouseRequestAction,
    KillHouseRequestActionWinner, DriverRequestCancel, KillHouseVet, PercentageOfLosses, KillHouseComplaint,
    CheckKillHouseComplaint, ProvinceFactorToKillHouseForPoultry, CheckUnusualCasualties, KillHousePercentage,
    TotalPoultryRequestQuantity, KillHouseAssignmentImages, VetSupervisor, KillRequestFactor, KillRequestFactorPayment,
    Pricing, AutomaticKillRequest, KillHouseCreditors, ShareOfAllocation, ProvinceOperator, SmsLicense,
    KillHouseAllowVet, Wallet, ProvinceAllowKillHouseRegisterCar, PoultryHatching, Poultry,
    AutoAcceptProvinceKillRequest, KillHouseWareHouse, KillHouseFreeBarInformation, Guilds,
    CityOperator, PoultryRequestAuction, ProvinceAllowKillHouseChooseStewardGuilds, KillHouseHourLimit,
    ProvinceAllowKillHouseDirectBuying, KillHousePurchaseRequest, Steward, StewardAllocation, StewardWareHouse,
    ColdHouseAllocations, KillHouseFreeSaleBarInformation, OperationLimitation,
    EvacuationPermit, TimeRange, SlaughterHouseTransaction, WageType, PercentageOfWageType,
    InternalTransaction, BarDocumentStatus, VetFarmAggregatePermission, OutProvinceCarcassesBuyer, RolesProducts,
    AutomaticDirectBuyingPermission, FreeSaleWithinprovince, CityOperatorCheckRequest, POSMachine, ColdHouse,
    BarDifferenceRequest, ChickenAgeRange, RequestLimitation, PriceConfirmation, DirectBuyingPayment,
    DirectBuyingVerification, FinePermission, IndexWeightCategory, PosSegmentation, RestrictionCarcassDistribution,
    AllowRegisterCodeForKillHouseFreeSaleBarInformation, ProductsTransactions,
    LimitationForDirectPurchaseAndBarInformation, WarehouseArchive
)
# آدرس پایه مربوط به ذخیره عکس در گالری مربوط به کشتارگاه در استوریج آروان
from panel.poultry.helpers import poultry_prediction, create_update_chicken_commission_prices
from panel.poultry.serializers import PoultryRequestSerializer, PoultryRequestForKillingInformationSerializer
from ticket.bucket import upload_to_liara
from ticket.helper import send_image_to_server

ARVAN_Kill_house_URL = 'https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/'
ARTA_URL_REGISTER = "https://userbackend.rasadyar.com/api/register/"


class CustomPagination(PageNumberPagination):
    page_size = 10


from django.db.models import Q


def get_exclusive_killer_operation(kill_houses):
    for kill_house in kill_houses:
        total_unpaid_wage = 0
        total_paid_wage = 0
        province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
                                                                    state__in=('pending', 'accepted'), trash=False,
                                                                    return_to_province=False,
                                                                    first_car_allocated_quantity=0,
                                                                    archive_wage=False,
                                                                    )
        kill_house_requests = KillHouseRequest.objects.filter(
            Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q(
                Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q(
                Q(killer__isnull=True) | Q(killer=kill_house)),
            # killhouse_user=kill_house,
            archive_wage=False,
            trash=False
        )

        kill_house_requests = kill_house_requests.filter(Q(killer=kill_house) | Q(killhouse_user=kill_house))

        free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, archive_wage=False,
                                                               trash=False)

        total_unpaid_wage += province_kill_requests.aggregate(total=Sum('total_wage_amount'))[
                                 'total'] or 0
        total_unpaid_wage += free_bars.aggregate(total=Sum('total_wage_amount'))[
                                 'total'] or 0
        total_unpaid_wage += \
            kill_house_requests.aggregate(total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
                'total'] or 0
        slaughter_transactions = InternalTransaction.objects.filter(
            kill_house=kill_house, status='completed',
            trash=False)

        total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[
                               'total'] or 0
        total_amount = total_unpaid_wage - total_paid_wage
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(limitation=True, kill_house=kill_house).first()
        if kill_house_purchase:
            if total_amount >= kill_house_purchase.limitation_number:
                kill_house.show_exclusive = False
                kill_house.save()
            else:
                kill_house.show_exclusive = True
                kill_house.save()
        else:
            kill_house.show_exclusive = True
            kill_house.save()


def update_kill_house_requests(province_kill_request, poultry_request):
    # gate_way_percentage = PaymentGatewayPercentage.objects.get(trash=False)
    kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_request, trash=False)

    total_kill_house_requests_quantity = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_quantity'))[
        'total_quantity']
    total_kill_house_requests_weight = kill_house_requests.aggregate(total_weight=Sum('accepted_real_weight'))[
        'total_weight']
    total_first_allocated_cars = kill_house_requests.aggregate(total_weight=Sum('quantity'))[
        'total_weight']

    province_kill_request.total_killed_quantity = total_kill_house_requests_quantity or province_kill_request.main_quantity
    province_kill_request.first_car_allocated_quantity = total_first_allocated_cars or 0
    province_kill_request.total_killed_weight = total_kill_house_requests_weight or int(
        province_kill_request.main_quantity * poultry_request.Index_weight)
    province_kill_request.total_wage_amount = province_kill_request.total_killed_weight * province_kill_request.wage

    province_kill_request.save()

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


def update_province_kill_requests(poultry_hatching):
    province_kill_requests = ProvinceKillRequest.objects.filter(
        trash=False,
        state__in=('pending', 'accepted'),
        return_to_province=False,
        province_request__poultry_request__hatching=poultry_hatching
    )

    total_killed_quantity = province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total']
    total_extra_quantity = province_kill_requests.aggregate(total=Sum('extra_killed_quantity'))['total']

    free_filter = Q(province_request__poultry_request__free_sale_in_province=True, state__in=('pending', 'accepted'),
                    trash=False)
    governmental_filter = ~free_filter

    total_free_quantity = \
        province_kill_requests.filter(free_filter, province_request__poultry_request__export=False).aggregate(
            total=Sum('total_killed_quantity'))[
            'total']
    total_free_weight = \
        province_kill_requests.filter(free_filter, province_request__poultry_request__export=False).aggregate(
            total=Sum('total_killed_weight'))['total']
    total_governmental_quantity = \
        province_kill_requests.filter(governmental_filter, province_request__poultry_request__export=False).aggregate(
            total=Sum('total_killed_quantity'))['total']
    total_governmental_weight = \
        province_kill_requests.filter(governmental_filter, province_request__poultry_request__export=False).aggregate(
            total=Sum('total_killed_weight'))['total']
    total_export_quantity = \
        province_kill_requests.filter(province_request__poultry_request__export=True).aggregate(
            total=Sum('total_killed_quantity'))['total']
    total_export_weight = \
        province_kill_requests.filter(province_request__poultry_request__export=True).aggregate(
            total=Sum('total_killed_weight'))['total']

    poultry_hatching.free_killed_quantity = total_free_weight or 0
    poultry_hatching.free_quantity = total_free_quantity or 0
    poultry_hatching.governmental_killed_quantity = total_governmental_weight or 0
    poultry_hatching.governmental_quantity = total_governmental_quantity or 0
    poultry_hatching.export_killed_weight = total_export_weight or 0
    poultry_hatching.export_killed_quantity = total_export_quantity or 0
    poultry_hatching.extra_killed_quantity = total_extra_quantity or 0
    poultry_hatching.killed_quantity = total_killed_quantity or 0

    poultry_hatching.save()


class BarDocumentStatusViewset(viewsets.ModelViewSet):
    queryset = BarDocumentStatus.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = BarDocumentStatusSerializer

    def list(self, request, *args, **kwargs):
        bar_documents_status = BarDocumentStatus.objects.filter(trash=False).order_by('priority_id')
        serializer = self.serializer_class(bar_documents_status, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

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

        if 'priority_list' in request.data:
            priority_list = request.data['priority_list']
            priorities = {item['key']: item['value'] for item in priority_list}
            bar_documents_status = BarDocumentStatus.objects.filter(trash=False).order_by('priority_id')
            for document in bar_documents_status:
                priority_id = priorities.get(str(document.key))
                if priority_id is not None:
                    document.priority_id = priority_id
                    document.save()

            return Response({"result": "با موفقیت انجام شد."}, status=status.HTTP_200_OK)
        bar_documents_status = BarDocumentStatus.objects.get(key=request.data['bar_documents_status_key'], trash=False)
        request.data.pop('bar_documents_status_key')
        serializer = self.serializer_class(bar_documents_status)
        serializer.update(instance=bar_documents_status, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        bar_documents_status = BarDocumentStatus.objects.get(id=pk, trash=False)
        if KillHouseRequest.objects.filter(bar_document_status=bar_documents_status,
                                           trash=False).exists():
            return Response({"result": "به علت استفاده ار این وضعیت سند بر روی  بار امکان حذف  وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)
        bar_documents_status.delete()
        return Response({"result": "با موفقیت حذف شد."},
                        status=status.HTTP_200_OK)


class KillHouseCreditorsViewSet(viewsets.ModelViewSet):
    queryset = KillHouseCreditors.objects.all()
    serializer_class = KillHouseCreditorsSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        creditors = KillHouseCreditors.objects.filter(kill_house__system_address__province=user.province).order_by('id')
        serializer_request = self.serializer_class(creditors, many=True)
        return Response(serializer_request.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        creditors = KillHouseCreditors.objects.get(key=request.data["key"], trash=False)
        request.data.pop('key')
        amount = request.data['amount']
        request.data.pop('amount')

        creditors.amount -= float(amount)
        creditors.save()

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


# ویوست مربوط به اپراتور کشتارگاه
class KillHouseOperatorViewSet(viewsets.ModelViewSet):
    queryset = KillHouseOperator.objects.all()
    serializer_class = KillHouseOperatorSerializer
    permission_classes = [TokenHasReadWriteScope]

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

        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
            kill_house_operator_serializer = KillHouseOperatorSerializer(kill_house_operator)
            kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
            kill_house_serializer = KillHouseSerializer(kill_house, many=True)
            profile_info = {
                # 'profile': user_serializer.data,
                'kill_house_operator': kill_house_operator_serializer.data,
                'kill_house': kill_house_serializer.data
            }
            return Response(profile_info, status=status.HTTP_200_OK)


class KillHouseForKillHouseRequestWageViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForKillHouseRequestWageSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

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

        if 'date1' in request.GET:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if request.GET['role'] == 'ProvinceOPerator':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    archive_wage=False,
                    province_kill_request__union_share__gt=0,
                    trash=False).values(
                    'killhouse_user'), trash=False)
            elif request.GET['role'] == 'Company':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    province_kill_request__company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)
            elif request.GET['role'] == 'Guilds':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    province_kill_request__guilds_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)
            else:

                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)
        else:

            if request.GET['role'] == 'ProvinceOPerator':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    province_kill_request__union_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)
            elif request.GET['role'] == 'Company':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    province_kill_request__company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)
            elif request.GET['role'] == 'Guilds':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    province_kill_request__guilds_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)
            else:

                kill_houses = KillHouse.objects.filter(pk__in=KillHouseRequest.objects.filter(
                    archive_wage=False,
                    trash=False).values(
                    'killhouse_user'), trash=False)

        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 (self.filterset_class(
                                data=query,
                                queryset=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_houses = ps.filter()
                else:
                    kill_houses = kill_houses
        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_houses)
        if page is not None:
            if 'date1' in request.GET:
                serializer = KillHouseForKillHouseRequestWageWithDateSerializer(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 = KillHouseForProvinceWageWithDateSerializer(kill_houses, many=True,
                                                                    context={'request': request})
        else:

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


class KillHouseForNewWageInormationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForNewWageInormationSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

    def list(self, request, *args, **kwargs):
        kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list(
            'kill_house', flat=True)
        kill_houses = KillHouse.objects.filter(out_province=False, trash=False).exclude(id__in=kill_house_ids).order_by(
            'id')
        serializer = self.get_serializer(kill_houses, many=True, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseForColdHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForColdHouseSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

    def list(self, request, *args, **kwargs):
        kill_houses = KillHouse.objects.filter(out_province=False, trash=False,
                                               pk__in=ColdHouse.objects.filter(kill_house__isnull=False).values_list(
                                                   'kill_house', flat=True)).order_by('id')
        if 'search' in request.GET:
            if request.GET['search'] == 'filter':
                kill_houses_list = []
                if request.GET['value'] != "":
                    for item in self.filterset_fields:
                        query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                        if (self.filterset_class(
                                data=query,
                                queryset=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_houses_list = ps.filter()
                    kill_houses = [] if len(kill_houses_list) == 0 else kill_houses_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(kill_houses)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(kill_houses, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseColdHousesViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseColdHousesSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        serializer = self.get_serializer(kill_houses)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ParentCompanyKillHouseForNewWageInormationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = ParentCompanyKillHouseForNewWageInormationSerializer
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id')
        serializer = self.get_serializer(kill_houses, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseForProvinceWareHouseDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.filter(out_province=False, trash=False).order_by('id')
    serializer_class = KillHouseForProvinceWareHouseDashboardSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET.get('role')
        kill_house_filters = {'out_province': False, 'active': True, 'trash': False}
        if role in ['CityJahad']:
            kill_house_filters['kill_house_operator__user__city'] = user.city

        kill_houses = KillHouse.objects.filter(**kill_house_filters).order_by(
            'id')

        kill_houses = kill_houses.annotate(
            allocation_count=Count(
                'kill_house_steward_allocation',
                filter=Q(kill_house_steward_allocation__receiver_state__in=['pending', 'accepted'])
            )
        ).order_by(
            '-allocation_count'
        )
        serializer = self.get_serializer(kill_houses, many=True, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseForTotalProvinceWareHouseDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.filter(out_province=False, trash=False).order_by('id')
    serializer_class = KillHouseForProvinceWareHouseDashboardSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET.get('role')
        kill_house_filters = {'out_province': False, 'active': True, 'trash': False}
        if role in ['CityJahad']:
            kill_house_filters['kill_house_operator__user__city'] = user.city

        kill_houses = KillHouse.objects.filter(**kill_house_filters).order_by(
            'id')

        kill_houses = kill_houses.annotate(
            allocation_count=Count(
                'kill_house_steward_allocation',
                filter=Q(kill_house_steward_allocation__receiver_state__in=['pending', 'accepted'])
            )
        ).order_by(
            '-allocation_count'
        )
        products = RolesProducts.objects.filter(kill_house__in=kill_houses, trash=False, name='مرغ گرم')

        # products = RolesProducts.objects.filter(kill_house__in=kill_houses, trash=False)
        # product_remain_weight = products.aggregate(total=Sum('total_remain_weight'))[
        #                             'total'] or 0

        if 'date1' in request.GET:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            bars_date1 = date1
            bars_date2 = date2
            # bars_date1 = date1 - timedelta(days=1)
            # bars_date2 = date2 - timedelta(days=1)

            kill_house_requests = KillHouseRequest.objects.filter(
                input_warehouse__in=kill_houses,
                kill_request__recive_date__date__gte=bars_date1,
                kill_request__recive_date__date__lte=bars_date2,
                temporary_trash=False,
                temporary_deleted=False,
                trash=False, calculate_status=True, warehouse=True)

            kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter(Q(date__date__gte=date1,
                                                                                            date__date__lte=date2,
                                                                                            buy_type='carcass') | Q(
                create_date__date__gte=date1, create_date__date__lte=date2, buy_type='live'),
                                                                                          input_warehouse__in=kill_houses,
                                                                                          trash=False,
                                                                                          temporary_trash=False,
                                                                                          temporary_deleted=False,
                                                                                          calculate_status=True,
                                                                                          warehouse=True).exclude(
                entered_message='ورود به انبار مجازی')
            kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter(
                kill_house__in=kill_houses,
                date__date__gte=date1,
                date__date__lte=date2,
                trash=False,
                temporary_trash=False,
                temporary_deleted=False,
                calculate_status=True, warehouse=True)
            kill_house_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False,
                                                                      receiver_state__in=('pending', 'accepted'),
                                                                      date__date__gte=date1,
                                                                      date__date__lte=date2,
                                                                      temporary_trash=False,
                                                                      temporary_deleted=False,
                                                                      to_cold_house__isnull=True,
                                                                      calculate_status=True, warehouse=True)
            segmentations = PosSegmentation.objects.filter(kill_house__in=kill_houses, trash=False,
                                                           date__date__gte=date1,
                                                           date__date__lte=date2, warehouse=True)
            cold_house_allocations = StewardAllocation.objects.filter(
                kill_house__in=kill_houses,
                date__date__gte=date1,
                date__date__lte=date2,
                to_cold_house__isnull=False,
                receiver_state__in=('accepted', 'pending'),
                trash=False, warehouse=True)
            transactions = ProductsTransactions.objects.filter(product__in=products, transaction__paid=True,
                                                               transaction__date__date__gte=date1,
                                                               transaction__date__date__lte=date2, trash=False,
                                                               warehouse=True)
            archives = WarehouseArchive.objects.filter(kill_house__in=kill_houses, date__date__gte=date1,
                                                       date__date__lte=date2, trash=False, warehouse=True)


        else:
            kill_house_requests = KillHouseRequest.objects.filter(
                input_warehouse__in=kill_houses,
                temporary_trash=False,
                temporary_deleted=False,
                trash=False, calculate_status=True, warehouse=True)

            kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter(
                input_warehouse__in=kill_houses,
                trash=False,
                temporary_trash=False,
                temporary_deleted=False,
                calculate_status=True, warehouse=True).exclude(entered_message='ورود به انبار مجازی')
            kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter(
                kill_house__in=kill_houses,
                trash=False,
                temporary_trash=False,
                temporary_deleted=False,
                calculate_status=True, warehouse=True)
            kill_house_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False,
                                                                      receiver_state__in=('pending', 'accepted'),
                                                                      temporary_trash=False,
                                                                      temporary_deleted=False,
                                                                      to_cold_house__isnull=True,
                                                                      calculate_status=True, warehouse=True)

            segmentations = PosSegmentation.objects.filter(kill_house__in=kill_houses, trash=False, warehouse=True)
            cold_house_allocations = StewardAllocation.objects.filter(
                kill_house__in=kill_houses,
                to_cold_house__isnull=False,
                receiver_state__in=('accepted', 'pending'),
                trash=False, warehouse=True)
            transactions = ProductsTransactions.objects.filter(product__in=products, transaction__paid=True,
                                                               trash=False, warehouse=True)
            archives = WarehouseArchive.objects.filter(kill_house__in=kill_houses, trash=False, warehouse=True)

        total_kill_house_requests_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[
                                                 'total'] or 0
        total_kill_house_requests_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                                               'total'] or 0
        total_entered_kill_house_requests_carcasses_weight = \
            kill_house_requests.filter(ware_house_confirmation=True).aggregate(
                total=Sum('ware_house_accepted_real_weight'))[
                'total'] or 0
        total_entered_kill_house_requests_carcasses_governmental_weight = \
            kill_house_requests.filter(ware_house_confirmation=True,
                                       province_request__poultry_request__free_sale_in_province=False).aggregate(
                total=Sum('ware_house_accepted_real_weight'))[
                'total'] or 0
        total_entered_kill_house_requests_carcasses_free_weight = \
            kill_house_requests.filter(ware_house_confirmation=True,
                                       province_request__poultry_request__free_sale_in_province=True).aggregate(
                total=Sum('ware_house_accepted_real_weight'))[
                'total'] or 0
        kill_house_free_bar_informations_live = kill_house_free_bar_informations.filter(buy_type='live')
        kill_house_free_bar_informations_carcasses = kill_house_free_bar_informations.filter(buy_type='carcass')
        total_kill_house_free_bar_quantity = \
            kill_house_free_bar_informations_live.aggregate(total=Sum('quantity'))['total'] or 0
        total_kill_house_free_bar_weight = \
            kill_house_free_bar_informations_live.aggregate(total=Sum('live_weight'))['total'] or 0
        total_kill_house_free_bar_carcasses = \
            kill_house_free_bar_informations_carcasses.aggregate(total=Sum('number_of_carcasses'))[
                'total'] or 0
        total_kill_house_free_bar_carcasses_weight = \
            kill_house_free_bar_informations_carcasses.aggregate(total=Sum('weight_of_carcasses'))[
                'total'] or 0
        total_entered_kill_house_free_bar_carcasses_weight = \
            kill_house_free_bar_informations.aggregate(total=Sum('weight_of_carcasses'))[
                'total'] or 0

        total_kill_house_free_sale__bar_carcasses_weight = \
            kill_house_free_Sale_bar_informations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        total_kill_house_free_sale__bar_carcasses_governmental_weight = \
            kill_house_free_Sale_bar_informations.filter(quota='governmental').aggregate(
                total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_kill_house_free_sale__bar_carcasses_free_weight = \
            kill_house_free_Sale_bar_informations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_kill_house_allocations_weight = \
            kill_house_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        total_kill_house_allocations_governmental_weight = \
            kill_house_allocations.filter(quota='governmental').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        total_kill_house_allocations_free_weight = \
            kill_house_allocations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        segmentations_weight = \
            segmentations.aggregate(total=Sum('weight'))[
                'total'] or 0
        segmentations_governmental_weight = \
            segmentations.filter(quota='governmental').aggregate(total=Sum('weight'))[
                'total'] or 0
        segmentations_free_weight = \
            segmentations.filter(quota='free').aggregate(total=Sum('weight'))[
                'total'] or 0
        cold_house_allocations_weight = \
            cold_house_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        cold_house_allocations_governmental_weight = \
            cold_house_allocations.filter(quota='governmental').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        cold_house_allocations_free_weight = \
            cold_house_allocations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        pos_allocated_weight_info = transactions.aggregate(
            pos_allocated_weight=Sum('cur_weight'),
            pos_governmental_allocated_weight=Sum('cur_weight',
                                                  filter=Q(price_approved=True)),
            pos_free_allocated_weight=Sum('cur_weight', filter=Q(price_approved=False)),

        )
        archives_info = archives.aggregate(
            total_archive_governmental_weight=Sum('weight', filter=Q(quota='governmental')),
            total_archive_free_weight=Sum('weight', filter=Q(quota='free')),
        )
        pos_allocated_weight = pos_allocated_weight_info['pos_allocated_weight'] or 0
        pos_governmental_allocated_weight = pos_allocated_weight_info['pos_governmental_allocated_weight'] or 0
        pos_free_allocated_weight = pos_allocated_weight_info['pos_free_allocated_weight'] or 0
        total_archive_governmental_weight = archives_info['total_archive_governmental_weight'] or 0
        total_archive_free_weight = archives_info['total_archive_free_weight'] or 0

        total_governmental_input_weight = total_entered_kill_house_requests_carcasses_governmental_weight
        total_free_input_weight = total_entered_kill_house_requests_carcasses_free_weight + total_entered_kill_house_free_bar_carcasses_weight
        total_governmental_output_weight = total_kill_house_free_sale__bar_carcasses_governmental_weight + segmentations_governmental_weight + total_kill_house_allocations_governmental_weight + cold_house_allocations_governmental_weight + int(pos_governmental_allocated_weight / 1000)
        total_free_output_weight = total_kill_house_free_sale__bar_carcasses_free_weight + total_kill_house_allocations_free_weight + segmentations_free_weight + cold_house_allocations_free_weight + int(pos_free_allocated_weight / 1000)
        total_governmental_remain_weight = (
                                                   total_governmental_input_weight - total_governmental_output_weight) - total_archive_governmental_weight if (
                                                                                                                                                                      total_governmental_input_weight - total_governmental_output_weight) - total_archive_governmental_weight > 0 else 0
        last_total_governmental_remain_weight = (
                                                        (
                                                                total_governmental_input_weight - total_governmental_output_weight) - total_archive_governmental_weight) * -1 if (
                                                                                                                                                                                         total_governmental_input_weight - total_governmental_output_weight) - total_archive_governmental_weight < 0 else 0
        total_free_remain_weight = (total_free_input_weight - total_free_output_weight) - total_archive_free_weight if (
                                                                                                                               total_free_input_weight - total_free_output_weight) - total_archive_free_weight > 0 else 0
        last_total_free_remain_weight = ((
                                                 total_free_input_weight - total_free_output_weight) - total_archive_free_weight) * -1 if (
                                                                                                                                                  total_free_input_weight - total_free_output_weight) - total_archive_free_weight < 0 else 0
        last_total_remain_weight = last_total_governmental_remain_weight + last_total_free_remain_weight
        warehouse_total_weight = total_kill_house_requests_weight + total_kill_house_free_bar_weight + total_kill_house_free_bar_carcasses_weight
        warehouse_total_entered_carcasses_weight = total_entered_kill_house_requests_carcasses_weight + total_entered_kill_house_free_bar_carcasses_weight
        result = {
            "product_remain_weight": int(total_governmental_remain_weight + total_free_remain_weight),
            "warehouse_total_quantity": int(
                total_kill_house_requests_quantity + total_kill_house_free_bar_quantity + total_kill_house_free_bar_carcasses),
            "warehouse_total_weight": int(warehouse_total_weight),
            "warehouse_total_entered_carcasses_weight": int(warehouse_total_entered_carcasses_weight),
            "total_kill_house_allocations_weight": int(total_kill_house_allocations_weight),
            "total_kill_house_free_sale_bar_carcasses_weight": int(total_kill_house_free_sale__bar_carcasses_weight),
            "segmentations_weight": int(segmentations_weight),
            "cold_house_allocations_weight": int(cold_house_allocations_weight),
            "total_governmental_input_weight": int(total_governmental_input_weight),
            "total_free_input_weight": int(total_free_input_weight),
            "total_governmental_output_weight": int(total_governmental_output_weight),
            "total_free_output_weight": int(total_free_output_weight),
            "total_governmental_remain_weight": int(total_governmental_remain_weight),
            "total_free_remain_weight": int(total_free_remain_weight),
            "last_total_governmental_remain_weight": int(last_total_governmental_remain_weight),
            "last_total_free_remain_weight": int(last_total_free_remain_weight),
            "last_total_remain_weight": int(last_total_remain_weight),
            "pos_allocated_weight": int(pos_allocated_weight / 1000),
            "pos_governmental_allocated_weight": int(pos_governmental_allocated_weight / 1000),
            "pos_free_allocated_weight": int(pos_free_allocated_weight / 1000),
            "total_archive_governmental_weight": total_archive_governmental_weight,
            "total_archive_free_weight": total_archive_free_weight,

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


class KillHouseDistributionInormationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForNewWageInormationSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        role = request.GET.get('role')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if role == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            steward_allocations = StewardAllocation.objects.filter(kill_house=kill_house,
                                                                   receiver_state__in=('pending', 'accepted'),
                                                                   calculate_status=True, trash=False)
            free_sales = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
                                                                        calculate_status=True)
            steward_allocations_weight = \
                steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0

            free_sales_weight = free_sales.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0

        else:
            guild = Guilds.objects.get(user=user, trash=False)
            steward_allocations = StewardAllocation.objects.filter(Q(steward=guild) | Q(guilds=guild),
                                                                   receiver_state__in=('pending', 'accepted'),
                                                                   calculate_status=True, trash=False)
            steward_allocations_weight = \
                steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0

            free_sales_weight = 0

        result = {
            "steward_allocations_weight": steward_allocations_weight,
            "free_sales_weight": free_sales_weight,
        }

        return Response(result, status=status.HTTP_200_OK)


class KillHouseTotalDashboardForNewWageInormationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForKillHouseRequestWageSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id')
        total_wage_type = WageType.objects.filter(trash=False)
        province_live_wage_type = total_wage_type.filter(en_name='province-kill-request', trash=False).first()
        free_buying_live_weight_wage_type = total_wage_type.filter(en_name='live-buy', trash=False).first()
        free_buying_carcesses_weight_wage_type = total_wage_type.filter(en_name='carcasse-buy', trash=False).first()
        free_sell_carcesses_weight_wage_type = total_wage_type.filter(en_name='carcasse-sell', trash=False).first()
        province_live_wage_type_amount = province_live_wage_type.amount if province_live_wage_type.status == True else 0
        free_buying_live_weight_wage_type_amount = free_buying_live_weight_wage_type.amount if free_buying_live_weight_wage_type.status == True else 0
        free_buying_carcesses_weight_wage_type_amount = free_buying_carcesses_weight_wage_type.amount if free_buying_carcesses_weight_wage_type.status == True else 0
        free_sell_carcesses_weight_wage_type_amount = free_sell_carcesses_weight_wage_type.amount if free_sell_carcesses_weight_wage_type.status == True else 0

        province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False,
                                                                    archive_wage=False, return_to_province=False,
                                                                    state__in=('pending', 'accepted'),
                                                                    first_car_allocated_quantity=0).order_by('id')
        kill_house_requests = KillHouseRequest.objects.filter(
            Q(Q(killhouse_user__in=kill_houses) & Q(killer__in=kill_houses)) | Q(
                Q(killhouse_user__in=kill_houses) & Q(killer__isnull=True)) | Q(
                Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses)), archive_wage=False,
            trash=False
        )
        kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses,
                                                                              archive_wage=False,
                                                                              trash=False)
        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
            kill_house__in=kill_houses,
            archive_wage=False,
            trash=False)

        slaughter_transactions = InternalTransaction.objects.filter(
            kill_house__in=kill_houses, status='completed',
            trash=False)

        total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[
                              'total'] or 0

        total_province_live_weight = province_kill_requests.aggregate(total=Sum('total_killed_weight'))['total'] or 0
        total_province_live_weight += kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
        total_out_selling_province_carcasses_weight = \
            kill_house_free_sale_bar_info.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0
        total_province_carcasses_weight = total_province_live_weight * 0.75
        total_pure_province_carcasses_weight = total_province_carcasses_weight - total_out_selling_province_carcasses_weight
        total_out_live_buying_province_carcasses_weight = \
            kill_house_free_bar_info.filter(buy_type='live').aggregate(total=Sum('live_weight'))['total'] or 0
        total_out_carcasses_buying_province_carcasses_weight = \
            kill_house_free_bar_info.filter(buy_type='carcass').aggregate(total=Sum('weight_of_carcasses'))[
                'total'] or 0
        total_pure_province_carcasses_price = total_pure_province_carcasses_weight * province_live_wage_type_amount
        total_out_selling_province_carcasses_price = total_out_selling_province_carcasses_weight * free_sell_carcesses_weight_wage_type_amount
        total_out_live_buying_province_carcasses_price = total_out_live_buying_province_carcasses_weight * free_buying_live_weight_wage_type_amount
        total_out_carcasses_buying_province_carcasses_price = total_out_carcasses_buying_province_carcasses_weight * free_buying_carcesses_weight_wage_type_amount
        total_price = total_pure_province_carcasses_price + total_out_selling_province_carcasses_price + total_out_live_buying_province_carcasses_price + total_out_carcasses_buying_province_carcasses_price

        result = {
            "total_province_live_weight": total_province_live_weight,
            "total_province_carcasses_weight": total_province_carcasses_weight,
            "total_out_selling_province_carcasses_weight": total_out_selling_province_carcasses_weight,
            "total_pure_province_carcasses_weight": total_pure_province_carcasses_weight,
            "total_pure_province_carcasses_price": total_pure_province_carcasses_price,
            "total_out_selling_province_carcasses_price": total_out_selling_province_carcasses_price,
            "total_out_carcasses_buying_province_carcasses_weight": total_out_carcasses_buying_province_carcasses_weight,
            "total_out_carcasses_buying_province_carcasses_price": total_out_carcasses_buying_province_carcasses_price,
            "total_out_live_buying_province_carcasses_weight": total_out_live_buying_province_carcasses_weight,
            "total_out_live_buying_province_carcasses_price": total_out_live_buying_province_carcasses_price,
            "total_paid_wage": total_paid_wage,
            "total_price": total_price,
            "province_live_wage_amount": province_live_wage_type_amount,
            "free_buying_live_weight_amount": free_buying_live_weight_wage_type_amount,
            "free_buying_carcesses_weight_amount": free_buying_carcesses_weight_wage_type_amount,
            "free_sell_carcesses_weight_amount": free_sell_carcesses_weight_wage_type_amount,

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


class KillHouseForProvinceWageViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForProvinceWageSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

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

        if request.GET['type'] == 'unpaid':
            if 'date1' in request.GET:
                date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                if request.GET['role'] == 'ProvinceOPerator':
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,
                        union_share__gt=0,
                        trash=False).values(
                        'killhouse_user'), trash=False)
                elif request.GET['role'] == 'Company':
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,
                        company_share__gt=0,
                        trash=False).values(
                        'killhouse_user'), trash=False)
                elif request.GET['role'] == 'Guilds':
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,
                        guilds_share__gt=0,
                        trash=False).values(
                        'killhouse_user'), trash=False)
                else:
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,
                        trash=False).values(
                        'killhouse_user'), trash=False)

            else:

                if request.GET['role'] == 'ProvinceOPerator':
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,
                        union_share__gt=0,
                        trash=False).values(
                        'killhouse_user'), trash=False)
                elif request.GET['role'] == 'Company':
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        company_share__gt=0,
                        archive_wage=False,
                        trash=False).values(
                        'killhouse_user'), trash=False)
                elif request.GET['role'] == 'Guilds':
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(
                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,

                        guilds_share__gt=0,
                        trash=False).values(
                        'killhouse_user'), trash=False)
                else:
                    kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(

                        state__in=(
                            'pending',
                            'accepted'),
                        return_to_province=False,
                        archive_wage=False,
                        trash=False).values(
                        'killhouse_user'), trash=False)

        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 (self.filterset_class(
                                data=query,
                                queryset=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_houses = ps.filter()
                else:
                    kill_houses = kill_houses
        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_houses)
        if page is not None:
            if 'date1' in request.GET:
                serializer = KillHouseForProvinceWageWithDateSerializer(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 = KillHouseForProvinceWageWithDateSerializer(kill_houses, many=True,
                                                                    context={'request': request})
        else:

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


# class KillHouseForProvinceWageViewSet(viewsets.ModelViewSet):
#     queryset = KillHouse.objects.all()
#     serializer_class = KillHouseForProvinceWageSerializer
#     pagination_class = CustomPagination
#     permission_classes = [TokenHasReadWriteScope]
#     filter_backends = [DjangoFilterBackend]
#     filterset_class = KillHouseFilterSet
#     filterset_fields = [
#         'name',
#         'kill_house_operator__user__fullname',
#         'kill_house_operator__user__mobile',
#         'system_address__city__name',
#
#     ]
#
#     def list(self, request, *args, **kwargs):
#
#         if request.GET['type'] == 'unpaid':
#             if 'date1' in request.GET:
#                 date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
#                 date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
#                 kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(wage_pay=False,
#                                                                                                  kill_request__recive_date__date__gte=date1,
#                                                                                                  kill_request__recive_date__date__lte=date2,
#                                                                                                  state__in=(
#                                                                                                      'pending',
#                                                                                                      'accepted'),
#                                                                                                  archive_by_province=False,
#                                                                                                  return_to_province=False,
#                                                                                                  trash=False).values(
#                     'killhouse_user'), trash=False)
#             else:
#
#                 kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(wage_pay=False,
#                                                                                                  state__in=(
#                                                                                                      'pending',
#                                                                                                      'accepted'),
#                                                                                                  archive_by_province=False,
#                                                                                                  return_to_province=False,
#                                                                                                  trash=False).values(
#                     'killhouse_user'), trash=False)
#
#
#         elif request.GET['type'] == 'paid':
#             if 'date1' in request.GET:
#                 date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
#                 date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
#                 kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(wage_pay=True,
#                                                                                                  kill_request__recive_date__date__gte=date1,
#                                                                                                  kill_request__recive_date__date__lte=date2,
#                                                                                                  state__in=(
#                                                                                                      'pending',
#                                                                                                      'accepted'),
#                                                                                                  archive_by_province=False,
#                                                                                                  return_to_province=False,
#                                                                                                  trash=False).values(
#                     'killhouse_user'), trash=False)
#
#             else:
#                 kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(wage_pay=True,
#                                                                                                  state__in=(
#                                                                                                      'pending',
#                                                                                                      'accepted'),
#                                                                                                  archive_by_province=False,
#                                                                                                  return_to_province=False,
#                                                                                                  trash=False).values(
#                     'killhouse_user'), trash=False)
#
#
#         elif request.GET['type'] == 'archive':
#             if 'date1' in request.GET:
#                 date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
#                 date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
#                 kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(wage_pay=False,
#                                                                                                  kill_request__recive_date__date__gte=date1,
#                                                                                                  kill_request__recive_date__date__lte=date2,
#                                                                                                  state__in=(
#                                                                                                      'pending',
#                                                                                                      'accepted'),
#                                                                                                  archive_by_province=True,
#                                                                                                  return_to_province=False,
#                                                                                                  trash=False).values(
#                     'killhouse_user'), trash=False)
#
#             else:
#                 kill_houses = KillHouse.objects.filter(pk__in=ProvinceKillRequest.objects.filter(wage_pay=False,
#                                                                                                  state__in=(
#                                                                                                      'pending',
#                                                                                                      'accepted'),
#                                                                                                  archive_by_province=True,
#                                                                                                  return_to_province=False,
#                                                                                                  trash=False).values(
#                     'killhouse_user'), trash=False)
#
#         else:
#             if 'date1' in request.GET:
#                 date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
#                 date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
#                 kill_houses = KillHouse.objects.filter(
#                     pk__in=ProvinceKillRequest.objects.filter(
#                         kill_request__recive_date__date__gte=date1,
#                         kill_request__recive_date__date__lte=date2,
#                         state__in=('pending', 'accepted'), trash=False).values(
#                         'killhouse_user'), trash=False)
#             else:
#                 kill_houses = KillHouse.objects.filter(
#                     pk__in=ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'), trash=False).values(
#                         'killhouse_user'), trash=False)
#
#         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 (self.filterset_class(
#                                 data=query,
#                                 queryset=kill_houses
#                         )
#                         ).filter():
#                             ps = self.filterset_class(data=query, queryset=kill_houses)
#                             kill_houses = ps.filter()
#                 else:
#                     kill_houses = kill_houses
#         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_houses)
#         if page is not None:
#             if 'date1' in request.GET:
#                 serializer = KillHouseForProvinceWageWithDateSerializer(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 = KillHouseForProvinceWageWithDateSerializer(kill_houses, many=True,
#                                                                     context={'request': request})
#         else:
#
#             serializer = self.get_serializer(kill_houses, many=True, context={'request': request})
#         return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseForTotalProvinceWageTransactionViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForTotalProvinceWageTransactionSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

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

        if 'date1' in request.GET:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if request.GET['role'] == 'ProvinceOperator':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='kill_house',
                    union_share__gt=0,
                    trash=False).values(
                    'kill_house'), trash=False)

            elif request.GET['role'] == 'Company':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='kill_house',
                    company_share__gt=0,
                    trash=False).values(
                    'kill_house'), trash=False)
            elif request.GET['role'] == 'Guilds':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    status='completed',
                    payer_type='kill_house',
                    guilds_share__gt=0,
                    trash=False).values(
                    'kill_house'), trash=False)

            elif request.GET['role'] == 'SuperAdmin':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    payer_type='kill_house',
                    status='completed',
                    trash=False).exclude(union_share=0, company_share=0, guilds_share=0).values(
                    'kill_house'), trash=False)
            else:
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    payer_type='kill_house',
                    status='completed',
                    trash=False).values(
                    'kill_house'), trash=False)
        else:

            if request.GET['role'] == 'ProvinceOperator':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='kill_house',
                    union_share__gt=0,
                    trash=False).values(
                    'kill_house'), trash=False)

            elif request.GET['role'] == 'Company':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='kill_house',
                    company_share__gt=0,
                    trash=False).values(
                    'kill_house'), trash=False)
            elif request.GET['role'] == 'Guilds':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='kill_house',
                    guilds_share__gt=0,
                    trash=False).values(
                    'kill_house'), trash=False)

            elif request.GET['role'] == 'SuperAdmin':
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='kill_house',
                    trash=False).exclude(union_share=0, company_share=0, guilds_share=0).values(
                    'kill_house'), trash=False)
            else:
                kill_houses = KillHouse.objects.filter(pk__in=InternalTransaction.objects.filter(
                    status='completed',
                    payer_type='kill_house',
                    trash=False).values(
                    'kill_house'), trash=False)

        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 (self.filterset_class(
                                data=query,
                                queryset=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_houses = ps.filter()
                else:
                    kill_houses = kill_houses
        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_houses)
        if page is not None:
            if 'date1' in request.GET:
                serializer = KillHouseForTotalProvinceWageTransactionWithDAteSerializer(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 = KillHouseForTotalProvinceWageTransactionWithDAteSerializer(kill_houses, many=True,
                                                                                    context={'request': request})
        else:

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


class KillHouseForFreeBarWageViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForFreeBarWageSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

    def list(self, request, *args, **kwargs):
        type = request.GET['type']

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

                kill_houses = KillHouse.objects.filter(pk__in=KillHouseFreeBarInformation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    buy_type=type,
                    archive_wage=False,
                    trash=False).values(
                    'kill_house'), trash=False)
        else:

            if request.GET['role'] == 'ProvinceOperator':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseFreeBarInformation.objects.filter(
                    buy_type=type,
                    union_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'kill_house'), trash=False)
            elif request.GET['role'] == 'Company':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseFreeBarInformation.objects.filter(
                    buy_type=type,
                    company_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'kill_house'), trash=False)
            elif request.GET['role'] == 'Guilds':
                kill_houses = KillHouse.objects.filter(pk__in=KillHouseFreeBarInformation.objects.filter(
                    buy_type=type,
                    guilds_share__gt=0,
                    archive_wage=False,
                    trash=False).values(
                    'kill_house'), trash=False)
            else:

                kill_houses = KillHouse.objects.filter(pk__in=KillHouseFreeBarInformation.objects.filter(
                    buy_type=type,
                    archive_wage=False,
                    trash=False).values(
                    'kill_house'), trash=False)
        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 (self.filterset_class(
                                data=query,
                                queryset=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_houses = ps.filter()
                else:
                    kill_houses = kill_houses
        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_houses)
        if page is not None:
            if 'date1' in request.GET:
                serializer = KillHouseForFreeBarWageWithDateSerializer(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 = KillHouseForFreeBarWageWithDateSerializer(kill_houses, many=True,
                                                                   context={'request': request})
        else:

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


class KillHouseForFreeSaleBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForFreeSaleBarInformationViewSetSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'date1' in request.GET:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']:
                free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, date__date__gte=date1,
                                                                            date__date__lte=date2)


            else:
                free_sales = KillHouseFreeSaleBarInformation.objects.filter(kill_house__system_address__city=user.city,
                                                                            trash=False, date__date__gte=date1,
                                                                            date__date__lte=date2)



        else:
            if request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']:
                free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False)



            else:
                free_sales = KillHouseFreeSaleBarInformation.objects.filter(kill_house__system_address__city=user.city,
                                                                            trash=False)

        kill_houses = KillHouse.objects.filter(pk__in=free_sales.values_list('kill_house', flat=True)).order_by('id')

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

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


# ویوست مربوط به ثبت کشتارگاه


class KillHouseforPurchaseRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.filter(trash=False, out_province=False).order_by('id')
    serializer_class = KillHouseforPurchaseRequestSerializer
    permission_classes = [TokenHasReadWriteScope]


class KillHousePurchaseRequestPermissionViewSet(viewsets.ModelViewSet):
    queryset = KillHousePurchaseRequest.objects.all()
    serializer_class = KillHousePurchaseRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        total_unpaid_wage = 0
        total_paid_wage = 0
        permission = True
        exclusive = False
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_role = Group.objects.get(name='KillHouse')
        if kill_house_role in user.role.all():
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            exclusive = True if kill_house.type == 'exclusive' else False
            purchase = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()
            if purchase:
                if purchase.total_limitation == True:
                    permission = False
                else:
                    permission = True
            else:
                permission = True

        return Response({
            "permission": permission,
            "exclusive": exclusive
        }, status=status.HTTP_200_OK)


class KillHousePurchaseRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHousePurchaseRequest.objects.all()
    serializer_class = KillHousePurchaseRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def update(self, request, pk=None, *args, **kwargs):
        kill_house = KillHouse.objects.get(key=request.data['kill_house_key'], trash=False)
        request.data.pop('kill_house_key')
        serializer = self.serializer_class(data=request.data)
        purchace = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()
        if purchace:
            serializer.update(instance=purchace, validated_data=request.data)
        else:
            if serializer.is_valid():
                purchace = serializer.create(validated_data=request.data)
                purchace.kill_house = kill_house
                purchace.save()

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


class TotalReportOfKillHouseWareHouseForDailyBroadCastInDetailsViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseWareHouseForDailyBroadCastOInDetailsSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        kill_house_ware_houses = KillHouseWareHouse.objects.filter(
            Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
                pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=date1,
            date__date__lte=date2, trash=False)
        kill_houses = KillHouse.objects.filter(
            pk__in=kill_house_ware_houses.values('kill_house')
        )

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


class TotalReportOfKillHouseWareHouseForDailyBroadCastViewSet(viewsets.ModelViewSet):
    queryset = KillHouseWareHouse.objects.all()
    serializer_class = KillHouseWareHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        kill_house_ware_houses = KillHouseWareHouse.objects.filter(
            Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
                pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=date1,
            date__date__lte=date2, trash=False)
        number_of_kill_houses = KillHouse.objects.filter(
            pk__in=kill_house_ware_houses.values('kill_house')
        )

        steward_allocations = StewardAllocation.objects.filter(
            Q(type='manual') | Q(type='auto', system_registration_code=True),
            ware_house__in=kill_house_ware_houses, receiver_state__in=('pending', 'accepted'), trash=False).order_by(
            'id')

        guild_allocations = steward_allocations.filter(guilds__isnull=False, trash=False)
        number_of_guild = guild_allocations.values('guilds').distinct().count() if guild_allocations else 0

        steward_allocations_for_number_of_steward = steward_allocations.filter(steward__isnull=False, trash=False)
        number_of_steward = steward_allocations_for_number_of_steward.values(
            'steward').distinct().count() if steward_allocations_for_number_of_steward else 0

        total_pre_cold_quantity = \
            kill_house_ware_houses.aggregate(total=Sum('pre_cold_number_of_carcasses_to_ware_house'))[
                'total']
        total_pre_cold_weight = \
            kill_house_ware_houses.aggregate(total=Sum('pre_cold_weight_of_carcasses_to_ware_house'))[
                'total']
        total_number_of_free_carcasses = kill_house_ware_houses.aggregate(total=Sum('number_of_free_carcasses'))[
            'total']
        total_free_weight_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('free_weight_of_carcasses'))[
            'total']
        total_number_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('number_of_carcasses'))[
            'total']
        total_weight_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('weight_of_carcasses'))[
            'total']

        final_total_number_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
                'total']
        final_total_weight_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
                'total']

        total_remain_quantity = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                'total']

        total_remain_weight = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                'total']

        total_allocated_quantity = \
            steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[
                'total']

        total_allocated_weight = \
            steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total']

        total_accepted_allocated_quantity = \
            steward_allocations.aggregate(total=Sum('receiver_real_number_of_carcasses'))[
                'total']

        total_accepted_allocated_weight = \
            steward_allocations.aggregate(total=Sum('receiver_real_weight_of_carcasses'))[
                'total']

        return Response({
            "buyers": len(number_of_kill_houses),
            "incoming_quantity_of_cold_house": 0,
            "incoming_weight_of_cold_house": 0,
            "total_pre_cold_quantity": total_pre_cold_quantity if total_pre_cold_quantity != None else 0,
            "total_pre_cold_weight": total_pre_cold_weight if total_pre_cold_weight != None else 0,
            "total_number_of_free_carcasses": total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
            "total_free_weight_of_carcasses": total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
            "total_number_of_carcasses": total_number_of_carcasses if total_number_of_carcasses != None else 0,
            "total_weight_of_carcasses": total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
            "final_total_number_of_carcasses": final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
            "final_total_weight_of_carcasses": final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
            "total_allocated_quantity": total_allocated_quantity if total_allocated_quantity != None else 0,
            "total_allocated_weight": total_allocated_weight if total_allocated_weight != None else 0,
            "total_accepted_allocated_quantity": total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
            "total_accepted_allocated_weight": total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
            "total_remain_quantity": total_remain_quantity if total_remain_quantity != None else 0,
            "total_remain_weight": total_remain_weight if total_remain_weight != None else 0,
            "number_of_guild": number_of_guild,
            "number_of_steward": number_of_steward,

        })


class TotalReportForDailyBroadCastViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForTotalReportAutomaticStewardAllocationSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date = datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date()
        date_one_day_ago = date - timedelta(days=1)
        province_kill_requests = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                                    kill_request__recive_date__date=date_one_day_ago).select_related(
            'killhouse_user')
        kill_houses = KillHouse.objects.filter(
            pk__in=province_kill_requests.values('killhouse_user')
        )
        kill_house_ware_houses = KillHouseWareHouse.objects.filter(kill_house__in=kill_houses, date__date=date)
        steward_allocations = StewardAllocation.objects.filter(
            Q(type='manual') | Q(type='auto', system_registration_code=True),
            ware_house__in=kill_house_ware_houses, trash=False,
            date__date=date).order_by('id')

        total_number_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
            'total']
        total_weight_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
            'total']
        allocated_total_number_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('allocated_total_number_of_carcasses'))['total']
        allocated_total_weight_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('allocated_total_weight_of_carcasses'))['total']
        remain_total_number_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))['total']
        remain_total_weight_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))['total']

        return Response({
            "buyers": len(kill_house_ware_houses),
            "allocations": len(steward_allocations),
            "total_number_of_carcasses": total_number_of_carcasses if total_number_of_carcasses != None else 0,
            "total_weight_of_carcasses": total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
            "allocated_total_number_of_carcasses": allocated_total_number_of_carcasses if allocated_total_number_of_carcasses != None else 0,
            "allocated_total_weight_of_carcasses": allocated_total_weight_of_carcasses if allocated_total_weight_of_carcasses != None else 0,
            "remain_total_number_of_carcasses": remain_total_number_of_carcasses if remain_total_number_of_carcasses != None else 0,
            "remain_total_weight_of_carcasses": remain_total_weight_of_carcasses if remain_total_weight_of_carcasses != None else 0,
        })


class KillHouseForTotalReportAutomaticStewardAllocationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForTotalReportAutomaticStewardAllocationSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date = datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date()
        kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'])
        serializer = self.serializer_class(kill_house, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseForAutomaticStewardAllocationViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForAutomaticStewardAllocationSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date = datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date()
        date = date - timedelta(days=1)
        if request.GET['role'] == 'KillHouse':
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user)
            serializer = self.serializer_class(kill_house, many=True, context={'request': request})
        else:
            province_kill_requests = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                                        kill_request__recive_date__date=date).select_related(
                'killhouse_user')
            kill_houses = KillHouse.objects.filter(
                pk__in=province_kill_requests.values('killhouse_user')
            )

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


class KillHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به ثبت کشتارگاه
    def create(self, request, *args, **kwargs):
        group = Group.objects.get(name__exact="KillHouse")
        city = City.objects.get(name=request.data['city'])
        request.data.pop('city')
        province = Province.objects.get(key=city.province.key)
        system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
        if system_profile:
            if KillHouse.objects.filter(kill_house_operator__user=system_profile, trash=False).exists():
                return Response({"result": "این کشتارگاه قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)

        else:
            password = request.data['password']
            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)
        address = SystemAddress(city=city, province=province, address=request.data['address'])
        address.save()
        wallet = Wallet()
        wallet.save()
        system_profile.role.add(group)
        operator = KillHouseOperator.objects.filter(user=system_profile, trash=False).last()
        if operator:
            pass
        else:
            operator = KillHouseOperator(
                user=system_profile,
                address=address,
                wallet=wallet,
            )
            operator.save()
        request.data.pop('mobile')
        request.data.pop('first_name')
        request.data.pop('last_name')
        request.data.pop('address')
        request.data.pop('national_id')
        request.data.pop('password')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house = serializer.create(validated_data=request.data)
            kill_house.kill_house_operator = operator
            kill_house.system_address = address
            kill_house.save()
            percentage = KillHousePercentage(kill_house=kill_house)
            percentage.save()
            province_allow_kill_house_choose_steward_guilds = ProvinceAllowKillHouseChooseStewardGuilds(
                kill_house=kill_house)
            province_allow_kill_house_choose_steward_guilds.save()
            province_allow_direct_buying = ProvinceAllowKillHouseDirectBuying(kill_house=kill_house)
            province_allow_direct_buying.save()
            return Response({"result": "با موفقیت ثبت شد."}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    # تابع برای نمایش مربوط به نمایش کشتارگاه
    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'role' in request.GET:
            # if 'kill_house' in request.GET:
            #     kill_house = KillHouse.objects.filter(system_address__province=user.province, killer=False, trash=False)
            #
            # else:
            if request.GET['role'] == 'KillHouse':
                kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
                kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator,
                                                      trash=False)

            # if request.GET['role'] == 'ProvinceInspector' or request.GET['role'] == 'ProvinceOperator':
            else:
                kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False)
            serializer = KillHouseSerializer(kill_house, many=True)
        elif 'kill_house' in request.GET:
            kill_house = KillHouse.objects.filter(system_address__province=user.province,
                                                  kill_house_operator__killer=False, killer=False, trash=False)
            serializer = KillHouseSerializer(kill_house, many=True)

        elif 'all' in request.GET:
            kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False)
            serializer = KillHouseSerializer(kill_house, many=True)

        elif 'psp' in request.GET:
            kill_house = KillHouse.objects.filter(out_province=False, trash=False)
            serializer = PspKillHouseSerializer(kill_house, many=True)

        elif 'self_kill_houses' in request.GET:
            kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator,
                                                  trash=False)
            serializer = KillHouseSerializer(kill_house, many=True)
        elif 'exclusive-killers' in request.GET:
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            percentage = KillHousePercentage.objects.filter(
                Q(kill_house=kill_house) | Q(kill_house_for_killer=kill_house, kill_house__type='exclusive',
                                             kill_house__show_exclusive=True),
                trash=False).values_list('kill_house__id', flat=True).distinct()
            kill_houses = KillHouse.objects.filter(id__in=percentage, trash=False)

            serializer = KillHouseSerializer(kill_houses, many=True)

        elif 'total-exclude-exclusive-killers' in request.GET:
            percentage = KillHousePercentage.objects.filter(kill_house_for_killer__isnull=False,
                                                            kill_house__type='exclusive',
                                                            kill_house__show_exclusive=True, trash=False).values_list(
                'kill_house__id', flat=True).distinct()
            kill_houses = KillHouse.objects.filter(trash=False).exclude(id__in=percentage).order_by('id', 'killer')

            serializer = distributionKillHouseSerializer(kill_houses, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        elif 'exclusive-killers-free-bar' in request.GET:
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()

            percentage = KillHousePercentage.objects.filter(kill_house_for_killer=kill_house,
                                                            kill_house__type='exclusive',
                                                            kill_house__show_exclusive=True, trash=False).values_list(
                'kill_house__id', flat=True)

            kill_houses = KillHouse.objects.filter(Q(id__in=percentage) | Q(killer=True, type='public'), trash=False)

            serializer = KillHouseSerializer(kill_houses, many=True)

        elif 'dispenser' in request.GET:
            kill_house = KillHouse.objects.filter(system_address__province=user.province,
                                                  out_province=False, trash=False).order_by('id')
            serializer = GeneralKillHouseSerializer(kill_house, many=True)

        elif 'gate-way-kill-houses' in request.GET:
            kill_house = KillHouse.objects.filter(system_address__province=user.province,
                                                  out_province=False, trash=False)
            serializer = GeneralKillHouseSerializer(kill_house, many=True)


        else:
            try:
                kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
                kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False).first()
                serializer = KillHouseSerializer(kill_house)
            except:
                kill_house = KillHouse.objects.filter(out_province=False, type='public', trash=False)
                serializer = KillHouseSerializer(kill_house, many=True)

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

    # تابع برای ویرایش درخواست کشتار ثبت شده از سمت کشتارگاه
    def update(self, request, *args, pk=None, **kwargs):
        # refresh(request.user.id)

        kill_house = KillHouse.objects.filter(
            key=request.data['kill_house_key'], trash=False
        ).select_related('kill_house_operator__user').last()
        system_user_profile = SystemUserProfile.objects.get(key=kill_house.kill_house_operator.user.key)

        if 'company_gateway_percent' in request.data.keys():
            kill_house.company_gateway_percent = request.data['company_gateway_percent']
            kill_house.union_gateway_percent = request.data['union_gateway_percent']
            kill_house.guilds_gateway_percent = request.data['guilds_gateway_percent']
            kill_house.other_gateway_percent = request.data['other_gateway_percent']
            kill_house.save()
        elif 'quota' in request.data.keys():
            kill_house.quota = request.data['quota']
            kill_house.governmental_quota = request.data['governmental_quota']
            kill_house.quota_max_kill_limit = request.data['quota_max_kill_limit']
            kill_house.quota_request = request.data['quota_request']
            kill_house.quota_custom = request.data['quota_custom']
            kill_house.quota_custom_quantity = request.data['quota_custom_quantity']
            kill_house.save()
        elif 'maximum_load_volume_increase' in request.data.keys():
            kill_house.maximum_load_volume_increase = request.data['maximum_load_volume_increase']
            kill_house.maximum_load_volume_reduction = request.data['maximum_load_volume_reduction']
            kill_house.save()

        elif 'ware_house_remaining_weight_limitation_status' in request.data.keys():
            kill_house.ware_house_remaining_weight_limitation_status = request.data[
                'ware_house_remaining_weight_limitation_status']
            kill_house.ware_house_remaining_weight_limitation = request.data['ware_house_remaining_weight_limitation']
            kill_house.ware_house_remaining_percent_limitation_status = request.data[
                'ware_house_remaining_percent_limitation_status']
            kill_house.ware_house_remaining_percent_limitation = request.data['ware_house_remaining_percent_limitation']
            kill_house.save()


        elif 'total_kill_capacity' in request.data.keys():
            kill_house.max_kill_limit = request.data['max_kill_limit']
            kill_house.total_kill_capacity = request.data['total_kill_capacity']
            kill_house.extra_bar_kill_percent = request.data['extra_bar_kill_percent']
            kill_house.save()
        elif 'name' in request.data.keys():
            kill_house.name = request.data['name']
            kill_house.save()
        elif 'active' in request.data.keys():
            kill_house.active = request.data['active']
            kill_house.save()
        elif 'type' in request.data.keys():
            kill_house.type = request.data['type']
            kill_house.save()

        elif 'out_province_selling_limitation' in request.data.keys():
            kill_house.out_province_selling_limitation = request.data['out_province_selling_limitation']
            kill_house.out_province_selling_limitation_percent = request.data['out_province_selling_limitation_percent']
            kill_house.save()
        elif 'in_province_selling_limitation' in request.data.keys():
            kill_house.in_province_selling_limitation = request.data['in_province_selling_limitation']
            kill_house.in_province_selling_limitation_percent = request.data['in_province_selling_limitation_percent']
            kill_house.save()
        elif 'governmental_selling_permission' in request.data.keys():
            kill_house.governmental_selling_permission = request.data['governmental_selling_permission']
            kill_house.in_province_governmental_selling_percent = request.data[
                'in_province_governmental_selling_percent']
            kill_house.out_province_governmental_selling_percent = request.data[
                'out_province_governmental_selling_percent']
            kill_house.segmentation_governmental_percent = request.data['segmentation_governmental_percent']

            kill_house.save()

        elif 'free_selling_permission' in request.data.keys():
            kill_house.free_selling_permission = request.data['free_selling_permission']
            kill_house.in_province_free_selling_percent = request.data['in_province_free_selling_percent']
            kill_house.out_province_free_selling_percent = request.data['out_province_free_selling_percent']
            kill_house.segmentation_free_selling_percent = request.data['segmentation_free_selling_percent']

            kill_house.save()

        elif 'ware_house_remaining_weight_archive_percent':
            kill_house.ware_house_remaining_weight_archive_percent = request.data[
                'ware_house_remaining_weight_archive_percent']
            kill_house.save()

        else:
            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.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()
        return Response({"result": "باموفقیت ویرایش شد"}, status=status.HTTP_200_OK)

    # ویوست مربوط به ثبت کشتارگاه


class PosKillHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = PosKillHouseSerializer
    permission_classes = [AllowAny]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__mobile',
        'system_address__city__name',

    ]

    def list(self, request, *args, **kwargs):
        pos = POSMachine.objects.get(pos_id=request.GET['pos-id'], trash=False)
        if pos.kill_house:
            kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id').exclude(
                id=pos.kill_house.id)

        else:
            kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id')

        if 'search' in request.GET:
            if request.GET['search'] == 'filter':
                kill_houses_list = []
                if request.GET['value'] != "":
                    for item in self.filterset_fields:
                        query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                        if (self.filterset_class(
                                data=query,
                                queryset=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_houses_list = ps.filter()
                    kill_houses = [] if len(kill_houses_list) == 0 else kill_houses_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(kill_houses)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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


class KillHouseAllowVetViewSet(viewsets.ModelViewSet):
    queryset = KillHouseAllowVet.objects.all()
    serializer_class = KillHouseAllowVetSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به ثبت کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_operator = KillHouseOperator.objects.get(user=user)
        kill_houses = KillHouse.objects.filter(kill_house_operator=kill_house_operator)
        kill_house_allow_vets = KillHouseAllowVet.objects.filter(kill_house__in=kill_houses)
        allow = request.data['allow']
        if kill_house_allow_vets.count() > 0:
            for kill_house_allow_vet in kill_house_allow_vets:
                kill_house_allow_vet.allow = allow
                kill_house_allow_vet.save()
        else:
            for kill_house in kill_houses:
                serializer = self.serializer_class(data=request.data)
                if serializer.is_valid():
                    allow = serializer.create(validated_data=request.data)
                    allow.kill_house = kill_house
                    allow.save()
        return Response({"result": "created"}, status=status.HTTP_201_CREATED)

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

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_operator = KillHouseOperator.objects.get(user=user)
        kill_houses = KillHouse.objects.filter(kill_house_operator=kill_house_operator)
        kill_house_allow_vet = KillHouseAllowVet.objects.filter(kill_house__in=kill_houses)
        serializer = KillHouseAllowVetSerializer(kill_house_allow_vet, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHousePercentageViewSet(viewsets.ModelViewSet):
    queryset = KillHousePercentage.objects.all()
    serializer_class = KillHousePercentageSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        percents = []
        user_profile = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.filter(system_address__province=user_profile.province, trash=False)
        if kill_house:
            percents = KillHousePercentage.objects.filter(kill_house__in=kill_house).order_by('-percent')

        serializer = KillHousePercentageSerializer(percents, 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)
        if 'percentage_list' in request.data.keys():
            kill_house_percentage_lists = request.data['percentage_list']
            request.data.pop('percentage_list')
            if request.data['type'] == 'manual':
                for kill_house_percentage_list in kill_house_percentage_lists:
                    kill_house_percentage = KillHousePercentage.objects.get(key=kill_house_percentage_list["key"],
                                                                            trash=False)
                    kill_house_percentage.percent = kill_house_percentage_list["percent"]
                    if 'killer_kill_house_key' in kill_house_percentage_list.keys():
                        if kill_house_percentage_list['killer_kill_house_key'] != None:
                            kill_house_percentage.kill_house_for_killer = KillHouse.objects.get(
                                key=kill_house_percentage_list['killer_kill_house_key'], trash=False)
                    kill_house_percentage.save()
            else:

                guilds = Guilds.objects.filter(kill_house_centers_allocation__isnull=False, trash=False)
                total_count = len(guilds)
                total_weight = guilds.aggregate(total_quantity=Sum('allocation_limit')).get('total_quantity', 0)

                if total_count == 0:
                    return Response({"result": "صنفی وجود ندارد برای کشتارگاه ها و کشتارکن ها"},
                                    status=status.HTTP_403_FORBIDDEN)
                if request.data['type'] == 'guilds_weight':

                    for kill_house_percentage_list in kill_house_percentage_lists:
                        kill_house_percentage = KillHousePercentage.objects.get(key=kill_house_percentage_list["key"],
                                                                                trash=False)
                        kill_house_percentage_weight = 0
                        for guild in guilds:
                            if len(guild.kill_house_centers_allocation) == 0 or guild.kill_house_centers_allocation == None:
                                continue
                            if guild.kill_house_centers_allocation[0]['value'] == str(
                                    kill_house_percentage.kill_house.key):
                                kill_house_percentage_weight += guild.allocation_limit
                        kill_house_percentage.percent = round((kill_house_percentage_weight / total_weight) * 100, 2)
                        kill_house_percentage.guilds_weight = kill_house_percentage_weight
                        kill_house_percentage.last_guilds_update_date = str(datetime.now())
                        kill_house_percentage.save()


                else:

                    for kill_house_percentage_list in kill_house_percentage_lists:
                        kill_house_percentage = KillHousePercentage.objects.get(key=kill_house_percentage_list["key"],
                                                                                trash=False)
                        kill_house_percentage_counter = 0
                        for guild in guilds:
                            if len(guild.kill_house_centers_allocation) == 0 or guild.kill_house_centers_allocation == None:
                                continue
                            if guild.kill_house_centers_allocation[0]['value'] == str(
                                    kill_house_percentage.kill_house.key):
                                kill_house_percentage_counter += 1
                        kill_house_percentage.percent = round((kill_house_percentage_counter / total_count) * 100, 2)
                        kill_house_percentage.guilds_quantity = kill_house_percentage_counter
                        kill_house_percentage.last_guilds_update_date = str(datetime.now())
                        kill_house_percentage.save()

        elif 'percentage_key' in request.data.keys():
            percentage = KillHousePercentage.objects.get(key=request.data['percentage_key'])
            if 'identity' in request.data.keys():
                kill_house = KillHouse.objects.get(key=percentage.kill_house.key)
                if kill_house.killer == False:
                    if request.data['identity'] == 'Killer':
                        previous_state = kill_house.killer
                        if KillHousePercentage.objects.filter(
                                kill_house_for_killer=kill_house).exists():
                            return Response({
                                "result": "این کشتارگاه توسط چندین کشتارکن رزرو شده است و امکان تغییر ماهیت وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
                        if KillRequest.objects.filter(remain_quantity__gt=0, slaughter_house=kill_house,
                                                      trash=False).exists():
                            return Response({
                                "result": "این کشتارگاه توسط چندین کشتارکن در قسمت اعلام نیاز کشتارگاه رزرو شده است و امکان تغییر ماهیت وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)

                        kill_house.killer = True
                        kill_house.save()
                        new_state = kill_house.killer
                        percentage.change_data = {
                            "previous_killer_state": previous_state,
                            "new_killer_state": new_state,
                            "type": kill_house.type,
                            "fullname": user.fullname,
                            "mobile": user.mobile,
                            "date": str(datetime.now()),
                            "kill_house": percentage.kill_house_for_killer.name if percentage.kill_house_for_killer != None else None,

                        }
                        percentage.save()


                else:
                    if request.data['identity'] == 'KillHouse':
                        previous_state = kill_house.killer
                        kill_house.killer = False
                        kill_house.save()
                        new_state = kill_house.killer
                        percentage.kill_house_for_killer = None
                        percentage.change_data = {
                            "previous_killer_state": previous_state,
                            "new_killer_state": new_state,
                            "type": kill_house.type,
                            "fullname": user.fullname,
                            "mobile": user.mobile,
                            "date": str(datetime.now()),
                            "kill_house": percentage.kill_house_for_killer.name if percentage.kill_house_for_killer != None else None,

                        }
                        percentage.save()


            else:
                kill_house = KillHouse.objects.get(key=request.data['kill_house_key'])
                percentage.kill_house_for_killer = kill_house
                if percentage.change_data:
                    percentage.change_data["kill_house"] = kill_house.name
                    percentage.change_data["date"] = str(datetime.now())
                percentage.save()
        return Response({"result": "با موفقیت ویرایش شد."}, status=status.HTTP_200_OK)


# ویوست مربوط به اضافه کردن خودرو به کشتارگاه
class KillHouseDriverViewSet(viewsets.ModelViewSet):
    queryset = KillHouseDriver.objects.all()
    serializer_class = KillHouseDriverSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseDriverFilterSet
    filterset_fields = [
        'health_code',
        'user__mobile',
        'user__national_id',
        'user__base_order',
    ]

    # تابع مربوط به اضافه کردن خودرو به کشتارگاه
    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.data['role']
        request.data.pop('role')

        # refresh(request.user.id)
        kill_house = None
        if 'kill_house_key' in request.data.keys():
            if request.data['kill_house_key'] != None:
                kill_house = KillHouse.objects.get(key=request.data['kill_house_key'])
            request.data.pop('kill_house_key')
        if role == 'KillHouse':
            kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
            # if not ProvinceAllowKillHouseRegisterCar.objects.filter(
            #         kill_house__in=kill_house, allow=True).exists():
            #     return Response({"result": "شما اجازه ساخت ماشین ندارید"}, status=status.HTTP_403_FORBIDDEN)
        person = SystemUserProfile.objects.get(user=request.user)
        group = Group.objects.get(name__exact="Driver")
        city = City.objects.get(name=request.data['city_name'])
        province = Province.objects.get(key=user.province.key)
        request.data.pop('city_name')
        # request.data.pop('province_name')
        if KillHouseDriver.objects.filter(pelak=request.data['pelak'], trash=False).exists():
            return Response({"result": "این ماشین قبلا ثبت شده!"}, status=status.HTTP_403_FORBIDDEN)
        system_profile = SystemUserProfile.objects.filter(mobile=request.data['driver_mobile'], trash=False)
        if system_profile.count() > 0:
            system_profile = system_profile.last()
            if group not in system_profile.role.all():
                system_profile.role.add(group)

        else:

            password = "00100"
            data = {
                "username": request.data['driver_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['driver_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['driver_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,
                    city=city,
                    province=province
                )
                system_profile.save()
                system_profile.role.add(group)


            else:
                return Response({"result": "در ثبت کاربر مشکلی پیش آمده است!"}, status=status.HTTP_403_FORBIDDEN)

        wallet = Wallet()
        wallet.save()
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            full_name = request.data['first_name'] + " " + request.data['last_name']
            request.data.pop('first_name')
            request.data.pop('last_name')
            kill_house_driver = serializer.create(validated_data=request.data)
            kill_house_driver.user = system_profile
            kill_house_driver.wallet = wallet
            kill_house_driver.registrar = {
                "role": role,
                "full_name": person.fullname,
                "mobile": person.mobile,
                "date": str(kill_house_driver.create_date)
            }
            kill_house_driver.driver_name = full_name
            kill_house_driver.save()
            if kill_house != None:
                if KillHouseADDCAR.objects.filter(kill_house__in=kill_house, driver=kill_house_driver,
                                                  trash=False).exists():
                    return Response({"result": "این ماشین قبلا برای کشتارگاه ثبت شده!"},
                                    status=status.HTTP_403_FORBIDDEN)
                else:
                    add_car = KillHouseADDCAR(
                        kill_house=kill_house.last(),
                        driver=kill_house_driver
                    )
                    add_car.save()
            else:
                if kill_house_driver.type == 'rental':
                    # kill_houses = KillHouse.objects.filter(trash=False)
                    # for kill_house in kill_houses:
                    add_car = KillHouseADDCAR(
                        # kill_house=kill_house,
                        driver=kill_house_driver
                    )
                    add_car.save()

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

    def list(self, request, *args, **kwargs):
        if 'role' in request.GET:
            # refresh(request.user.id)
            user = SystemUserProfile.objects.get(user=request.user)
            list_car = []
            if 'health_code' in request.GET:

                for item in self.filterset_fields:
                    query = QueryDict('{0}={1}'.format(item, request.GET['health_code']))
                    if (self.filterset_class(
                            data=query,
                            queryset=self.queryset.filter(trash=False)
                    )
                    ).filter():
                        ps = self.filterset_class(data=query, queryset=self.queryset)
                        filtered_kill_house_driver = ps.filter()
                        serializer = self.serializer_class(filtered_kill_house_driver, many=True)
                        return Response(serializer.data)
                return Response(list_car)


            # cars = KillHouseDriver.objects.filter(health_code=request.GET['health_code'],
            #                                       trash=False)
            # if cars.count() > 0:
            #     cars = cars.last()
            #     dict1 = {
            #         "id": cars.id,
            #         "key": cars.key,
            #         "driver_name": cars.driver_name,
            #         "driver_mobile": cars.driver_mobile,
            #         "type_car": cars.type_car,
            #         "pelak": cars.pelak,
            #         "capocity": float(cars.capocity),
            #         "weight_without_load": cars.weight_without_load,
            #         "health_code": cars.health_code,
            #     }
            #     list_car.append(dict1)
            # return Response(list_car, status=status.HTTP_200_OK)
            else:
                if request.GET['role'] == 'KillHouse':
                    kill_house_drivers = KillHouseDriver.objects.filter(user__province=user.province, type='rental',
                                                                        archive=False)
                    kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
                    kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False).first()
                    add_car = KillHouseADDCAR.objects.filter(kill_house=kill_house, trash=False,
                                                             archive=False).order_by('id')
                    if add_car.count() > 0:
                        kill_house_list = []
                        for add_car_obj in add_car:
                            allow = ProvinceAllowKillHouseRegisterCar.objects.filter(
                                kill_house=add_car_obj.kill_house)
                            if allow.count() > 0:
                                allow_state = allow.last().allow
                            else:
                                allow_state = None
                            kill_house_name = add_car_obj.kill_house.name
                            kill_house_key = add_car_obj.kill_house.key
                            kill_house_dict = {"kill_house_name": kill_house_name, "kill_house_key": kill_house_key,
                                               "allow_state": allow_state}
                            if not any(d["kill_house_name"] == kill_house_name for d in kill_house_list):
                                kill_house_list.append(kill_house_dict)

                            dict1 = {
                                "id": add_car_obj.driver.id,
                                "key": add_car_obj.driver.key,
                                "add_car_key": add_car_obj.key,
                                "driver_name": add_car_obj.driver.driver_name,
                                "driver_type": add_car_obj.driver.type,
                                "driver_active_state": add_car_obj.driver.active_state,
                                "add_car_active_state": add_car_obj.active_state,
                                "first_name": add_car_obj.driver.user.first_name,
                                "last_name": add_car_obj.driver.user.last_name,
                                "city": add_car_obj.driver.user.city.name,
                                "driver_mobile": add_car_obj.driver.driver_mobile,
                                "kill_house_list": kill_house_list,
                                "type_car": add_car_obj.driver.type_car,
                                "type": add_car_obj.driver.type,
                                "pelak": add_car_obj.driver.pelak,
                                "capocity": float(add_car_obj.driver.capocity),
                                "weight_without_load": add_car_obj.driver.weight_without_load,
                                "health_code": add_car_obj.driver.health_code,
                            }
                            list_car.append(dict1)
                        if kill_house_drivers:
                            for kill_house_driver in kill_house_drivers:
                                dict2 = {
                                    "id": kill_house_driver.id,
                                    "key": kill_house_driver.key,
                                    "add_car_key": None,
                                    "add_car_active_state": kill_house_driver.active_state,
                                    "driver_name": kill_house_driver.driver_name,
                                    "driver_type": kill_house_driver.type,
                                    "driver_active_state": kill_house_driver.active_state,
                                    "first_name": kill_house_driver.user.first_name,
                                    "last_name": kill_house_driver.user.last_name,
                                    "city": kill_house_driver.user.city.name,
                                    "driver_mobile": kill_house_driver.driver_mobile,
                                    "kill_house_list": [],
                                    "type_car": kill_house_driver.type_car,
                                    "type": kill_house_driver.type,
                                    "pelak": kill_house_driver.pelak,
                                    "capocity": float(kill_house_driver.capocity),
                                    "weight_without_load": kill_house_driver.weight_without_load,
                                    "health_code": kill_house_driver.health_code,
                                }
                                list_car.append(dict2)

                    return Response(list_car, status=status.HTTP_200_OK)
                else:
                    list_car = []
                    cars = KillHouseDriver.objects.filter(user__province=user.province, trash=False,
                                                          archive=False).order_by('id') \
                        .select_related('user')

                    if cars.count() > 0:
                        for car in cars:
                            add_car = KillHouseADDCAR.objects.filter(driver=car, trash=False,
                                                                     archive=False).select_related(
                                'kill_house')
                            if add_car.count() > 0:
                                kill_house_list = []
                                for add_car_obj in add_car:
                                    if add_car_obj.kill_house != None:
                                        allow = ProvinceAllowKillHouseRegisterCar.objects.filter(
                                            kill_house=add_car_obj.kill_house)
                                        if allow.count() > 0:
                                            allow_state = allow.last().allow
                                        else:
                                            allow_state = None
                                        kill_house_name = add_car_obj.kill_house.name
                                        kill_house_key = add_car_obj.kill_house.key
                                        kill_house_dict = {"kill_house_name": kill_house_name,
                                                           "kill_house_key": kill_house_key, "allow_state": allow_state}
                                        if not any(d["kill_house_name"] == kill_house_name for d in kill_house_list):
                                            kill_house_list.append(kill_house_dict)

                                    dict1 = {
                                        "id": car.id,
                                        "key": car.key,
                                        "add_car_key": None,
                                        "driver_name": car.driver_name,
                                        "driver_type": car.type,
                                        "driver_active_state": car.active_state,
                                        "type": car.type,
                                        "first_name": car.user.first_name,
                                        "last_name": car.user.last_name,
                                        "city": car.user.city.name,
                                        "driver_mobile": car.driver_mobile,
                                        "kill_house_list": kill_house_list,
                                        "type_car": car.type_car,
                                        "pelak": car.pelak,
                                        "capocity": float(car.capocity),
                                        "weight_without_load": car.weight_without_load,
                                        "health_code": car.health_code,
                                    }
                                    list_car.append(dict1)
                            else:
                                dict1 = {
                                    "id": car.id,
                                    "type": car.type,
                                    "add_car_key": None,
                                    "key": car.key,
                                    "driver_type": car.type,
                                    "driver_name": car.driver_name,
                                    "driver_active_state": car.active_state,
                                    "first_name": car.user.first_name,
                                    "last_name": car.user.last_name,
                                    "city": car.user.city.name,
                                    "driver_mobile": car.driver_mobile,
                                    "kill_house_list": [],
                                    "type_car": car.type_car,
                                    "pelak": car.pelak,
                                    "capocity": float(car.capocity),
                                    "weight_without_load": car.weight_without_load,
                                    "health_code": car.health_code,
                                }
                                list_car.append(dict1)

                        return Response(list_car, status=status.HTTP_200_OK)
                    else:
                        return Response(list_car, status=status.HTTP_200_OK)

        else:
            return Response([], status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        if 'change_activation' in request.data.keys():
            car = KillHouseDriver.objects.get(key=request.data["driver_key"])

            add_cars = KillHouseADDCAR.objects.filter(driver=car, trash=False)
            for add_car in add_cars:
                add_car.active_state = request.data['change_activation']
                add_car.save()
            car.active_state = request.data['change_activation']
            car.save()
            return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)
        elif 'add_car_change_activation' in request.data.keys():
            add_car = KillHouseADDCAR.objects.get(key=request.data["add_car_key"], trash=False)
            add_car.active_state = request.data['add_car_change_activation']
            add_car.save()
            return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)



        else:
            car = KillHouseDriver.objects.get(key=request.data["driver_key"])

            if 'city_name' in request.data.keys() and request.data['city_name'] != None:
                city = City.objects.get(name=request.data['city_name'])
            else:
                city = None
            request.data.pop('city_name')

            user = SystemUserProfile.objects.get(key=car.user.key)
            request.data.pop('driver_key')
            first_name = request.data['first_name']
            last_name = request.data['last_name']
            request.data.pop('first_name')
            request.data.pop('last_name')
            if first_name != None:
                user.first_name = first_name
            if last_name != None:
                user.last_name = last_name
            if city != None:
                user.city = city
            if first_name != None and last_name != None:
                car.driver_name = first_name + "" + last_name
                user.fullname = first_name + "" + last_name
            # serializer = self.serializer_class(car)
            user.save()
            car.save()
            serializer = self.serializer_class(car)
            serializer.update(instance=car, validated_data=request.data)
            return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        car = KillHouseDriver.objects.get(key=request.GET["key"])
        if KillHouseRequest.objects.filter(active_state='active', add_car__driver=car, trash=False).exists():
            return Response({"result": "ماشین دارای بار فعال میباشد"}, status=status.HTTP_403_FORBIDDEN)

        kill_house_cars = KillHouseADDCAR.objects.filter(driver=car, trash=False)
        if kill_house_cars:
            for add_car in kill_house_cars:
                add_car.trash = True
                add_car.save()

        car.trash = True
        car.save()
        return Response('ماشین با موفقیت حذف شد', status=status.HTTP_200_OK)


class KillHouseDriverTotalDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouseDriver.objects.all()
    serializer_class = KillHouseDriverSerializer
    permission_classes = [TokenHasReadWriteScope]

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

        if request.GET['role'] == 'KillHouse':
            user = SystemUserProfile.objects.get(trash=False, user=request.user)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            kill_house_drivers = KillHouseDriver.objects.filter(archive=False, pk__in=KillHouseADDCAR.objects.filter(
                Q(kill_house=kill_house) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                archive=False).values_list(
                'driver__id', flat=True), trash=False)
            active = kill_house_drivers.filter(pk__in=KillHouseADDCAR.objects.filter(
                Q(kill_house=kill_house) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                active_state=True, archive=False).values_list('driver__id', flat=True))
            inactive = kill_house_drivers.filter(pk__in=KillHouseADDCAR.objects.filter(
                Q(kill_house=kill_house) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                active_state=False, archive=False).values_list('driver__id', flat=True))
            suspended = 0

        else:
            kill_house_drivers = KillHouseDriver.objects.filter(trash=False, archive=False)

            active = kill_house_drivers.filter(pk__in=KillHouseADDCAR.objects.filter(
                Q(kill_house__isnull=False) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                active_state=True, archive=False).values_list('driver__id', flat=True))
            inactive = kill_house_drivers.filter(pk__in=KillHouseADDCAR.objects.filter(
                Q(kill_house__isnull=False) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                active_state=False, archive=False).values_list('driver__id', flat=True))
            suspended = kill_house_drivers.exclude(pk__in=KillHouseADDCAR.objects.filter(
                Q(kill_house__isnull=False) | Q(kill_house__isnull=True, driver__type='rental'),
                trash=False, archive=False).values_list('driver__id', flat=True))
            suspended = len(suspended)

        rental = kill_house_drivers.filter(type='rental')
        exclusive = kill_house_drivers.filter(type='exclusive')

        result = {
            "total": len(kill_house_drivers),
            "exclusive": len(exclusive),
            "rental": len(rental),
            "active": len(active),
            "inactive": len(inactive),
            "suspended": suspended,
        }

        return Response(result, status=status.HTTP_200_OK)


# ویوست مربوط به اضافه کردن خودرو به کشتارگاه
class KillHouseADDCARViewSet(viewsets.ModelViewSet):
    queryset = KillHouseADDCAR.objects.all()
    serializer_class = KillHouseADDCARSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به اضافه کردن خودرو به کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        kill_house = KillHouse.objects.get(key=request.data['kill_house_key'], trash=False)
        driver = KillHouseDriver.objects.get(key=request.data['driver_key'])
        request.data.pop('driver_key')
        request.data.pop('kill_house_key')
        if 'role' in request.data.keys():
            request.data.pop('role')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            if KillHouseADDCAR.objects.filter(kill_house=kill_house, driver=driver, trash=False):
                return Response({"result": "already exist"}, status=status.HTTP_403_FORBIDDEN)
            kill_house_car = serializer.create(validated_data=request.data)
            kill_house_car.kill_house = kill_house
            kill_house_car.driver = driver
            kill_house_car.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    # تابع مربوط به نمایش خودروهای ثبت شده کشتارگاه
    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        if 'kill_request_key' in request.GET:
            kill_request = KillRequest.objects.get(key=request.GET['kill_request_key'])
        list_car = []
        if 'key' in request.GET:
            poultry_request = PoultryRequest.objects.get(key=request.GET['key'])
        else:
            poultry_request = None
        if 'kill_house_key' in request.GET:
            kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'], trash=False)

            if kill_house.killer == True:
                if KillHouseADDCAR.objects.filter(kill_house=kill_house, trash=False, archive=False).exists():
                    cars = KillHouseADDCAR.objects.filter(
                        Q(kill_house=kill_house) | Q(kill_house__isnull=True, driver__type='rental'),
                        trash=False, archive=False).order_by('driver__type')
                else:
                    killer_kill_house = KillHouse.objects.get(key=kill_request.slaughter_house.key)
                    cars = KillHouseADDCAR.objects.filter(
                        Q(kill_house=killer_kill_house) | Q(kill_house__isnull=True, driver__type='rental'),
                        trash=False, archive=False).order_by('driver__type')
            else:
                cars = KillHouseADDCAR.objects.filter(
                    Q(kill_house=kill_house) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                    archive=False).order_by(
                    'driver__type')

        else:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
            cars = KillHouseADDCAR.objects.filter(
                Q(kill_house__in=kill_house) | Q(kill_house__isnull=True, driver__type='rental'), trash=False,
                archive=False).order_by(
                'driver__type')
        # if poultry_request != None:
        #     send_date = poultry_request.send_date.date()
        #     list1 = []
        #     kill_house_requests = KillHouseRequest.objects.filter(active_state='active')
        #     for kill_house_request in kill_house_requests:
        #         if kill_house_request.province_kill_request != None:
        #             date = kill_house_request.province_request.city_request_Poultry.poultry_request.send_date.date()
        #             if send_date.year == date.year and send_date.month == date.month and send_date.day == date.day:
        #                 list1.append(kill_house_request)
        #         else:
        #             date2 = kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.send_date.date()
        #             if send_date.year == date2.year and send_date.month == date2.month and send_date.day == date2.day:
        #                 list1.append(kill_house_request)
        #     if len(list1) > 0:
        #         for kill_house_car in cars:
        #             list2 = []
        #             i = 0
        #             for request_car in list1:
        #                 if i == len(list1):
        #                     break
        #                 if kill_house_car.driver.pelak == request_car.add_car.driver.pelak:
        #                     dict1 = {
        #                         "id": kill_house_car.id,
        #                         "key": kill_house_car.key,
        #                         "driver_name": kill_house_car.driver.driver_name,
        #                         "driver_mobile": kill_house_car.driver.driver_mobile,
        #                         "type_car": kill_house_car.driver.type_car,
        #                         "pelak": kill_house_car.driver.pelak,
        #                         "capocity": float(kill_house_car.driver.capocity),
        #                         "weight_without_load": kill_house_car.driver.weight_without_load,
        #                         "health_code": kill_house_car.driver.health_code,
        #                         "busy": True
        #                     }
        #                     list2.append(dict1)
        #                     i += 1
        #             if len(list2) > 0:
        #                 list_car.append(list2[0])
        #             else:
        #                 dict1 = {
        #                     "id": kill_house_car.id,
        #                     "key": kill_house_car.key,
        #                     "driver_name": kill_house_car.driver.driver_name,
        #                     "driver_mobile": kill_house_car.driver.driver_mobile,
        #                     "type_car": kill_house_car.driver.type_car,
        #                     "pelak": kill_house_car.driver.pelak,
        #                     "capocity": float(kill_house_car.driver.capocity),
        #                     "weight_without_load": kill_house_car.driver.weight_without_load,
        #                     "health_code": kill_house_car.driver.health_code,
        #                     "busy": False
        #                 }
        #                 list_car.append(dict1)
        #         return Response(list_car, status=status.HTTP_200_OK)

        for car in cars:
            if car.active_state == True:
                dict1 = {
                    "id": car.id,
                    "key": car.key,
                    "type": car.driver.type,
                    "driver_name": car.driver.driver_name,
                    "driver_mobile": car.driver.driver_mobile,
                    "type_car": car.driver.type_car,
                    "pelak": car.driver.pelak,
                    "capocity": float(car.driver.capocity),
                    "weight_without_load": car.driver.weight_without_load,
                    "health_code": car.driver.health_code,
                }
                list_car.append(dict1)
        return Response(list_car, status=status.HTTP_200_OK)

    # تابع مربوط به حذف خودروهای ثبت شده کشتارگاه
    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        car = KillHouseDriver.objects.get(key=request.GET["driver_key"])
        kill_house = KillHouse.objects.get(key=request.GET["kill_house_key"])
        if KillHouseRequest.objects.filter(active_state='active', add_car__driver=car, trash=False).exists():
            return Response({"result": "ماشین دارای بار فعال میباشد"}, status=status.HTTP_403_FORBIDDEN)
        add_car = KillHouseADDCAR.objects.filter(driver=car, kill_house=kill_house, trash=False)
        if add_car.count() > 0:
            add_car = add_car.last()
            add_car.trash = True
            add_car.save()
            return Response('ماشین با موفقیت حذف شد', status=status.HTTP_200_OK)
        else:
            return Response('مشکلی در حذف ماشین به وجود آمده است !', status=status.HTTP_403_FORBIDDEN)

    def update(self, request, pk=None, *args, **kwargs):
        car = KillHouseADDCAR.objects.get(key=request.data["add_car_key"])
        request.data.pop('add_car_key')
        serializer = self.serializer_class(car)
        serializer.update(instance=car, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


class AutomaticKillRequestViewSet(viewsets.ModelViewSet):
    queryset = AutomaticKillRequest.objects.all()
    serializer_class = AutomaticKillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    # def create(self, request, *args, **kwargs):
    #     # refresh(request.user.id)
    #     state = request.data['active']
    #     auomatic_kill_reqs = AutomaticKillRequest.objects.all()
    #     if auomatic_kill_reqs.count() > 0:
    #         auomatic_kill_reqs = auomatic_kill_reqs.last()
    #         auomatic_kill_reqs.active = state
    #         auomatic_kill_reqs.save()
    #         serializer_request = self.serializer_class(auomatic_kill_reqs)
    #         return Response(serializer_request.data, status=status.HTTP_200_OK)
    #     else:
    #         serializer = self.serializer_class(data=request.data)
    #         if serializer.is_valid():
    #             auomatic_kill_reqs = serializer.create(validated_data=request.data)
    #
    #     serializer_request = self.serializer_class(auomatic_kill_reqs)
    #     return Response(serializer_request.data, status=status.HTTP_201_CREATED)

    def create(self, request, *args, **kwargs):
        try:
            automatic_kill_req = AutomaticKillRequest.objects.latest('id')
        except AutomaticKillRequest.DoesNotExist:
            automatic_kill_req = None

        serializer = self.serializer_class(automatic_kill_req, data=request.data)
        if serializer.is_valid():
            if automatic_kill_req:
                serializer.save()
                return Response(serializer.data, status=status.HTTP_200_OK)
            else:
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors)


class KillRequestForPoultryViewSet(viewsets.ModelViewSet):
    queryset = KillRequest.objects.all()
    serializer_class = KillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def update(self, request, pk=None, *args, **kwargs):
        kill_req = KillRequest.objects.get(key=request.data['kill_req_key'], trash=False)
        kill_req.remain_quantity_for_poultry += int(request.data['quantity_sum'])
        kill_req.save()
        return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)


class DeleteDebtorsKillRequestsViewSet(viewsets.ModelViewSet):
    queryset = KillRequest.objects.all()
    serializer_class = KillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def destroy(self, request, pk=None, *args, **kwargs):
        today = datetime.now().date()
        kill_requests = KillRequest.objects.filter(trash=False, recive_date__date=today, market=False)
        for kill_request in kill_requests:
            kill_house = kill_request.kill_house
            kill_house_purchase = KillHousePurchaseRequest.objects.filter(limitation=True,
                                                                          kill_house=kill_house).first()
            if kill_house_purchase:
                total_unpaid_wage = 0
                total_paid_wage = 0
                total_unpaid_wage = get_finance_info(kill_house)['total_price']
                slaughter_transactions = InternalTransaction.objects.filter(
                    Q(kill_house=kill_house) | Q(parent_kill_house=kill_house),
                    status='completed',
                    trash=False)

                total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[
                                       'total'] or 0
                total_amount = total_unpaid_wage - total_paid_wage
                if total_amount >= kill_house_purchase.limitation_number:
                    if not ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                              kill_request__recive_date__date=today,
                                                              killhouse_user=kill_house).exists():
                        kill_request.message = 'به علت بدهی اعلام نیاز حذف گردید'
                        kill_request.trash = True
                        kill_request.save()

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


# ویوست مربوط به ثبت درخواست کشتار از سمت کشتارگاه
class KillRequestViewSet(viewsets.ModelViewSet):
    queryset = KillRequest.objects.all()
    serializer_class = KillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillRequestFilterSet
    filterset_fields = [
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__name',
        'slaughter_house__name',
        'export_country',
        'export_code',
        'direct_buying_code',
        'poultry__user__fullname',
        'poultry__user__mobile',
        'poultry__unit_name',
    ]

    # تابع مربوط به ثبت درخواست کشتار از سمت کشتارگاه
    def create(self, request, *args, **kwargs):
        total_unpaid_wage = 0
        total_paid_wage = 0

        limitation_direct_purchase = LimitationForDirectPurchaseAndBarInformation.objects.filter(
            trash=False, active=True).first()
        is_in_limitation_range = False

        if limitation_direct_purchase:
            if not limitation_direct_purchase.allow_buying:
                is_in_limitation_range = False
            else:
                if limitation_direct_purchase.start_time and limitation_direct_purchase.end_time:
                    current_time = datetime.now().time()
                    if limitation_direct_purchase.start_time <= current_time <= limitation_direct_purchase.end_time:
                        is_in_limitation_range = True

        if not is_in_limitation_range:
            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") == "kill_request" and t.get("active", False)),
                    None)
                if time:
                    start_hour = datetime.strptime(time.get("start", 0), "%H:%M:%S").time()
                    end_hour = datetime.strptime(time.get("end", 0), "%H:%M:%S").time()
                    current_hour = datetime.now().time().replace(second=0, microsecond=0)
                    if not (start_hour < current_hour < end_hour):
                        return Response(
                            {"result": "لطفا در ساعات مجاز برای ثبت درخواست اقدام نمایید!"},
                            status=status.HTTP_403_FORBIDDEN)
        if 'role' in request.data.keys() and request.data['role'] != None:
            role = request.data['role']
            request.data.pop('role')
        else:
            role = None
        if role != None and role == 'KillHouse':
            now_request_date = datetime.now().date()
            now = datetime.now().time()
            now_hour = KillHouseHourLimit.objects.filter(trash=False).last()
            if now_hour and 'poultry_key' not in request.data.keys():
                if now_hour.active == True:
                    request_date = datetime.strptime(request.data['recive_date'], '%Y-%m-%d %H:%M:%S').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)

        killer_kill_house = None
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.get(key=request.data['kill_house_key'], trash=False)
        request.data.pop('kill_house_key')
        if kill_house.out_province == True:
            return Response({
                "result": "امکان ثبت اعلام نیاز برای کشتارگاه خارج از استان وجود ندارد!"},
                status=status.HTTP_403_FORBIDDEN)
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()
        if kill_house_purchase:
            if kill_house_purchase.allow == False:
                return Response({
                    "result": "شما مجاز به ثبت درخواست خرید نمیباشید جهت اطلاع با اتحادیه مرغ گوشتی استان خود تماس حاصل فرمایید"},
                    status=status.HTTP_403_FORBIDDEN)
            else:
                if kill_house_purchase.limitation == True:
                    try:
                        recive_date = datetime.strptime(str(request.data['recive_date']),
                                                        '%Y-%m-%dT%H:%M:%S.%fZ').date()
                    except:
                        recive_date = datetime.strptime(str(request.data['recive_date']), '%Y-%m-%d %H:%M:%S').date()
                    total_unpaid_wage = get_finance_info(kill_house)['total_price']
                    slaughter_transactions = InternalTransaction.objects.filter(
                        Q(kill_house=kill_house) | Q(parent_kill_house=kill_house),
                        status='completed',
                        trash=False)

                    total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[
                                           'total'] or 0

                    if kill_house_purchase.limitation_number <= total_unpaid_wage - total_paid_wage:
                        if not ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
                                                                  kill_request__recive_date__date=recive_date,
                                                                  trash=False,
                                                                  state__in=('pending', 'accepted')).exists():
                            return Response({
                                "result": "به علت بدهی امکان ثبت درخواست وحود ندارد لطفا بدهی خود را در پنل کارمزد ها تسویه کنید"},
                                status=status.HTTP_403_FORBIDDEN)
        if kill_house.poultry_payment_limitation:
            today_check_date = datetime.now().date()
            if ProvinceKillRequest.objects.filter(Q(payment_deadline_date__date__lt=today_check_date,
                                                    extension_payment_deadline_date__isnull=True) | Q(
                payment_deadline_date__date__lt=today_check_date,
                extension_payment_deadline_date__date__lt=today_check_date), trash=False, temporary_trash=False,
                                                  return_to_province=False,
                                                  state__in=('pending', 'accepted'), payment_deadline_archive=False,
                                                  payment_deadline_state__in=('pending', 'rejected')).exists():
                return Response({
                    "result": "به دلیل عدم تسویه با مرغدار شما مجاز به خرید نمی باشید لطفا اطلاعات پرداخت را در بخش تسویه حساب بارگزاری کنید!"},
                    status=status.HTTP_403_FORBIDDEN)
        if 'killer_kill_house_key' in request.data.keys():
            if request.data['killer_kill_house_key'] != None:
                killer_kill_house = KillHouse.objects.get(key=request.data['killer_kill_house_key'], trash=False)
                request.data.pop('killer_kill_house_key')
            else:
                request.data.pop('killer_kill_house_key')
        cash = request.data['cash']
        credit = request.data['credit']
        low_weight = request.data['low_weight']
        high_weight = request.data['high_weight']
        credit = request.data['credit']
        request.data.pop('cash')
        request.data.pop('credit')
        request.data.pop('low_weight')
        request.data.pop('high_weight')
        poultry = None
        hatching = None
        if 'poultry_key' in request.data.keys():
            poultry = Poultry.objects.get(key=request.data['poultry_key'])
            hatching = PoultryHatching.objects.get(key=request.data['hatching_key'])
            request.data.pop('poultry_key')
            request.data.pop('hatching_key')
            if poultry.order_limit:
                return Response({
                    "result": "امکان ثبت کشتار برای مرغدار وجود ندارد جهت اطلاعات بیشتر بااتحادیه استان خود هماهنگ کنید!"},
                    status=status.HTTP_403_FORBIDDEN)
            if 'confirm_poultry_mobile' in request.data.keys() and len(request.data['confirm_poultry_mobile']) == 11:

                first_mobile_number = poultry.user.mobile
                second_mobile_number = request.data['confirm_poultry_mobile']
                request.data.pop('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()

            try:
                recive_date = datetime.strptime(str(request.data['recive_date']), '%Y-%m-%dT%H:%M:%S.%fZ').date()
            except:
                recive_date = datetime.strptime(str(request.data['recive_date']), '%Y-%m-%d %H:%M:%S').date()

            if request.data['free_direct_buying'] == True:

                if kill_house.quota:
                    kill_house_info = calculate_governmental_quota(kill_house)
                    if kill_house_info == 'not_allowed':
                        return Response({"result": " امکان خرید آزاد تا تکمیل تعهد دولتی وجود ندارد!"},
                                        status=status.HTTP_403_FORBIDDEN)

            age_range = ChickenAgeRange.objects.filter(trash=False).first()
            if role and role not in ('AdminX', 'SuperAdmin'):

                if age_range.active == True:
                    chicken_age = (datetime.now().date() - 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 kill_house.max_kill_limit and kill_house.total_kill_capacity > 0:
                recive_date = datetime.strptime(str(request.data['recive_date']), '%Y-%m-%dT%H:%M:%S.%fZ').date()

                if kill_house.max_kill_limit and kill_house.total_kill_capacity > 0:
                    total_province_kill_requests = ProvinceKillRequest.objects.filter(trash=False,
                                                                                      return_to_province=False,
                                                                                      archive_wage=False,
                                                                                      state__in=('pending', 'accepted'),
                                                                                      killhouse_user=kill_house,
                                                                                      kill_request__recive_date__date=recive_date)
                    total_province_kill_requests_quantity = \
                        total_province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total'] or 0
                    if kill_house.total_kill_capacity < total_province_kill_requests_quantity + int(
                            request.data['kill_capacity']):
                        return Response({"result": "تعداد وارد شده از مانده سهمیه کشتار روزانه کشتارگاه بیشتر است !"},
                                        status=status.HTTP_403_FORBIDDEN)

        dict1 = {}
        dict2 = {}
        if kill_house.ware_house_remaining_weight_limitation_status:
            if kill_house.total_remain_warehouse_governmental_weight > kill_house.ware_house_remaining_weight_limitation:
                return Response({
                    "result": "باقی مانده انبار شما از حداکثر محدودیت وزن باقی مانده انبار بیشتر است !"},
                    status=status.HTTP_403_FORBIDDEN)

        if kill_house.ware_house_remaining_percent_limitation_status:
            if not check_kill_house_remain_limitation_weight(kill_house):
                return Response({
                    "result": "باقی مانده انبار شما از حداکثر محدودیت وزن باقی مانده روزانه انبار بیشتر است !"},
                    status=status.HTTP_403_FORBIDDEN)

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_request = serializer.create(validated_data=request.data)
            buying_verification = DirectBuyingVerification.objects.filter(trash=False).first()
            price_confirmation = PriceConfirmation.objects.filter(trash=False).first()
            price_confirmation = price_confirmation.poultry_status if price_confirmation else False
            kill_request.kill_house = kill_house
            free_sale_in_province = False if kill_request.free_direct_buying == False else True
            kill_request.previous_kill_capacity = kill_request.kill_capacity
            if poultry != None:
                # hatching = PoultryHatching.objects.filter(trash=False, poultry=poultry).only('chicken_breed').first()
                if 'payment_deadline_days' in request.data.keys():
                    kill_request.payment_deadline_date = datetime.now() + timedelta(
                        days=request.data['payment_deadline_days'])
                    kill_request.payment_deadline = True

                kill_request.chicken_breed = hatching.chicken_breed
                province_operator = SystemUserProfile.objects.filter(trash=False, role__name='ProvinceOperator').first()
                kill_request.poultry = poultry
                kill_request.poultry_hatching = hatching
                mobile = poultry.user.mobile
                poultry_name = poultry.user.fullname
                code = str(random.randint(10000, 99000))
                kill_request.direct_buying_code = code
                buyer = kill_request.kill_house.kill_house_operator.user.fullname
                buyer_mobile = kill_request.kill_house.kill_house_operator.user.mobile
                quantity = kill_request.kill_capacity
                kill_place = kill_request.slaughter_house.name if kill_request.slaughter_house != None else kill_request.kill_house.name
                date_str = str(kill_request.recive_date)
                # if kill_request.recive_date.date().day == datetime.now().date().day:
                try:
                    date = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%f%z').date()
                except:
                    date = 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 kill_request.export_status == False:
                    pass

                    # sms_direct_buying_sms = threading.Thread(
                    #     target=direct_buying_code_sms,
                    #     args=(
                    #         mobile, buyer, buyer_mobile, quantity, kill_place, date, code))
                    # sms_direct_buying_sms.start()
                else:
                    export_country = kill_request.export_country
                    sms_export_sms = threading.Thread(
                        target=export_code_sms,
                        args=(
                            mobile, buyer, buyer_mobile, quantity, kill_place, date, export_country,
                            code, poultry_name, province_operator.mobile))
                    sms_export_sms.start()

            # kill_request.remain_quantity_for_poultry = kill_request.kill_capacity
            if killer_kill_house != None:
                kill_request.slaughter_house = killer_kill_house
            kill_request.remain_quantity = kill_request.kill_capacity
            dict1.update({
                'cash': cash,
                'credit': credit
            })
            kill_request.buy_type = dict1
            dict2.update({
                'low_weight': low_weight,
                'high_weight': high_weight

            })
            kill_request.weight_type = dict2
            if role != None:
                kill_request.registrar = {
                    "role": role,
                    "full_name": user.fullname,
                    "date": str(kill_request.create_date)
                }
            kill_request.save()
            permission_duirect_buying = AutomaticDirectBuyingPermission.objects.first()
            if role == 'KillHouse':
                if kill_request.poultry is None:
                    if SmsLicense.objects.filter(kill_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()
                        quantity = kill_request.kill_capacity
                        chicken_breed = kill_request.chicken_breed
                        date_str = kill_request.recive_date
                        try:
                            send_date = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%f%z').date()
                        except:
                            send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                        # send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                        send_date = jdatetime.datetime.fromgregorian(year=send_date.year, month=send_date.month,
                                                                     day=send_date.day).strftime('%Y-%m-%d')
                        date_list = reversed(send_date.split('-'))
                        separate = "-"
                        send_date = separate.join(date_list)
                        province = kill_request.kill_house.system_address.province.name
                        city = kill_request.kill_house.system_address.city.name
                        kill_house_name = kill_request.kill_house.name
                        province_operator_mobile = province_operator.user.mobile
                        province_operator_name = province_operator.user.fullname
                        sms_kill_request_province_sms = threading.Thread(target=kill_request_province_sms,
                                                                         args=(
                                                                             province_operator_mobile, kill_house_name,
                                                                             quantity,
                                                                             chicken_breed,
                                                                             send_date, province, city))
                        sms_kill_request_province_sms.start()
                        serializer_request = self.serializer_class(kill_request)
                if price_confirmation:
                    kill_request.price_confirmation = True
                    kill_request.save()
                return Response({"result": "درخواست شما با موفقیت برای استان ارسال شد."},
                                status=status.HTTP_201_CREATED)

            else:
                kill_request.remain_quantity = kill_request.kill_capacity
                kill_request.province_state = 'accepted'
                kill_request.final_accept = True
                kill_request.save()
                price = Pricing.objects.all()
                if price.count() > 0:
                    price = price.last()
                    factor = KillRequestFactor(
                        kill_request=kill_request,
                        amount=round(
                            (kill_request.kill_capacity * kill_request.Index_weight) * price.live_chicken_price,
                            0),
                        minimum_amount=round(
                            ((kill_request.kill_capacity * kill_request.Index_weight) * price.live_chicken_price) * (
                                    70 / 100),
                            0)

                    )
                    factor.save()
                    kill_request.factor_amount = factor.amount
                    kill_request.save()
                if kill_request.poultry is None:
                    if SmsLicense.objects.filter(kill_request=True).exists():
                        mobile = kill_request.kill_house.kill_house_operator.user.mobile
                        kill_house_name = kill_request.kill_house.name
                        sms_province_kill_request_accept_sms = threading.Thread(
                            target=province_kill_request_accept_sms,
                            args=(
                                kill_house_name,))
                        sms_province_kill_request_accept_sms.start()
                now = datetime.now().time().replace(second=0, microsecond=0)
                if price_confirmation:
                    poultry_fullname = poultry.unit_name
                    # poultry_mobile = poultry.user.mobile
                    poultry_mobile = second_mobile_number if not kill_request.direct_buying_intermediary_mobile else kill_request.direct_buying_intermediary_mobile
                    quantity = kill_request.kill_capacity
                    chicken_breed = kill_request.chicken_breed
                    request_kill_house = kill_request.kill_house.name
                    date_str = kill_request.recive_date
                    clean_date_str = date_str.split('T')[0] + ' ' + date_str.split('T')[1].split('.')[0]
                    send_date = datetime.strptime(str(clean_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_price_poultry_request = threading.Thread(
                        target=confirm_price_poultry_request_direct_buying_sms,
                        args=(
                            poultry_mobile, poultry_fullname,
                            quantity, chicken_breed,
                            send_date,
                            kill_request.free_direct_buying,
                            kill_request.amount, request_kill_house,
                            code))
                    confirm_price_poultry_request.start()
                    kill_request.price_confirmation = True
                    kill_request.save()
                    return Response({"result": "درخواست شما با موفقیت ارسال شد."},
                                    status=status.HTTP_201_CREATED)
                else:
                    if permission_duirect_buying.allow == True and not buying_verification.poultry_code_mandatory and permission_duirect_buying.start_time < \
                            now < permission_duirect_buying.end_time:
                        poultry_requests = PoultryRequest.objects.filter(poultry=kill_request.poultry,
                                                                         trash=False).order_by(
                            'create_date')
                        if not hatching:
                            hatching = PoultryHatching.objects.filter(poultry=kill_request.poultry, state='pending',
                                                                      archive=False,
                                                                      allow_hatching='pending', trash=False).order_by(
                                'id').last()

                        poultry = Poultry.objects.get(key=kill_request.poultry.key, trash=False)
                        vet_farm = VetFarm.objects.filter(trash=False, poultry=poultry).first()
                        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

                        if poultry_requests.count() > 0:
                            order_code = poultry_requests.last().order_code + 1
                        else:
                            order_code = int(str(poultry.user.base_order) + '0001')
                        city_operator = CityOperator.objects.filter(unit_name=poultry.city_operator, trash=False).last()
                        if not city_operator:
                            city_operator = CityOperator.objects.filter(unit_name='اتحادیه استان (فاقد تعاونی)',
                                                                        trash=False).last()
                        if hatching.left_over < kill_request.kill_capacity:
                            return Response({"result": "تعداد جوجه در سالن کمتر از تعداد درخواستی است"},
                                            status=status.HTTP_403_FORBIDDEN)

                        poultry_request = PoultryRequest(
                            hatching=hatching,
                            order_code=order_code,
                            general_order_code=general_order_code,
                            city_operator=city_operator,
                            poultry=poultry,
                            previous_quantity=kill_request.kill_capacity,
                            remain_quantity=kill_request.kill_capacity,
                            quantity=kill_request.kill_capacity,
                            first_quantity=kill_request.kill_capacity,
                            chicken_breed=hatching.chicken_breed,
                            Index_weight=kill_request.Index_weight,
                            state_process='accepted',
                            province_state='accepted',
                            direct_buying=True,
                            free_sale_in_province=free_sale_in_province,
                            send_date=kill_request.recive_date,
                            amount=kill_request.amount,
                        )
                        if kill_request.freezing:
                            poultry_request.freezing = True
                        poultry_request.save()
                        kill_request.poultry_request = poultry_request
                        if kill_request.export_status == True:
                            poultry_request.export = True
                        send_date_str = poultry_request.send_date
                        send_date_datetime = datetime.strptime(str(send_date_str), '%Y-%m-%dT%H:%M:%S.%fZ')
                        poultry_request.killing_age = (send_date_datetime.date() - hatching.date.date()).days + 1

                        poultry_request.state = {
                            "city_operator": city_operator.user.fullname,
                            "city_state": poultry_request.state_process,
                            "city_operator_mobile": city_operator.user.mobile,
                            "province_operator": "",
                            "province_state": ""
                        }
                        poultry_request.registrar = {
                            "role": role,
                            "fullname": user.fullname,
                            "date": str(poultry_request.create_date)
                        }
                        poultry_request.save()

                        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()
                        wage_type = WageType.objects.filter(en_name='province-kill-request', trash=False).first()
                        wage = wage_type.amount if wage_type.status == True else 0
                        percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0,
                                                                                    trash=False)
                        province_killrequest = ProvinceKillRequest(
                            killhouse_user=kill_request.kill_house,
                            kill_request=kill_request,
                            province_request=check,
                            quantity=kill_request.kill_capacity,
                            total_killed_quantity=kill_request.kill_capacity,
                            total_killed_weight=int(kill_request.kill_capacity * poultry_request.Index_weight),
                            main_quantity=kill_request.kill_capacity,
                            wage=wage,
                            direct_buying=True,
                            total_wage_amount=wage * int(kill_request.kill_capacity * poultry_request.Index_weight),
                        )
                        province_killrequest.save()
                        # fine = FinePermission.objects.filter(trash=False).first()
                        # time_for_fine = datetime.now()
                        # time_for_fine = time_for_fine.replace(second=0, microsecond=0).time()
                        # if fine.direct_buying:
                        #     if fine.direct_buying_start_time < time_for_fine < fine.direct_buying_end_time:
                        #         province_killrequest.direct_buying_fine = True
                        #         province_killrequest.direct_buying_fine_amount = fine.direct_buying_fine_coefficient * province_killrequest.total_wage_amount
                        #         province_killrequest.direct_buying_fine_coefficient = fine.direct_buying_fine_coefficient
                        create_update_chicken_commission_prices()
                        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':
                                    province_killrequest.union_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.union_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'company':
                                    province_killrequest.company_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.company_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'guilds':
                                    province_killrequest.guilds_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.guilds_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'city':
                                    province_killrequest.city_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.city_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'other':
                                    province_killrequest.other_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.other_share_percent = percentage_wage_type.percent

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

                                else:
                                    province_killrequest.other_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.other_share_percent = percentage_wage_type.percent
                                province_killrequest.save()

                        tomorrow = datetime.now().date() + timedelta(days=1)
                        if not KillHouseWareHouse.objects.filter(kill_house=kill_request.kill_house,
                                                                 date__date=tomorrow).exists():
                            ware_house_date = datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day,
                                                       hour=1,
                                                       minute=12, second=20)
                            kill_house_ware_house = KillHouseWareHouse(
                                kill_house=kill_request.kill_house,
                                date=ware_house_date
                            )
                            kill_house_ware_house.save()
                        kill_house_check = KillHouseCheckRequest(
                            province_kill_request=province_killrequest,
                            state='accepted'
                        )

                        kill_house_check.save()
                        province_killrequest.state = 'accepted'
                        if buying_verification.payment_deadline:
                            province_killrequest.payment_deadline = True
                            province_killrequest.payment_deadline_date = datetime.now() + timedelta(
                                days=request.data['payment_deadline_days'])
                        province_killrequest.save()
                        check.quantity = 0
                        check.save()

                        if poultry_request.export == True:
                            hatching.export_killed_weight += int(
                                kill_request.kill_capacity * poultry_request.Index_weight)
                            hatching.export_killed_quantity += kill_request.kill_capacity


                        elif poultry_request.free_sale_in_province == True:
                            hatching.free_killed_quantity += int(
                                kill_request.kill_capacity * poultry_request.Index_weight)
                            hatching.free_quantity += kill_request.kill_capacity

                        else:
                            hatching.governmental_killed_quantity += int(
                                kill_request.kill_capacity * poultry_request.Index_weight)
                            hatching.governmental_quantity += kill_request.kill_capacity
                        hatching.killed_quantity += kill_request.kill_capacity
                        hatching.save()
                        poultry_request.remain_quantity = 0
                        poultry_request.direct_buying_kill_place = kill_request.kill_house.name
                        poultry_request.direct_buying_buyer_info = {
                            "buyer_fullname": kill_request.kill_house.kill_house_operator.user.fullname,
                            "buyer_mobile": kill_request.kill_house.kill_house_operator.user.mobile,
                        }
                        poultry_request.save()
                        if kill_request.export_status == True:
                            kill_request.export_state = 'accepted'
                            kill_request.direct_buying_message = request.data['direct_buying_message']

                        else:
                            kill_request.direct_buying_state = 'accepted'

                        kill_request.accept_reject_date = datetime.now()

                        kill_request.save()
                        poultry_fullname = poultry.unit_name
                        # poultry_mobile = poultry.user.mobile
                        poultry_mobile = second_mobile_number if not kill_request.direct_buying_intermediary_mobile else kill_request.direct_buying_intermediary_mobile
                        quantity = kill_request.kill_capacity
                        chicken_breed = kill_request.chicken_breed
                        request_kill_house = kill_request.kill_house.name
                        date_str = kill_request.recive_date
                        if isinstance(date_str, str):
                            clean_date_str = date_str.split('.')[0]
                            clean_date_str = clean_date_str.replace('T', ' ')
                            clean_date_str = clean_date_str.replace('Z', '')

                            send_date = datetime.strptime(clean_date_str, '%Y-%m-%d %H:%M:%S').date()

                        elif isinstance(date_str, datetime):
                            send_date = date_str.date()
                        # clean_date_str = date_str.split('T')[0] + ' ' + date_str.split('T')[1].split('.')[0]
                        # send_date = datetime.strptime(str(clean_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 = "-"
                        code = "-"
                        send_date = separate.join(date_list)
                        confirm_price_poultry_request = threading.Thread(
                            target=confirm_price_poultry_request_direct_buying_sms,
                            args=(
                                poultry_mobile, poultry_fullname,
                                quantity, chicken_breed,
                                send_date,
                                kill_request.free_direct_buying,
                                kill_request.amount, request_kill_house,
                                code))
                        confirm_price_poultry_request.start()
                        bot_eitaa_for_each_province_kill_request(province_killrequest, vet_farm)
                        return Response({"result": "درخواست شما با موفقیت ارسال شد."},
                                        status=status.HTTP_201_CREATED)
                    else:
                        poultry_fullname = poultry.unit_name
                        # poultry_mobile = poultry.user.mobile
                        poultry_mobile = second_mobile_number if not kill_request.direct_buying_intermediary_mobile else kill_request.direct_buying_intermediary_mobile
                        quantity = kill_request.kill_capacity
                        chicken_breed = kill_request.chicken_breed
                        request_kill_house = kill_request.kill_house.name
                        date_str = kill_request.recive_date
                        if isinstance(date_str, str):
                            clean_date_str = date_str.split('.')[0]
                            clean_date_str = clean_date_str.replace('T', ' ')
                            clean_date_str = clean_date_str.replace('Z', '')

                            send_date = datetime.strptime(clean_date_str, '%Y-%m-%d %H:%M:%S').date()

                        elif isinstance(date_str, datetime):
                            send_date = date_str.date()
                        # clean_date_str = date_str.split('T')[0] + ' ' + date_str.split('T')[1].split('.')[0]
                        # send_date = datetime.strptime(str(clean_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 = "-"
                        code = "-"
                        send_date = separate.join(date_list)
                        confirm_price_poultry_request = threading.Thread(
                            target=confirm_price_poultry_request_direct_buying_sms,
                            args=(
                                poultry_mobile, poultry_fullname,
                                quantity, chicken_breed,
                                send_date,
                                kill_request.free_direct_buying,
                                kill_request.amount, request_kill_house,
                                code))
                        confirm_price_poultry_request.start()
                return Response({"result": "درخواست شما با موفقیت به پنل تخصیص اضافه شد."},
                                status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        now = datetime.now().date()
        if 'role' in request.GET:
            if request.GET['role'] == 'KillHouse':
                kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
                kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
                date1 = datetime.strptime(str(request.GET['date1']),
                                          '%Y-%m-%d').date() if 'date1' in request.GET else now
                date2 = datetime.strptime(str(request.GET['date2']),
                                          '%Y-%m-%d').date() if 'date2' in request.GET else now
                if 'direct_buying' in request.GET:
                    from django.db.models import Value
                    kill_req_list = []
                    # if request.GET['type'] == 'pending':
                    #     querysets = KillRequest.objects.filter(kill_house__in=kill_house, recive_date__date__gte=date1,
                    #                                            recive_date__date__lte=date2, poultry__isnull=False,
                    #                                            direct_buying_state='pending',
                    #                                            export_status=False,trash=False
                    #                                            ).order_by(
                    #         'recive_date')
                    # else:
                    querysets = KillRequest.objects.filter(kill_house__in=kill_house, recive_date__date__gte=date1,
                                                           recive_date__date__lte=date2, poultry__isnull=False,
                                                           direct_buying_state__in=(
                                                               'accepted', 'rejected', 'deleted', 'pending'),
                                                           export_status=False, trash=False, market=False,
                                                           ).order_by(
                        Case(
                            When(direct_buying_state='pending', then=Value(0)),
                            default=Value(1)
                        ),
                        '-recive_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 (self.filterset_class(
                                            data=query,
                                            queryset=querysets
                                    )
                                    ).filter():
                                        ps = self.filterset_class(data=query, queryset=querysets)
                                        kill_req_list = ps.filter()
                                querysets = [] if len(kill_req_list) == 0 else kill_req_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(querysets)
                    if page is not None:
                        serializer = KillRequestSerializer(page, many=True)
                        return self.get_paginated_response(serializer.data)

                    serializer = KillRequestSerializer(querysets, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)

                if 'export' in request.GET:
                    kill_req_list = []
                    if request.GET['type'] == 'pending':
                        querysets = KillRequest.objects.filter(kill_house__in=kill_house, recive_date__date__gte=date1,
                                                               recive_date__date__lte=date2, poultry__isnull=False,
                                                               export_status=True, market=False,
                                                               export_state='pending'
                                                               ).order_by(
                            'recive_date')
                    else:
                        querysets = KillRequest.objects.filter(kill_house__in=kill_house, recive_date__date__gte=date1,
                                                               recive_date__date__lte=date2, poultry__isnull=False,
                                                               export_status=True, market=False,
                                                               export_state__in=(
                                                                   'accepted', 'rejected', 'deleted'),
                                                               ).order_by(
                            'recive_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 (self.filterset_class(
                                            data=query,
                                            queryset=querysets
                                    )
                                    ).filter():
                                        ps = self.filterset_class(data=query, queryset=querysets)
                                        kill_req_list = ps.filter()
                                querysets = [] if len(kill_req_list) == 0 else kill_req_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(querysets)
                    if page is not None:
                        serializer = KillRequestSerializer(page, many=True)
                        return self.get_paginated_response(serializer.data)

                    serializer = KillRequestSerializer(querysets, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)

                queryset_list = KillRequest.objects.filter(kill_house__in=kill_house, trash=False, market=False,
                                                           poultry__isnull=True).order_by(
                    'recive_date')
                querysets = [
                    kill_request for kill_request in queryset_list
                    if date1 <= kill_request.recive_date.date() <= date2
                ]
            elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX']:
                user = SystemUserProfile.objects.get(user=request.user, trash=False)
                date1 = datetime.strptime(str(request.GET['date1']),
                                          '%Y-%m-%d').date() if 'date1' in request.GET else now
                date2 = datetime.strptime(str(request.GET['date2']),
                                          '%Y-%m-%d').date() if 'date2' in request.GET else now

                if 'direct_buying' in request.GET:
                    from django.db.models import Value
                    kill_req_list = []
                    # if request.GET['type'] == 'pending':
                    #     querysets = KillRequest.objects.filter(
                    #         recive_date__date__gte=date1,
                    #         recive_date__date__lte=date2, poultry__isnull=False,
                    #         direct_buying_state='pending',
                    #         export_status=False,trash=False
                    #     ).order_by(
                    #         'recive_date')
                    # else:
                    querysets = KillRequest.objects.filter(
                        recive_date__date__gte=date1,
                        recive_date__date__lte=date2, poultry__isnull=False, market=False,
                        final_accept=True,
                        direct_buying_state__in=(
                            'accepted', 'rejected', 'deleted', 'pending'),
                        export_status=False, trash=False
                    ).select_related(
                        'poultry', 'kill_house', 'slaughter_house', 'poultry_hatching'

                    ).order_by(
                        Case(
                            When(direct_buying_state='pending', then=Value(0)),
                            default=Value(1)
                        ),
                        '-recive_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 (self.filterset_class(
                                            data=query,
                                            queryset=querysets
                                    )
                                    ).filter():
                                        ps = self.filterset_class(data=query, queryset=querysets)
                                        kill_req_list = ps.filter()
                                querysets = [] if len(kill_req_list) == 0 else kill_req_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(querysets)
                    if page is not None:
                        serializer = KillRequestForDirectBuyingTrueSerializer(page, many=True)
                        return self.get_paginated_response(serializer.data)

                    serializer = KillRequestSerializer(querysets, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)

                if 'export' in request.GET:
                    kill_req_list = []
                    if request.GET['type'] == 'pending':
                        querysets = KillRequest.objects.filter(
                            recive_date__date__gte=date1,
                            recive_date__date__lte=date2, poultry__isnull=False,
                            export_status=True, market=False,
                            export_state='pending'
                        ).order_by(
                            'recive_date')
                    else:
                        querysets = KillRequest.objects.filter(
                            recive_date__date__gte=date1,
                            recive_date__date__lte=date2, poultry__isnull=False,
                            export_status=True, market=False,
                            export_state__in=(
                                'accepted', 'rejected', 'deleted'),
                        ).order_by(
                            'recive_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 (self.filterset_class(
                                            data=query,
                                            queryset=querysets
                                    )
                                    ).filter():
                                        ps = self.filterset_class(data=query, queryset=querysets)
                                        kill_req_list = ps.filter()
                                querysets = [] if len(kill_req_list) == 0 else kill_req_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(querysets)
                    if page is not None:
                        serializer = KillRequestSerializer(page, many=True)
                        return self.get_paginated_response(serializer.data)

                    serializer = KillRequestSerializer(querysets, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)

                querysets_list = KillRequest.objects.filter(
                    trash=False, poultry__isnull=True).order_by('-recive_date')
                # for queryset in querysets_list:
                #     if (now - queryset.recive_date.date()).days > 2:
                #         queryset.remain_quantity = 0
                #         queryset.save()

                querysets = [
                    queryset_list for queryset_list in querysets_list
                    if date1 <= queryset_list.recive_date.date() <= date2
                ]
        elif 'poultry_key' in request.GET:
            kill_requests = []
            today = datetime.now().date()
            poultry = Poultry.objects.get(key=request.GET['poultry_key'], trash=False)
            kill_requests = KillRequest.objects.filter(direct_buying_state__in=('pending', 'accepted'), market=False,
                                                       poultry=poultry, recive_date__date=today, trash=False)
            serializer = KillRequestSerializer(kill_requests, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)


        else:
            if '0' in request.GET:
                poultry_request = PoultryRequest.objects.get(key=request.GET['0'])

                queryset = KillRequest.objects.filter(
                    recive_date__year=poultry_request.send_date.year,
                    recive_date__month=poultry_request.send_date.month,
                    recive_date__day=poultry_request.send_date.day,
                    province_state='accepted', market=False,
                    # automatic=False,
                    trash=False, poultry__isnull=True).order_by('id')
                result_list = []
                if len(poultry_request.kill_house_list) != 0:
                    querysets = []
                    for item in poultry_request.kill_house_list:
                        parts = item.split("(")
                        name = parts[0].strip()
                        result_list.append(name)
                    for kill_house in result_list:
                        priority_requests = []
                        remaining_requests = []
                        for kill_request in queryset:
                            if kill_request.kill_house.name == kill_house:
                                priority_requests.append(kill_request)
                                kill_request.priority = True
                                kill_request.save()
                            else:
                                kill_request.priority = False
                                kill_request.save()
                                remaining_requests.append(kill_request)
                        for x in priority_requests:
                            if x in querysets:
                                pass
                            else:
                                querysets.append(x)
                        for y in remaining_requests:
                            if y in querysets:
                                pass
                            else:
                                querysets.append(y)


                else:

                    for kill_request in queryset:
                        kill_request.priority = False
                        kill_request.save()
                    querysets = queryset

            else:
                querysets = []
        serializer = KillRequestSerializer(querysets, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # تابع مربوط به حذف درخواست کشتارهای ثبت شده از سمت کشتارگاه
    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        if 'role' in request.GET:
            kill_request = KillRequest.objects.get(key=request.GET['kill_request_key'])

            limitation_direct_purchase = LimitationForDirectPurchaseAndBarInformation.objects.filter(
                trash=False, active=True).first()

            if limitation_direct_purchase and limitation_direct_purchase.start_time and limitation_direct_purchase.end_time:
                current_time = datetime.now().time()
                if limitation_direct_purchase.start_time <= current_time <= limitation_direct_purchase.end_time:
                    record_create_time = kill_request.create_date.time()
                    if not (
                            limitation_direct_purchase.start_time <= record_create_time <= limitation_direct_purchase.end_time):
                        return Response(
                            {"result": "شما فقط می‌توانید بارهایی که در بازه زمانی مجاز ثبت شده‌اند را حذف کنید!"},
                            status=status.HTTP_403_FORBIDDEN)
            if request.GET['role'] == 'KillHouse':
                if kill_request.direct_buying_state != 'pending' and kill_request.export_status == False:
                    return Response({"result": "به علت تایید یا رد استان شما نمیتوانیددرخواست رو حذف کنید"})
                if kill_request.export_state != 'pending' and kill_request.export_status == True:
                    return Response({"result": "به علت تایید یا رد استان شما نمیتوانیددرخواست رو حذف کنید"})
            if kill_request.export_status == False:
                kill_request.direct_buying_state = 'deleted'
            else:
                kill_request.export_state = 'deleted'

            kill_request.trash = True
            kill_request.save()
            return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)

        user = SystemUserProfile.objects.get(user=request.user)
        kill_request = KillRequest.objects.get(id=pk)
        if ProvinceKillRequest.objects.filter(kill_request=kill_request, trash=False).exists():
            return Response({"result": "error"}, status=status.HTTP_403_FORBIDDEN)
        if SmsLicense.objects.filter(kill_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()
            quantity = kill_request.kill_capacity
            chicken_breed = kill_request.chicken_breed
            date_str = str(kill_request.recive_date)
            send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
            send_date = jdatetime.datetime.fromgregorian(year=send_date.year, month=send_date.month,
                                                         day=send_date.day).strftime('%Y-%m-%d')
            date_list = reversed(send_date.split('-'))
            separate = "-"
            send_date = separate.join(date_list)
            province = kill_request.kill_house.system_address.province.name
            city = kill_request.kill_house.system_address.city.name
            kill_house_name = kill_request.kill_house.name
            province_operator_mobile = province_operator.user.mobile
            province_operator_name = province_operator.user.fullname
            # kill_request_province_sms(province_operator_mobile, kill_house_name, quantity, chicken_breed,
            #                           send_date, province, city)

            sms_kill_request_delete_province_sms = threading.Thread(target=kill_request_delete_province_sms,
                                                                    args=(
                                                                        province_operator_mobile, kill_house_name,
                                                                        quantity,
                                                                        chicken_breed,
                                                                        send_date, province, city))
            sms_kill_request_delete_province_sms.start()
        kill_request.trash = True
        kill_request.save()

        return Response('request deleted', status=status.HTTP_200_OK)

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

        if 'kill_request_key' in request.data.keys():
            kill_request_instance = KillRequest.objects.filter(key=request.data['kill_request_key'],
                                                               trash=False).first()
            if kill_request_instance:
                limitation_direct_purchase = LimitationForDirectPurchaseAndBarInformation.objects.filter(
                    trash=False, active=True).first()

                if limitation_direct_purchase and limitation_direct_purchase.start_time and limitation_direct_purchase.end_time:
                    current_time = datetime.now().time()
                    if limitation_direct_purchase.start_time <= current_time <= limitation_direct_purchase.end_time:
                        record_create_time = kill_request_instance.create_date.time()
                        if not (
                                limitation_direct_purchase.start_time <= record_create_time <= limitation_direct_purchase.end_time):
                            return Response(
                                {
                                    "result": "شما فقط می‌توانید بارهایی که در بازه زمانی مجاز ثبت شده‌اند را ویرایش کنید!"},
                                status=status.HTTP_403_FORBIDDEN)

        if 'role' in request.data.keys():
            kill_request = KillRequest.objects.get(key=request.data['kill_request_key'])
            if kill_request.trash:
                return Response({"result": "به علت بدهی درخواست شما حذف گردید!"}, status=status.HTTP_403_FORBIDDEN)
            if request.data['role'] == 'KillHouse':
                if kill_request.direct_buying_state != 'pending':
                    return Response({"result": "به علت تایید یا رد استان شما نمیتوانیددرخواست رو ویرایش کنید"})
            request.data.pop('role')
            request.data.pop('kill_request_key')
            if 'input_direct_buying_code' in request.data.keys():
                if request.data['input_direct_buying_code'] != None or request.data['input_direct_buying_code'] != "":
                    if request.data['input_direct_buying_code'] != kill_request.direct_buying_code:
                        return Response({"result": "کد وارد شده صحیح نمی باشد"}, status=status.HTTP_403_FORBIDDEN)

                user = SystemUserProfile.objects.get(user=request.user, trash=False)
                now = datetime.now().time().replace(second=0, microsecond=0)

                free_sale_in_province = False if kill_request.free_direct_buying == False else True

                permission_duirect_buying = AutomaticDirectBuyingPermission.objects.first()

                if permission_duirect_buying.allow == True and permission_duirect_buying.start_time < \
                        now < permission_duirect_buying.end_time:
                    # kill_request.kill_capacity = int(request.data['quantity'])
                    # kill_request.remain_quantity = int(request.data['quantity'])
                    # kill_request.save()
                    # request.data.pop('quantity')
                    poultry_requests = PoultryRequest.objects.filter(poultry__user=kill_request.poultry.user,
                                                                     trash=False).order_by(
                        'create_date')

                    if kill_request.poultry_hatching:
                        hatching = kill_request.poultry_hatching
                    else:

                        hatching = PoultryHatching.objects.filter(poultry=kill_request.poultry, state='pending',
                                                                  archive=False,
                                                                  allow_hatching='pending', trash=False).order_by(
                            'id').last()

                    poultry = Poultry.objects.get(key=kill_request.poultry.key, trash=False)
                    vet_farm = VetFarm.objects.filter(trash=False, poultry=poultry).first()
                    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

                    if poultry_requests.count() > 0:
                        order_code = poultry_requests.last().order_code + 1
                    else:
                        order_code = int(str(poultry.user.base_order) + '0001')
                    city_operator = CityOperator.objects.filter(unit_name=poultry.city_operator, trash=False).last()
                    if not city_operator:
                        city_operator = CityOperator.objects.filter(unit_name='اتحادیه استان (فاقد تعاونی)',
                                                                    trash=False).last()
                    if hatching.left_over < kill_request.kill_capacity:
                        return Response({"result": "تعداد جوجه در سالن کمتر از تعداد درخواستی است"},
                                        status=status.HTTP_403_FORBIDDEN)

                    if kill_request.kill_house.max_kill_limit and kill_request.kill_house.total_kill_capacity > 0:
                        total_province_kill_requests = ProvinceKillRequest.objects.filter(trash=False,
                                                                                          return_to_province=False,
                                                                                          archive_wage=False,
                                                                                          state__in=(
                                                                                              'pending', 'accepted'),
                                                                                          killhouse_user=kill_request.kill_house,
                                                                                          kill_request__recive_date__date=kill_request.recive_date.date())
                        total_province_kill_requests_quantity = \
                            total_province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total'] or 0
                        if kill_request.kill_house.total_kill_capacity < total_province_kill_requests_quantity + kill_request.kill_capacity:
                            return Response(
                                {"result": "تعداد وارد شده از مانده سهمیه کشتار روزانه کشتارگاه بیشتر است !"},
                                status=status.HTTP_403_FORBIDDEN)

                    poultry_request = PoultryRequest(
                        hatching=hatching,
                        order_code=order_code,
                        general_order_code=general_order_code,
                        city_operator=city_operator,
                        poultry=poultry,
                        previous_quantity=kill_request.kill_capacity,
                        remain_quantity=kill_request.kill_capacity,
                        quantity=kill_request.kill_capacity,
                        first_quantity=kill_request.kill_capacity,
                        chicken_breed=hatching.chicken_breed,
                        Index_weight=kill_request.Index_weight,
                        state_process='accepted',
                        province_state='accepted',
                        direct_buying=True,
                        amount=kill_request.amount,
                        free_sale_in_province=free_sale_in_province,
                        send_date=kill_request.recive_date
                    )
                    if kill_request.freezing:
                        poultry_request.freezing = True

                    poultry_request.save()
                    kill_request.poultry_request = poultry_request
                    poultry_prediction(poultry_request.poultry)

                    if kill_request.export_status == True:
                        poultry_request.export = True

                    send_date_str = poultry_request.send_date

                    if isinstance(send_date_str, str):
                        # حذف میلی‌ثانیه و کاراکترهای اضافی
                        clean_date_str = send_date_str.split('.')[0]  # حذف بخش .759000
                        clean_date_str = clean_date_str.replace('T', ' ')  # جایگزینی T با فاصله
                        clean_date_str = clean_date_str.replace('Z', '')  # حذف Z اگر وجود دارد

                        # تبدیل به تاریخ میلادی
                        send_date_datetime = datetime.strptime(clean_date_str, '%Y-%m-%d %H:%M:%S').date()

                    # اگر از قبل شی datetime است
                    elif isinstance(send_date_str, datetime):
                        send_date_datetime = send_date_str.date()

                    # send_date_datetime = datetime.strptime(str(send_date_str), '%Y-%m-%dT%H:%M:%S.%fZ')
                    poultry_request.killing_age = (send_date_datetime - hatching.date.date()).days + 1

                    poultry_request.state = {
                        "city_operator": city_operator.user.fullname,
                        "city_state": poultry_request.state_process,
                        "city_operator_mobile": city_operator.user.mobile,
                        "province_operator": "",
                        "province_state": ""
                    }
                    poultry_request.registrar = {
                        "role": 'KillHouse',
                        "fullname": user.fullname,
                        "date": str(poultry_request.create_date)
                    }
                    poultry_request.save()

                    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()
                    wage_type = WageType.objects.filter(en_name='province-kill-request', trash=False).first()
                    wage = wage_type.amount if wage_type.status == True else 0
                    percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0,
                                                                                trash=False)
                    province_killrequest = ProvinceKillRequest(
                        killhouse_user=kill_request.kill_house,
                        kill_request=kill_request,
                        province_request=check,
                        quantity=kill_request.kill_capacity,
                        total_killed_quantity=kill_request.kill_capacity,
                        total_killed_weight=int(kill_request.kill_capacity * poultry_request.Index_weight),
                        main_quantity=kill_request.kill_capacity,
                        wage=wage,
                        direct_buying=True,
                        total_wage_amount=wage * int(kill_request.kill_capacity * poultry_request.Index_weight),
                    )
                    province_killrequest.save()
                    # fine = FinePermission.objects.filter(trash=False).first()
                    # time_for_fine = datetime.now()
                    # time_for_fine = time_for_fine.replace(second=0, microsecond=0).time()
                    # if fine.direct_buying:
                    #     if fine.direct_buying_start_time < time_for_fine < fine.direct_buying_end_time:
                    #         province_killrequest.direct_buying_fine = True
                    #         province_killrequest.direct_buying_fine_amount = (
                    #                                                                  fine.direct_buying_fine_coefficient - 1) * province_killrequest.total_wage_amount if fine.direct_buying_fine_coefficient > 1 else province_killrequest.total_wage_amount
                    #         province_killrequest.direct_buying_fine_coefficient = fine.direct_buying_fine_coefficient
                    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':
                                province_killrequest.union_share = int(
                                    (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                province_killrequest.union_share_percent = percentage_wage_type.percent

                            elif percentage_wage_type.share_type.en_name == 'company':
                                province_killrequest.company_share = int(
                                    (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                province_killrequest.company_share_percent = percentage_wage_type.percent

                            elif percentage_wage_type.share_type.en_name == 'guilds':
                                province_killrequest.guilds_share = int(
                                    (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                province_killrequest.guilds_share_percent = percentage_wage_type.percent

                            elif percentage_wage_type.share_type.en_name == 'city':
                                province_killrequest.city_share = int(
                                    (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                province_killrequest.city_share_percent = percentage_wage_type.percent

                            elif percentage_wage_type.share_type.en_name == 'other':
                                province_killrequest.other_share = int(
                                    (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                province_killrequest.other_share_percent = percentage_wage_type.percent

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

                            else:
                                province_killrequest.other_share = int(
                                    (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                province_killrequest.other_share_percent = percentage_wage_type.percent
                            province_killrequest.save()

                    tomorrow = datetime.now().date() + timedelta(days=1)
                    if not KillHouseWareHouse.objects.filter(kill_house=kill_request.kill_house,
                                                             date__date=tomorrow).exists():
                        ware_house_date = datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=1,
                                                   minute=12, second=20)
                        kill_house_ware_house = KillHouseWareHouse(
                            kill_house=kill_request.kill_house,
                            date=ware_house_date
                        )
                        kill_house_ware_house.save()
                    kill_house_check = KillHouseCheckRequest(
                        province_kill_request=province_killrequest,
                        state='accepted'
                    )

                    kill_house_check.save()
                    province_killrequest.state = 'accepted'

                    if kill_request.payment_deadline:
                        province_killrequest.payment_deadline = True
                        province_killrequest.payment_deadline_date = kill_request.payment_deadline_date
                    province_killrequest.save()
                    check.quantity = 0
                    check.save()

                    if poultry_request.export == True:
                        hatching.export_killed_weight += int(kill_request.kill_capacity * poultry_request.Index_weight)
                        hatching.export_killed_quantity += kill_request.kill_capacity


                    elif poultry_request.free_sale_in_province == True:
                        hatching.free_killed_quantity += int(kill_request.kill_capacity * poultry_request.Index_weight)
                        hatching.free_quantity += kill_request.kill_capacity

                    else:
                        hatching.governmental_killed_quantity += int(
                            kill_request.kill_capacity * poultry_request.Index_weight)
                        hatching.governmental_quantity += kill_request.kill_capacity
                    hatching.killed_quantity += kill_request.kill_capacity
                    hatching.save()
                    poultry_request.remain_quantity = 0
                    poultry_request.direct_buying_kill_place = kill_request.kill_house.name
                    poultry_request.direct_buying_buyer_info = {
                        "buyer_fullname": kill_request.kill_house.kill_house_operator.user.fullname,
                        "buyer_mobile": kill_request.kill_house.kill_house_operator.user.mobile,
                    }
                    poultry_request.save()
                    if kill_request.export_status == True:
                        kill_request.export_state = 'accepted'
                        kill_request.direct_buying_message = request.data['direct_buying_message']

                    else:
                        kill_request.direct_buying_state = 'accepted'

                    kill_request.accept_reject_date = datetime.now()
                    kill_request.automatic_accept = True
                    kill_request.input_direct_buying_code = request.data['input_direct_buying_code']
                    kill_request.save()
                    bot_eitaa_for_each_province_kill_request(province_killrequest, vet_farm)
                    return Response({"result": "درخواست شما با موفقیت تایید و ارسال شد."},
                                    status=status.HTTP_201_CREATED)
            if 'input_export_code' in request.data.keys():
                if request.data['input_export_code'] != None or request.data['input_export_code'] != "":
                    if request.data['input_export_code'] != kill_request.export_code:
                        return Response({"result": "کد وارد شده صحیح نمی باشد"}, status=status.HTTP_403_FORBIDDEN)

            if 'final_accept' in request.data.keys():

                user = SystemUserProfile.objects.get(user=request.user, trash=False)
                kill_request.final_accept = True
                now = datetime.now().time().replace(second=0, microsecond=0)
                price_confirmation = PriceConfirmation.objects.filter(trash=False).first()
                price_confirmation = price_confirmation.poultry_status if price_confirmation else False
                buying_verification = DirectBuyingVerification.objects.filter(trash=False).first()

                if buying_verification.poultry_code_mandatory:
                    poultry_fullname = kill_request.poultry.unit_name
                    poultry_mobile = kill_request.poultry.user.mobile if not kill_request.direct_buying_intermediary_mobile else kill_request.direct_buying_intermediary_mobile
                    quantity = kill_request.kill_capacity
                    chicken_breed = kill_request.chicken_breed
                    request_kill_house = kill_request.kill_house.name
                    date_str = kill_request.recive_date
                    # clean_date_str = date_str.split('T')[0] + ' ' + date_str.split('T')[1].split('.')[0]

                    # send_date = 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)

                    if isinstance(date_str, str):
                        clean_date_str = date_str.split('.')[0]
                        clean_date_str = clean_date_str.replace('T', ' ')
                        clean_date_str = clean_date_str.replace('Z', '')

                        send_date = datetime.strptime(clean_date_str, '%Y-%m-%d %H:%M:%S').date()

                    elif isinstance(date_str, datetime):
                        send_date = date_str.date()

                    jalali_date = jdatetime.date.fromgregorian(
                        year=send_date.year,
                        month=send_date.month,
                        day=send_date.day
                    )

                    formatted_jalali = jalali_date.strftime('%Y-%m-%d')

                    date_parts = formatted_jalali.split('-')
                    send_date = '-'.join(reversed(date_parts))

                    confirm_price_poultry_request = threading.Thread(
                        target=confirm_price_poultry_request_direct_buying_sms,
                        args=(
                            poultry_mobile, poultry_fullname,
                            quantity, chicken_breed,
                            send_date,
                            kill_request.free_direct_buying,
                            kill_request.amount, request_kill_house,
                            kill_request.direct_buying_code))
                    confirm_price_poultry_request.start()
                    kill_request.price_confirmation = price_confirmation
                    kill_request.save()
                    return Response({"result": "درخواست شما با موفقیت تایید و ارسال شد."},
                                    status=status.HTTP_201_CREATED)
                else:
                    free_sale_in_province = False if kill_request.free_direct_buying == False else True

                    permission_duirect_buying = AutomaticDirectBuyingPermission.objects.first()

                    if permission_duirect_buying.allow == True and permission_duirect_buying.start_time < \
                            now < permission_duirect_buying.end_time:
                        # kill_request.kill_capacity = int(request.data['quantity'])
                        # kill_request.remain_quantity = int(request.data['quantity'])
                        # kill_request.save()
                        # request.data.pop('quantity')
                        poultry_requests = PoultryRequest.objects.filter(poultry__user=kill_request.poultry.user,
                                                                         trash=False).order_by(
                            'create_date')

                        if kill_request.poultry_hatching:
                            hatching = kill_request.poultry_hatching
                        else:

                            hatching = PoultryHatching.objects.filter(poultry=kill_request.poultry, state='pending',
                                                                      archive=False,
                                                                      allow_hatching='pending', trash=False).order_by(
                                'id').last()
                        # hatching = PoultryHatching.objects.filter(poultry=kill_request.poultry, state='pending',
                        #                                           archive=False,
                        #                                           allow_hatching='pending', trash=False).order_by(
                        #     'left_over').last()

                        poultry = Poultry.objects.get(key=kill_request.poultry.key, trash=False)
                        vet_farm = VetFarm.objects.filter(trash=False, poultry=poultry).first()
                        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

                        if poultry_requests.count() > 0:
                            order_code = poultry_requests.last().order_code + 1
                        else:
                            order_code = int(str(poultry.user.base_order) + '0001')
                        city_operator = CityOperator.objects.filter(unit_name=poultry.city_operator, trash=False).last()
                        if not city_operator:
                            city_operator = CityOperator.objects.filter(unit_name='اتحادیه استان (فاقد تعاونی)',
                                                                        trash=False).last()
                        if hatching.left_over < kill_request.kill_capacity:
                            return Response({"result": "تعداد جوجه در سالن کمتر از تعداد درخواستی است"},
                                            status=status.HTTP_403_FORBIDDEN)

                        if kill_request.kill_house.max_kill_limit and kill_request.kill_house.total_kill_capacity > 0:
                            total_province_kill_requests = ProvinceKillRequest.objects.filter(trash=False,
                                                                                              return_to_province=False,
                                                                                              archive_wage=False,
                                                                                              state__in=(
                                                                                                  'pending',
                                                                                                  'accepted'),
                                                                                              killhouse_user=kill_request.kill_house,
                                                                                              kill_request__recive_date__date=kill_request.recive_date.date())
                            total_province_kill_requests_quantity = \
                                total_province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total'] or 0
                            if kill_request.kill_house.total_kill_capacity < total_province_kill_requests_quantity + kill_request.kill_capacity:
                                return Response(
                                    {"result": "تعداد وارد شده از مانده سهمیه کشتار روزانه کشتارگاه بیشتر است !"},
                                    status=status.HTTP_403_FORBIDDEN)

                        poultry_request = PoultryRequest(
                            hatching=hatching,
                            order_code=order_code,
                            general_order_code=general_order_code,
                            city_operator=city_operator,
                            poultry=poultry,
                            previous_quantity=kill_request.kill_capacity,
                            remain_quantity=kill_request.kill_capacity,
                            quantity=kill_request.kill_capacity,
                            first_quantity=kill_request.kill_capacity,
                            chicken_breed=hatching.chicken_breed,
                            Index_weight=kill_request.Index_weight,
                            state_process='accepted',
                            province_state='accepted',
                            direct_buying=True,
                            amount=kill_request.amount,
                            free_sale_in_province=free_sale_in_province,
                            send_date=kill_request.recive_date
                        )
                        if kill_request.freezing:
                            poultry_request.freezing = True

                        poultry_request.save()
                        kill_request.poultry_request = poultry_request
                        poultry_prediction(poultry_request.poultry)

                        if kill_request.export_status == True:
                            poultry_request.export = True
                        date_str = poultry_request.send_date
                        if isinstance(date_str, str):
                            # حذف میلی‌ثانیه و کاراکترهای اضافی
                            clean_date_str = date_str.split('.')[0]  # حذف بخش .759000
                            clean_date_str = clean_date_str.replace('T', ' ')  # جایگزینی T با فاصله
                            clean_date_str = clean_date_str.replace('Z', '')  # حذف Z اگر وجود دارد

                            # تبدیل به تاریخ میلادی
                            send_date_datetime = datetime.strptime(clean_date_str, '%Y-%m-%d %H:%M:%S').date()

                        # اگر از قبل شی datetime است
                        elif isinstance(date_str, datetime):
                            send_date_datetime = date_str.date()
                        # send_date_datetime = datetime.strptime(str(send_date_str), '%Y-%m-%dT%H:%M:%S')
                        poultry_request.killing_age = (send_date_datetime - hatching.date.date()).days + 1

                        poultry_request.state = {
                            "city_operator": city_operator.user.fullname,
                            "city_state": poultry_request.state_process,
                            "city_operator_mobile": city_operator.user.mobile,
                            "province_operator": "",
                            "province_state": ""
                        }
                        poultry_request.registrar = {
                            "role": "KillHouse",
                            "fullname": user.fullname,
                            "date": str(poultry_request.create_date)
                        }
                        poultry_request.save()

                        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()
                        wage_type = WageType.objects.filter(en_name='province-kill-request', trash=False).first()
                        wage = wage_type.amount if wage_type.status == True else 0
                        percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0,
                                                                                    trash=False)
                        province_killrequest = ProvinceKillRequest(
                            killhouse_user=kill_request.kill_house,
                            kill_request=kill_request,
                            province_request=check,
                            quantity=kill_request.kill_capacity,
                            total_killed_quantity=kill_request.kill_capacity,
                            total_killed_weight=int(kill_request.kill_capacity * poultry_request.Index_weight),
                            main_quantity=kill_request.kill_capacity,
                            wage=wage,
                            direct_buying=True,
                            total_wage_amount=wage * int(kill_request.kill_capacity * poultry_request.Index_weight),
                        )
                        province_killrequest.save()
                        # fine = FinePermission.objects.filter(trash=False).first()
                        # time_for_fine = datetime.now()
                        # time_for_fine = time_for_fine.replace(second=0, microsecond=0).time()
                        # if fine.direct_buying:
                        #     if fine.direct_buying_start_time < time_for_fine < fine.direct_buying_end_time:
                        #         province_killrequest.direct_buying_fine = True
                        #         province_killrequest.direct_buying_fine_amount = (
                        #                                                                  fine.direct_buying_fine_coefficient - 1) * province_killrequest.total_wage_amount if fine.direct_buying_fine_coefficient > 1 else province_killrequest.total_wage_amount
                        #         province_killrequest.direct_buying_fine_coefficient = fine.direct_buying_fine_coefficient
                        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':
                                    province_killrequest.union_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.union_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'company':
                                    province_killrequest.company_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.company_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'guilds':
                                    province_killrequest.guilds_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.guilds_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'city':
                                    province_killrequest.city_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.city_share_percent = percentage_wage_type.percent

                                elif percentage_wage_type.share_type.en_name == 'other':
                                    province_killrequest.other_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.other_share_percent = percentage_wage_type.percent

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

                                else:
                                    province_killrequest.other_share = int(
                                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                                    province_killrequest.other_share_percent = percentage_wage_type.percent
                                province_killrequest.save()

                        tomorrow = datetime.now().date() + timedelta(days=1)
                        if not KillHouseWareHouse.objects.filter(kill_house=kill_request.kill_house,
                                                                 date__date=tomorrow).exists():
                            ware_house_date = datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day,
                                                       hour=1,
                                                       minute=12, second=20)
                            kill_house_ware_house = KillHouseWareHouse(
                                kill_house=kill_request.kill_house,
                                date=ware_house_date
                            )
                            kill_house_ware_house.save()
                        kill_house_check = KillHouseCheckRequest(
                            province_kill_request=province_killrequest,
                            state='accepted'
                        )

                        kill_house_check.save()
                        province_killrequest.state = 'accepted'
                        if kill_request.payment_deadline:
                            province_killrequest.payment_deadline = True
                            province_killrequest.payment_deadline_date = kill_request.payment_deadline_date
                        province_killrequest.save()
                        check.quantity = 0
                        check.save()

                        if poultry_request.export == True:
                            hatching.export_killed_weight += int(
                                kill_request.kill_capacity * poultry_request.Index_weight)
                            hatching.export_killed_quantity += kill_request.kill_capacity


                        elif poultry_request.free_sale_in_province == True:
                            hatching.free_killed_quantity += int(
                                kill_request.kill_capacity * poultry_request.Index_weight)
                            hatching.free_quantity += kill_request.kill_capacity

                        else:
                            hatching.governmental_killed_quantity += int(
                                kill_request.kill_capacity * poultry_request.Index_weight)
                            hatching.governmental_quantity += kill_request.kill_capacity
                        hatching.killed_quantity += kill_request.kill_capacity
                        hatching.save()
                        poultry_request.remain_quantity = 0
                        poultry_request.direct_buying_kill_place = kill_request.kill_house.name
                        poultry_request.direct_buying_buyer_info = {
                            "buyer_fullname": kill_request.kill_house.kill_house_operator.user.fullname,
                            "buyer_mobile": kill_request.kill_house.kill_house_operator.user.mobile,
                        }
                        poultry_request.save()
                        if kill_request.export_status == True:
                            kill_request.export_state = 'accepted'
                            kill_request.direct_buying_message = request.data['direct_buying_message']

                        else:
                            kill_request.direct_buying_state = 'accepted'

                        kill_request.accept_reject_date = datetime.now()
                        kill_request.automatic_accept = True

                        kill_request.save()
                        poultry_fullname = poultry.unit_name
                        poultry_mobile = poultry.user.mobile if not kill_request.direct_buying_intermediary_mobile else kill_request.direct_buying_intermediary_mobile
                        quantity = kill_request.kill_capacity
                        chicken_breed = kill_request.chicken_breed
                        request_kill_house = kill_request.kill_house.name
                        date_str = kill_request.recive_date
                        if isinstance(date_str, str):
                            clean_date_str = date_str.split('T')[0] + ' ' + date_str.split('T')[1].split('.')[0]
                        else:
                            clean_date_str = date_str.strftime('%Y-%m-%d %H:%M:%S')
                        send_date = datetime.strptime(str(clean_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 = "-"
                        code = "-"
                        send_date = separate.join(date_list)
                        confirm_price_poultry_request = threading.Thread(
                            target=confirm_price_poultry_request_direct_buying_sms,
                            args=(
                                poultry_mobile, poultry_fullname,
                                quantity, chicken_breed,
                                send_date,
                                kill_request.free_direct_buying,
                                kill_request.amount, request_kill_house,
                                code))
                        confirm_price_poultry_request.start()

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



                    else:
                        poultry = Poultry.objects.get(key=kill_request.poultry.key, trash=False)
                        poultry_fullname = poultry.unit_name
                        poultry_mobile = poultry.user.mobile if not kill_request.direct_buying_intermediary_mobile else kill_request.direct_buying_intermediary_mobile
                        quantity = kill_request.kill_capacity
                        chicken_breed = kill_request.chicken_breed
                        request_kill_house = kill_request.kill_house.name
                        date_str = kill_request.recive_date
                        if isinstance(date_str, str):
                            clean_date_str = date_str.split('T')[0] + ' ' + date_str.split('T')[1].split('.')[0]
                        else:
                            clean_date_str = date_str.strftime('%Y-%m-%d %H:%M:%S')
                        send_date = datetime.strptime(str(clean_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 = "-"
                        code = "-"
                        send_date = separate.join(date_list)
                        confirm_price_poultry_request = threading.Thread(
                            target=confirm_price_poultry_request_direct_buying_sms,
                            args=(
                                poultry_mobile, poultry_fullname,
                                quantity, chicken_breed,
                                send_date,
                                kill_request.free_direct_buying,
                                kill_request.amount, request_kill_house,
                                code))
                        confirm_price_poultry_request.start()
                        kill_request.save()
                        return Response({"result": "درخواست شما با موفقیت تایید و ارسال شد."},
                                        status=status.HTTP_201_CREATED)
            kill_request.save()
            serializer = self.serializer_class(data=request.data)
            if serializer.is_valid():
                serializer.update(instance=kill_request, validated_data=request.data)
                return Response({"result": "با موفقیت ویرایش شد"}, status=status.HTTP_200_OK)
            else:
                return Response({"result": "در ثبت مقادیر مشکلی به وجود آمده است !"}, status=status.HTTP_403_FORBIDDEN)

        if 'previous_requests' in request.data.keys():
            now = datetime.now().date()
            user = SystemUserProfile.objects.get(user=request.user)
            querysets_list = KillRequest.objects.filter(
                kill_house__system_address__province=user.province,
                trash=False, remain_quantity__gt=0).order_by('-recive_date')
            for queryset in querysets_list:
                if (now - queryset.recive_date.date()).days > 2:
                    queryset.remain_quantity = 0
                    queryset.save()
            return Response({"result": "با موفقیت ثبت شد"},
                            status=status.HTTP_200_OK)

        province_kill_request_quantity = 0
        kill_request = KillRequest.objects.get(key=request.data["kill_request_key"], trash=False)
        request.data.pop('kill_request_key')
        quantity = int(request.data['quantity'])
        request.data.pop('quantity')
        province_kill_requests = ProvinceKillRequest.objects.filter(kill_request=kill_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 int(quantity) < kill_request.kill_capacity:
                kill_request.remain_quantity -= kill_request.kill_capacity - int(quantity)
            else:
                kill_request.remain_quantity += int(quantity) - kill_request.kill_capacity
        else:
            kill_request.remain_quantity = int(quantity)

        kill_request.kill_capacity = int(quantity)
        kill_request.save()
        serializer = self.serializer_class(kill_request)
        serializer.update(instance=kill_request, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillRequestFactorViewSet(viewsets.ModelViewSet):
    queryset = KillRequestFactor.objects.all()
    serializer_class = KillRequestFactorSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        date1 = datetime.strptime(str(request.GET['date1']),
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(str(request.GET['date2']),
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        user_profile = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_user = get_object_or_404(KillHouseOperator, user=user_profile)
        kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_user)

        factor_list = KillRequestFactor.objects.filter(kill_request__kill_house__in=kill_house, trash=False).order_by(
            'id')
        factors = [
            kill_request_factor for kill_request_factor in factor_list
            if date1 <= kill_request_factor.kill_request.recive_date.date() <= date2
        ]
        serializer = KillRequestFactorSerializer(factors, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        if 'state' in request.data:
            if request.data['state'] == 'cancel':
                factor = KillRequestFactor.objects.get(key=request.data['factor_key'], trash=False)
                kill_request = KillRequest.objects.get(key=factor.kill_request.key)
                kill_request.trash = True
                kill_request.save()
                factor.trash = True
                factor.save()
            return Response({"result": "done!"}, status=status.HTTP_200_OK)


class KillRequestFactorPaymentViewSet(viewsets.ModelViewSet):
    queryset = KillRequestFactorPayment.objects.all()
    serializer_class = KillRequestFactorPaymentSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        factor = KillRequestFactor.objects.get(key=request.data['factor_key'], trash=False)
        kill_request = KillRequest.objects.get(key=factor.kill_request.key)
        kill_house = KillHouse.objects.get(key=kill_request.kill_house.key)
        request.data.pop('factor_key')
        image = request.data['image']
        request.data.pop('image')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            factor_payment = serializer.create(validated_data=request.data)
            factor_payment.kill_request_factor = factor
            factor_payment.image = send_image_to_server(image)
            factor_payment.remain_amount = float(request.data['amount'])
            factor_payment.state = 'paid'
            factor_payment.save()
            factor.state = 'paid'
            factor.save()
            kill_request.payment_info = {
                "amount": factor_payment.amount,
                "total_amount": factor.amount,
                "image": factor_payment.image,
                "date": str(factor_payment.create_date)
            }
            kill_request.factor_deposit = factor_payment.amount
            kill_request.save()
            kill_house.wallet_amount += factor_payment.amount
            kill_house.save()

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


def update_province_kill_request():
    wage = ShareOfAllocation.objects.all().last()
    wage = wage.province_union if wage else 0
    for province_kill_request in ProvinceKillRequest.objects.all():
        province_request = ProvinceCheckOperatorRequest.objects.filter(
            key=province_kill_request.province_request.key).last()
        province_kill_request.total_amount = wage * (
                province_kill_request.main_quantity * province_request.poultry_request.Index_weight)
        province_kill_request.save()


from django.db import models, transaction
from django.db.models import Sum, Count, F


# ... (previous code)

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

    def list(self, request, *args, **kwargs):
        province_kill_requests = ProvinceKillRequest.objects.filter(
            trash=False, return_to_province=False, state__in=('accepted', 'pending')
        ).annotate(
            total_quantity=Sum('total_killed_quantity'),
            total_weight=Sum('total_killed_weight'),
            total_amount_wage=Sum(
                F('wage') * F('total_killed_weight')),
            total_paid=Count('id', filter=models.Q(wage_pay=True, archive_by_province=False)),
            total_unpaid=Count('id', filter=models.Q(wage_pay=False, archive_by_province=False)),
            total_archive=Count('id', filter=models.Q(wage_pay=False, archive_by_province=True)),
            # total_kill_houses=Count('kill_request__kill_house', distinct=True)
        )

        total_requests_buyers = province_kill_requests.values('kill_request__kill_house').distinct().count()
        total_requests = province_kill_requests.count()
        total_requests_quantity = province_kill_requests.aggregate(total=Sum('total_quantity'))['total']
        total_requests_weight = province_kill_requests.aggregate(total=Sum('total_weight'))['total']
        total_requests_amount = province_kill_requests.aggregate(total=Sum('total_amount_wage'))['total']
        total_paid_requests = province_kill_requests.aggregate(total=Sum('total_paid'))['total']
        total_paid_requests_quantity = \
            province_kill_requests.filter(wage_pay=True).aggregate(total=Sum('total_quantity'))['total']
        total_paid_requests_weight = province_kill_requests.filter(wage_pay=True).aggregate(total=Sum('total_weight'))[
            'total']
        total_paid_requests_amount = \
            province_kill_requests.filter(wage_pay=True).aggregate(total=Sum('total_amount_wage'))['total']
        total_unpaid_requests = province_kill_requests.aggregate(total=Sum('total_unpaid'))['total']
        total_unpaid_requests_quantity = \
            province_kill_requests.filter(wage_pay=False, archive_by_province=False).aggregate(
                total=Sum('total_quantity'))['total']
        total_unpaid_requests_weight = \
            province_kill_requests.filter(wage_pay=False, archive_by_province=False).aggregate(
                total=Sum('total_weight'))['total']
        total_unpaid_requests_amount = \
            province_kill_requests.filter(wage_pay=False, archive_by_province=False).aggregate(
                total=Sum('total_amount_wage'))['total']

        total_archive_requests = province_kill_requests.aggregate(total=Sum('total_archive'))['total']
        total_archive_requests_quantity = \
            province_kill_requests.filter(wage_pay=False, archive_by_province=True).aggregate(
                total=Sum('total_quantity'))['total']
        total_archive_requests_weight = \
            province_kill_requests.filter(wage_pay=False, archive_by_province=True).aggregate(
                total=Sum('total_weight'))['total']
        total_archive_requests_amount = \
            province_kill_requests.filter(wage_pay=False, archive_by_province=True).aggregate(
                total=Sum('total_amount_wage'))['total']
        total_free_request = province_kill_requests.filter(
            province_request__poultry_request__free_sale_in_province=True)
        total_free_request_quantity = total_free_request.aggregate(total=Sum('total_quantity'))['total']
        total_free_request_weight = total_free_request.aggregate(total=Sum('total_weight'))['total']

        total_government_request = province_kill_requests.filter(
            province_request__poultry_request__free_sale_in_province=False)
        total_government_request_quantity = total_government_request.aggregate(total=Sum('total_quantity'))['total']
        total_government_request_weight = total_government_request.aggregate(total=Sum('total_weight'))['total']

        return Response({
            "total_requests_buyers": total_requests_buyers,
            "total_requests": total_requests,
            "total_requests_quantity": total_requests_quantity,
            "total_requests_weight": total_requests_weight,
            "total_requests_amount": total_requests_amount,
            "total_paid_requests": total_paid_requests,
            "total_paid_requests_quantity": total_paid_requests_quantity if total_paid_requests_quantity != None else 0,
            "total_paid_requests_weight": total_paid_requests_weight if total_paid_requests_weight != None else 0,
            "total_paid_requests_amount": total_paid_requests_amount if total_paid_requests_amount != None else 0,
            "total_unpaid_requests": total_unpaid_requests,
            "total_unpaid_requests_quantity": total_unpaid_requests_quantity,
            "total_unpaid_requests_weight": total_unpaid_requests_weight,
            "total_unpaid_requests_amount": total_unpaid_requests_amount,
            "total_archive_requests": total_archive_requests,
            "total_archive_requests_quantity": total_archive_requests_quantity,
            "total_archive_requests_weight": total_archive_requests_weight,
            "total_archive_requests_amount": total_archive_requests_amount,
            "total_free_request": len(total_free_request),
            "total_free_request_quantity": total_free_request_quantity,
            "total_free_request_weight": total_free_request_weight,
            "total_government_request": len(total_government_request),
            "total_government_request_quantity": total_government_request_quantity,
            "total_government_request_weight": total_government_request_weight,

        }, status=status.HTTP_200_OK)


def provincearchiveprovincekillrequestforwage(province_kill_request_list, message, role, user_fullname, date):
    province_kill_requests = ProvinceKillRequest.objects.filter(key__in=province_kill_request_list,
                                                                trash=False)
    for province_kill_request in province_kill_requests:
        province_kill_request.archive_by_province = True
        province_kill_request.archive_message = message
        province_kill_request.archiver = {
            "role": role,
            "fullname": user_fullname,
            "date": date,
        }
        province_kill_request.save()


# class ReportingProvinceKillRequestsWageViewSet(viewsets.ModelViewSet):
#     queryset = ProvinceKillRequest.objects.all()
#     serializer_class = ProvinceKillRequestSerializer
#     permission_classes = [TokenHasReadWriteScope]
#
#     def list(self, request, *args, **kwargs):
#         total_requests_buyers = 0
#         total_requests = 0
#         total_requests_quantity = 0
#         total_requests_weight = 0
#         total_requests_amount = 0
#         total_paid_requests = 0
#         total_paid_requests_quantity = 0
#         total_paid_requests_weight = 0
#         total_paid_requests_amount = 0
#         total_unpaid_requests = 0
#         total_unpaid_requests_quantity = 0
#         total_unpaid_requests_weight = 0
#         total_unpaid_requests_amount = 0
#         province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, state__in=('accepted', 'pending'))
#         for province_kill_request in province_kill_requests:
#             if province_kill_request.wage_pay == True:
#                 total_paid_requests +=1
#                 total_paid_requests_quantity += province_kill_request.main_quantity
#                 total_paid_requests_weight += int(province_kill_request.main_quantity * province_kill_request.province_request.poultry_request.Index_weight)
#                 total_paid_requests_amount += int(province_kill_request.wage * (province_kill_request.main_quantity * province_kill_request.province_request.poultry_request.Index_weight))
#             else:
#
#                 total_unpaid_requests +=1
#                 total_unpaid_requests_quantity += province_kill_request.main_quantity
#                 total_unpaid_requests_weight += int(province_kill_request.main_quantity * province_kill_request.province_request.poultry_request.Index_weight)
#                 total_unpaid_requests_amount += int(province_kill_request.wage * (province_kill_request.main_quantity * province_kill_request.province_request.poultry_request.Index_weight))
#
#         total_requests_buyers = len(province_kill_requests)
#         total_requests = total_paid_requests + total_unpaid_requests
#         total_requests_quantity = total_paid_requests_quantity + total_unpaid_requests_quantity
#         total_requests_weight = total_paid_requests_weight + total_unpaid_requests_weight
#         total_requests_amount = total_paid_requests_amount + total_unpaid_requests_amount
#
#
#         return Response({
#
#             "total_requests_buyers":total_requests_buyers,
#             "total_requests":total_requests,
#             "total_requests_quantity" :total_requests_quantity,
#             "total_requests_weight":total_requests_weight,
#             "total_requests_amount":total_requests_amount,
#             "total_paid_requests":total_paid_requests,
#             "total_paid_requests_quantity":total_paid_requests_quantity,
#             "total_paid_requests_weight":total_paid_requests_weight,
#             "total_paid_requests_amount":total_paid_requests_amount,
#             "total_unpaid_requests":total_unpaid_requests,
#             "total_unpaid_requests_quantity":total_unpaid_requests_quantity,
#             "total_unpaid_requests_weight":total_unpaid_requests_weight,
#             "total_unpaid_requests_amount":total_unpaid_requests_amount,
#          },status=status.HTTP_200_OK
#       )


# def auto_steward_allocation(kill_house_key, quantity, weight, date):
#     kill_house = KillHouse.objects.get(key=kill_house_key, trash=False)
#     stewards = Steward.objects.filter(guilds__steward=True, trash=False).order_by('id')
#     stewards_list = []
#     allocatated_quantity = 0
#     kill_house_total_quantity = 0
#     for steward in stewards:
#         if steward.centers_allocation != None:
#             for center_allocation in steward.centers_allocation:
#                 if str(kill_house.key) == center_allocation['value']:
#                     kill_house_total_quantity += steward.allocation_limit
#                     stewards_list.append(steward)
#     if len(stewards_list) > 0:
#         for steward_list in stewards_list:
#             allocatated_quantity = (steward_list.allocation_limit / kill_house_total_quantity) * quantity
#             auto_allocation = StewardAllocation(
#                 kill_house=kill_house,
#                 steward=steward_list,
#                 number_of_carcasses=allocatated_quantity,
#                 real_number_of_carcasses=allocatated_quantity,
#                 weight_of_carcasses=int(allocatated_quantity * weight),
#                 real_weight_of_carcasses=int(allocatated_quantity * weight),
#                 type='auto',
#                 date=date
#             )
#             auto_allocation.save()
class WalletWagePaymentViewSet(viewsets.ModelViewSet):
    queryset = ProvinceKillRequest.objects.all()
    serializer_class = ProvinceKillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    # def update(self, request, *args, **kwargs):
    #     user = SystemUserProfile.objects.get(user=request.user, trash=False)
    #     province_kill_request_keys = []
    #     for province_kill_request_key in request.data['province_kill_requests']:
    #         province_kill_request_keys.append(province_kill_request_key)
    #     province_kill_requests = ProvinceKillRequest.objects.filter(
    #         key__in=province_kill_request_keys).order_by('id')
    #     kill_house = KillHouse.objects.get(key=province_kill_requests.last().killhouse_user.key, trash=False)
    #     now = datetime.now()
    #     total_amount = 0
    #
    #     for province_kill_request in province_kill_requests:
    #         province_kill_request.wage_pay = True
    #         province_kill_request.wallet_pay = True
    #         province_kill_request.depositor = {
    #             "role": request.data['role'],
    #             "payer": user.fullname,
    #             "date": str(now),
    #             "payment_type": 'wallet',
    #             "tracking_code": '-',
    #             "refId": '-',
    #             "orderId": '-',
    #             "total_amount": province_kill_request.total_killed_weight * province_kill_request.wage
    #         }
    #         province_kill_request.save()
    #         total_amount += province_kill_request.total_killed_weight * province_kill_request.wage
    #     transaction = ExternalTransaction(
    #         amount=total_amount,
    #         type="withdraw",
    #         transaction_type="wallet",
    #         status='completed',
    #         kill_house_user=kill_house.kill_house_operator.user,
    #         creator=user,
    #         receiver=user,
    #         creator_role='KillHouse',
    #         receiver_role='ProvinceOperator',
    #         payer=kill_house.kill_house_operator.user.fullname,
    #
    #     )
    #     transaction.save()
    #
    #     return Response({"result": "با موفقیت انجام شد!"}, status=status.HTTP_200_OK)


# ویوست مربوط به تخصیص به کشتارگاه توسط استان
class ProvinceKillRequestViewSet(viewsets.ModelViewSet):
    queryset = ProvinceKillRequest.objects.all()
    serializer_class = ProvinceKillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]
    filterset_class = ProvinceKillRequestNewFilterSet

    # تابع مربوط به تخصیص به کشتارگاه توسط استان
    def create(self, request, *args, **kwargs):
        wage = 0
        province_check = ProvinceCheckOperatorRequest.objects.get(key=request.data['province_check_request_key'],
                                                                  trash=False)
        if province_check.poultry_request.price_confirmation and not province_check.poultry_request.input_price_confirmation_code:
            return Response({"result": "به علت عدم ورود کد احراز مرغدار امکان تخصیص وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

        if province_check.poultry_request.freezing == True:
            wage_type = WageType.objects.filter(en_name='province-kill-request-freezing', trash=False).first()
        else:

            wage_type = WageType.objects.filter(en_name='province-kill-request', trash=False).first()
        if wage_type.status == True:
            wage = wage_type.amount
        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") == "province_kill_request" and t.get("active", False)), None)
            if time:
                start_hour = datetime.strptime(time.get("start", 0), "%H:%M:%S").time()
                end_hour = datetime.strptime(time.get("end", 0), "%H:%M:%S").time()
                current_hour = datetime.now().time().replace(second=0, microsecond=0)
                if not (start_hour < current_hour < end_hour):
                    return Response(
                        {"result": "لطفا در ساعات مجاز برای ثبت درخواست اقدام نمایید!"},
                        status=status.HTTP_403_FORBIDDEN)
        now = datetime.now().date()
        kill_request = KillRequest.objects.get(key=request.data['kill_request_key'], trash=False)
        if OperationLimitation.objects.all().first().province_allocation_limitation == True:

            if now != kill_request.recive_date.date():
                return Response({"result": "مغایرت در تاریخ اعلام نیاز کشتار گاه و تاریخ تخصیص به کشتارگاه !"},
                                status=status.HTTP_403_FORBIDDEN)
        kill_house = KillHouse.objects.get(id=kill_request.kill_house.id, trash=False)
        poultry_request = PoultryRequest.objects.get(key=province_check.poultry_request.key)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
        if hatching.left_over < int(request.data['quantity']):
            return Response({"result": "تعداد تخصیص داده شده کمتر از تعداد موجود در سالن مرغدار است!"},
                            status=status.HTTP_403_FORBIDDEN)

        request.data.pop('kill_request_key')
        request.data.pop('province_check_request_key')
        if poultry_request.send_date.year != kill_request.recive_date.year or poultry_request.send_date.month != kill_request.recive_date.month or poultry_request.send_date.day != kill_request.recive_date.day:
            return Response({"result": "تاریخ درخواست کشتارها یکی نیست!"}, status=status.HTTP_403_FORBIDDEN)
        if province_check.quantity == 0:
            return Response("forbidden", status=status.HTTP_403_FORBIDDEN)
        if int(request.data['quantity']) > kill_request.remain_quantity:
            return Response({"result": "تعداد وارد شده از مانده سهمیه بیشتر است !"}, status=status.HTTP_403_FORBIDDEN)
        if kill_house.max_kill_limit and kill_house.total_kill_capacity > 0:
            total_province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                                              archive_wage=False,
                                                                              state__in=('pending', 'accepted'),
                                                                              killhouse_user=kill_house,
                                                                              kill_request__recive_date__date=kill_request.recive_date.date())
            total_province_kill_requests_quantity = \
                total_province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total'] or 0

            if kill_house.total_kill_capacity < total_province_kill_requests_quantity + int(request.data['quantity']):
                return Response({"result": "تعداد وارد شده از مانده سهمیه کشتار روزانه کشتارگاه بیشتر است !"},
                                status=status.HTTP_403_FORBIDDEN)

        if poultry_request.free_sale_in_province == True:

            if kill_house.quota:
                kill_house_info = calculate_governmental_quota(kill_house)
                if kill_house_info == 'not_allowed':
                    return Response({"result": " امکان خرید آزاد تا تکمیل تعهد دولتی وجود ندارد!"},
                                    status=status.HTTP_403_FORBIDDEN)

        if kill_house.ware_house_remaining_weight_limitation_status:
            if kill_house.total_remain_warehouse_governmental_weight > kill_house.ware_house_remaining_weight_limitation:
                return Response({
                    "result": "باقی مانده انبار شما از حداکثر محدودیت وزن باقی مانده انبار بیشتر است !"},
                    status=status.HTTP_403_FORBIDDEN)

        if kill_house.ware_house_remaining_percent_limitation_status:
            if not check_kill_house_remain_limitation_weight(kill_house):
                return Response({
                    "result": "باقی مانده انبار شما از حداکثر محدودیت وزن باقی مانده روزانه انبار بیشتر است !"},
                    status=status.HTTP_403_FORBIDDEN)

        province_kills = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
                                                            province_request__city_request_Poultry__poultry_request_id=province_check.city_request_Poultry.poultry_request.id,
                                                            state__in=('pending', 'accepted'), trash=False)
        if province_kills.count() > 0:
            province = province_kills.last()

            if province.main_quantity == province.quantity:
                province.total_killed_quantity += int(request.data['quantity'])
                province.total_killed_weight += int(int(request.data['quantity']) * poultry_request.Index_weight)
            province.quantity += int(request.data['quantity'])
            province.main_quantity += int(request.data['quantity'])
            kill_request.remain_quantity = kill_request.remain_quantity - int(request.data['quantity'])
            kill_request.save()
            province.save()
            province_check.quantity -= int(request.data['quantity'])
            province_check.save()
            poultry_request.remain_quantity -= int(request.data['quantity'])
            poultry_request.save()
            if poultry_request.export == True:
                hatching.export_killed_weight += int(int(request.data['quantity']) * poultry_request.Index_weight)
                hatching.export_killed_quantity += int(request.data['quantity'])
            elif poultry_request.free_sale_in_province == True:
                hatching.free_killed_quantity += int(int(request.data['quantity']) * poultry_request.Index_weight)
                hatching.free_quantity += int(request.data['quantity'])
            else:
                hatching.governmental_killed_quantity += int(
                    int(request.data['quantity']) * poultry_request.Index_weight)

                hatching.governmental_quantity += int(request.data['quantity'])
            hatching.save()
            tomorrow = now + timedelta(days=1)
            if not KillHouseWareHouse.objects.filter(kill_house=kill_house, date__date=tomorrow).exists():
                ware_house_date = datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=1,
                                           minute=12, second=20)
                kill_house_ware_house = KillHouseWareHouse(
                    kill_house=kill_house,
                    date=ware_house_date
                )
                kill_house_ware_house.save()
            province.total_wage_amount = province.total_killed_weight * province.wage
            province.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':
                        province.union_share = int((percentage_wage_type.percent / 100) * province.total_wage_amount)
                        province.union_share_percent = percentage_wage_type.percent
                        province.save()
                    elif percentage_wage_type.share_type.en_name == 'company':
                        province.company_share = int((percentage_wage_type.percent / 100) * province.total_wage_amount)
                        province.company_share_percent = percentage_wage_type.percent
                        province.save()

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

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

                    elif percentage_wage_type.share_type.en_name == 'other':
                        province.other_share = int((percentage_wage_type.percent / 100) * province.total_wage_amount)
                        province.other_share_percent = percentage_wage_type.percent
                        province.save()

                    else:
                        province.other_share = int((percentage_wage_type.percent / 100) * province.total_wage_amount)
                        province.other_share_percent = percentage_wage_type.percent
                        province.save()

            return Response({"result": "object create"}, status=status.HTTP_201_CREATED)

        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            province_kill_request_list = []
            if hatching.left_over < int(request.data['quantity']):
                return Response({"result": "تعداد تخصیص داده شده بیشتر از تعداد موجود در سالن مرغدار است!"},
                                status=status.HTTP_403_FORBIDDEN)
            province_kill_request = serializer.create(validated_data=request.data)
            province_kill_request.kill_request = kill_request
            province_kill_request.province_request = province_check
            province_kill_request.wage = wage
            province_kill_request.state = "pending"
            if province_check.quantity < int(request.data['quantity']):
                province_kill_request.quantity = province_check.quantity
            province_kill_request.killhouse_user = kill_house
            province_kill_request.main_quantity = int(request.data['quantity'])
            province_kill_request.total_killed_quantity = province_kill_request.main_quantity
            province_kill_request.total_killed_weight = int(
                province_kill_request.main_quantity * poultry_request.Index_weight)
            province_kill_request.total_wage_amount = province_kill_request.total_killed_weight * province_kill_request.wage
            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':
                        province_kill_request.union_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.union_share_percent = percentage_wage_type.percent
                    elif percentage_wage_type.share_type.en_name == 'company':
                        province_kill_request.company_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.company_share_percent = percentage_wage_type.percent

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

                    elif percentage_wage_type.share_type.en_name == 'other':
                        province_kill_request.other_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.other_share_percent = percentage_wage_type.percent

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

                    else:
                        province_kill_request.other_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.other_share_percent = percentage_wage_type.percent
                    province_kill_request.save()

            province_kill_request.save()
            poultry_request.remain_quantity -= province_kill_request.main_quantity
            poultry_request.save()

            province_check.quantity = province_check.quantity - int(int(request.data['quantity']))
            if province_check.quantity < 0 or province_check.quantity == 0:
                province_check.quantity = 0
                province_check.province_show_kill_house = 'accepted'
            province_check.save()
            kill_request.remain_quantity -= province_kill_request.main_quantity
            kill_request.save()
            kill_house_request_serializer = self.serializer_class(province_kill_request)
            dict1 = {
                "kill_house_req_key": str(province_kill_request.key),
                "kill_req_key": province_kill_request.kill_request.key,
                "province_kill_request_state": province_kill_request.state,
                "kill_house_name": province_kill_request.kill_request.kill_house.name,
                "kill_house_user_name": province_kill_request.kill_request.kill_house.kill_house_operator.user.fullname,
                "kill_house_user_city": province_kill_request.kill_request.kill_house.kill_house_operator.address.city.name,
                "kill_house_mobile": province_kill_request.kill_request.kill_house.kill_house_operator.user.mobile,
                "quantity": province_kill_request.quantity,
                "fee": province_kill_request.fee,
                "time": province_kill_request.kill_request.recive_time,
                "date": province_kill_request.kill_request.recive_date,
            }

            factor = KillRequestFactor.objects.filter(kill_request=kill_request)
            if factor.count() > 0:
                factor = factor.last()
                if KillRequestFactorPayment.objects.filter(kill_request_factor=factor).exists():
                    factor.state = 'paid'
                else:
                    factor.state = 'unpaid'
                factor.save()
            province_kill_request_list.append(province_kill_request.key)

            if AutoAcceptProvinceKillRequest.objects.filter(allow=True).exists():
                kill_house_check = KillHouseCheckRequest(
                    province_kill_request=province_kill_request,
                    role="ProvinceOperator",
                    state="accepted"

                )
                province_kill_request.state = 'accepted'
                kill_house_check.save()
                province_kill_request.save()
            if poultry_request.export == True:
                hatching.export_killed_weight += int(int(request.data['quantity']) * poultry_request.Index_weight)
                hatching.export_killed_quantity += int(request.data['quantity'])
            elif poultry_request.free_sale_in_province == True:
                hatching.free_killed_quantity += int(int(request.data['quantity']) * poultry_request.Index_weight)
                hatching.free_quantity += int(request.data['quantity'])
            else:
                hatching.governmental_killed_quantity += int(
                    int(request.data['quantity']) * poultry_request.Index_weight)

                hatching.governmental_quantity += int(request.data['quantity'])
            hatching.save()
            vet_farm = VetFarm.objects.filter(trash=False, poultry=hatching.poultry).first()
            if SmsLicense.objects.filter(province_kill_request=True).exists():
                kill_house_name = kill_house.name
                kill_house_mobile = kill_house.kill_house_operator.user.mobile
                kill_house_second_mobile = kill_house.alternate_number
                quantity = province_kill_request.quantity
                sale_in_province = province_check.poultry_request.free_sale_in_province
                amount = province_check.poultry_request.amount
                chicken_breed = province_check.poultry_request.chicken_breed
                poultry_name = province_check.poultry_request.poultry.unit_name
                poultry_mobile = province_check.poultry_request.poultry.user.mobile
                date_str = str(province_check.poultry_request.send_date)
                send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                send_date = jdatetime.datetime.fromgregorian(year=send_date.year, month=send_date.month,
                                                             day=send_date.day).strftime('%Y-%m-%d')
                date_list = reversed(send_date.split('-'))
                separate = "-"
                send_date = separate.join(date_list)
                province = province_check.poultry_request.poultry.address.province.name
                city = province_check.poultry_request.poultry.address.city.name
                province_kill_request_to_kill_house_sms(kill_house_mobile, quantity, chicken_breed, send_date,
                                                        poultry_name,
                                                        poultry_mobile, province, city, sale_in_province, amount,
                                                        kill_house_name
                                                        )
                if kill_house_second_mobile != None:
                    province_kill_request_to_kill_house_sms_threading = threading.Thread(
                        target=province_kill_request_to_kill_house_sms,
                        args=(
                            kill_house_second_mobile, quantity, chicken_breed, send_date,
                            poultry_name,
                            poultry_mobile, province, city, sale_in_province, amount,
                            kill_house_name
                        ))
                    province_kill_request_to_kill_house_sms_threading.start()
            if not KillHouseWareHouse.objects.filter(kill_house=kill_house, date__date=now).exists():
                ware_house_date = datetime(year=now.year, month=now.month, day=now.day, hour=1, minute=12, second=20)
                kill_house_ware_house = KillHouseWareHouse(
                    kill_house=kill_house,
                    date=ware_house_date
                )
                kill_house_ware_house.save()
            if base_url_sms == 'ha':
                poultry_name = province_kill_request.province_request.poultry_request.poultry.unit_name
                poultry_mobile = province_kill_request.province_request.poultry_request.poultry.user.mobile
                quantity = province_kill_request.main_quantity
                Index_weight = province_kill_request.province_request.poultry_request.Index_weight
                kill_house_name = province_kill_request.killhouse_user.name
                kill_house_mobile = province_kill_request.killhouse_user.kill_house_operator.user.mobile
                date_str = str(
                    province_kill_request.province_request.poultry_request.send_date)
                send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                send_date = jdatetime.datetime.fromgregorian(year=send_date.year, month=send_date.month,
                                                             day=send_date.day).strftime('%Y-%m-%d')
                date_list = reversed(send_date.split('-'))
                separate = "-"
                send_date = separate.join(date_list)
                # city = province_kill_request.province_request.poultry_request.poultry.address.city.name
                # vet_farm = VetFarm.objects.filter(
                #     poultry=province_kill_request.province_request.poultry_request.poultry).first()
                # sms_allocation_for_vet_farm(poultry_name, poultry_mobile,
                #                             quantity, Index_weight, kill_house_name, kill_house_mobile, city, send_date,
                #                             vet_farm.vet.user.mobile)
            create_update_chicken_commission_prices()
            bot_eitaa_for_each_province_kill_request(province_kill_request, vet_farm)
            return Response(dict1, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

    # تابع مربوط به نمایش  تخصیصات به کشتارگاها توسط استان
    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        # refresh(request.user.id)
        info_dict_list = []
        exclusive_killer = False
        info_list = []
        province_kill_reqs = []

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

                if 'car' in request.GET:
                    if KillHousePercentage.objects.filter(kill_house_for_killer__in=kill_house,
                                                          kill_house__type='exclusive').exists():
                        exclusive_killer = True
                    province_kill_reqs = ProvinceKillRequest.objects.filter(
                        Q(killhouse_user__in=kill_house) | Q(
                            kill_request__slaughter_house__in=kill_house),
                        province_request__poultry_request__send_date__date__gte=date1,
                        province_request__poultry_request__send_date__date__lte=date2,
                        state='accepted',
                        return_to_province=False,
                        province_request__city_request_Poultry__poultry_request__final_state='pending',
                        trash=False, quantity__gt=0).order_by(
                        'province_request__city_request_Poultry__poultry_request__send_date')
                    # province_kill_reqs = [
                    #     province_request for province_request in province_kill_req_lists
                    #     if date1 <= province_request.province_request.poultry_request.send_date.date() <= date2
                    # ]
                elif 'id' in request.GET:
                    poultry_request = PoultryRequest.objects.get(id=int(request.GET['id']))
                    province_kill_reqs = ProvinceKillRequest.objects.filter(state='accepted',
                                                                            killhouse_user__in=kill_house,
                                                                            province_request__city_request_Poultry__poultry_request=poultry_request,
                                                                            province_request__city_request_Poultry__poultry_request__final_state='pending',
                                                                            trash=False).order_by(
                        'province_request__city_request_Poultry__poultry_request__send_date')
                elif 'allocations' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        trash = True if 'deleted_object' in request.GET else False
                        province_kill_requests = ProvinceKillRequest.objects.filter(
                            Q(killhouse_user__in=kill_house) | Q(
                                kill_request__slaughter_house__in=kill_house),
                            trash=trash,
                            delete_message__isnull=False if trash else True,
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            temporary_trash=False, temporary_deleted=False
                        ).select_related(
                            'province_request__poultry_request__poultry',
                            'province_request__city_request_Poultry__poultry_request__poultry__user',
                            'province_request__city_request_Poultry__poultry_request__poultry__user__city',
                            'kill_request__kill_house',
                            'kill_request__kill_house__kill_house_operator__user',
                            'kill_request__kill_house__system_address__city'
                        ).values(
                            "province_request__poultry_request__order_code",
                            "province_request__poultry_request__amount",
                            "province_request__poultry_request__financial_operation",
                            "province_request__poultry_request__Index_weight",
                            "province_request__poultry_request__send_date",
                            "province_request__poultry_request__freezing",
                            "province_request__poultry_request__export",
                            "province_request__poultry_request__poultry__unit_name",
                            "province_request__poultry_request__poultry__user__fullname",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__mobile",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__city__name",
                            "province_request__poultry_request__quantity",
                            "kill_request__market",
                            "kill_request__kill_house__name",
                            "kill_request__kill_house__kill_house_operator__user__mobile",
                            "kill_request__kill_house__system_address__city__name",
                            "create_date",
                            "main_quantity",
                            "quantity",
                            "return_to_province",
                            "returner",
                            "key",
                            "state",
                            "kill_house_price",
                            "province_request__poultry_request__union",
                            "province_request__poultry_request__direct_buying",
                            "province_request__poultry_request__free_sale_in_province",
                            # "allocated_car_state"
                        ).order_by('province_request__poultry_request__send_date')
                        value = request.GET.get('value')
                        search = request.GET.get('search')
                        if value and search == 'filter':
                            if value != 'undefined' and value.strip():
                                province_kill_requests = province_kill_requests.filter(
                                    build_query(self.filterset_class, value)
                                )
                        province_kill_reqs_list_final_state = []
                        for request_data in province_kill_requests:
                            allocated_car_state = True if request_data.get('main_quantity') != request_data.get(
                                'quantity') else False

                            internal_dict = {
                                "order_code": request_data.get('province_request__poultry_request__order_code'),
                                "freezing": request_data.get('province_request__poultry_request__freezing'),
                                "export": request_data.get('province_request__poultry_request__export'),
                                "amount": request_data.get('province_request__poultry_request__amount'),
                                "financial_operation": request_data.get(
                                    'province_request__poultry_request__financial_operation'),
                                "index_weight": request_data.get('province_request__poultry_request__Index_weight'),
                                "total_weight": request_data.get('main_quantity') * request_data.get(
                                    'province_request__poultry_request__Index_weight'),
                                "send_date": request_data.get('province_request__poultry_request__send_date'),
                                "poultry_unit_name": request_data.get(
                                    'province_request__poultry_request__poultry__unit_name'),
                                "poultry_full_name": request_data.get(
                                    'province_request__poultry_request__poultry__user__fullname'),
                                "poultry_mobile": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__mobile'),
                                "poultry_city": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__city__name'),
                                "poultry_quantity": request_data.get('province_request__poultry_request__quantity'),
                                "kill_house_name": request_data.get('kill_request__kill_house__name'),
                                "market": request_data.get('kill_request__market'),
                                "kill_house_mobile": request_data.get(
                                    'kill_request__kill_house__kill_house_operator__user__mobile'),
                                "kill_house_city": request_data.get(
                                    'kill_request__kill_house__system_address__city__name'),
                                "date_of_allocate": request_data.get('create_date'),
                                "allocated_quantity": request_data.get('main_quantity'),
                                "return_to_province": request_data.get('return_to_province'),
                                "returner": request_data.get('returner'),
                                "allocated_remain_quantity": request_data.get('quantity') if request_data.get(
                                    'return_to_province') == False else 0,
                                "province_kill_request_key": request_data.get('key'),
                                "allocated_state": request_data.get('state'),
                                "union": request_data.get('province_request__poultry_request__union'),
                                "direct_buying": request_data.get(
                                    'province_request__poultry_request__direct_buying'),
                                "allocated_car_state": allocated_car_state,
                                "free_sale_in_province": request_data.get(
                                    'province_request__poultry_request__free_sale_in_province'),
                                "kill_house_price": request_data.get('kill_house_price')
                            }

                            province_kill_reqs_list_final_state.append(internal_dict)
                        return Response(province_kill_reqs_list_final_state, status=status.HTTP_200_OK)
                elif 'allocated_car_state' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        trash = True if 'deleted_object' in request.GET else False
                        province_kill_requests = ProvinceKillRequest.objects.filter(
                            Q(killhouse_user__in=kill_house) | Q(
                                kill_request__slaughter_house__in=kill_house),
                            trash=trash,
                            delete_message__isnull=False if trash else True,
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            temporary_trash=False, temporary_deleted=False, first_car_allocated_quantity=0
                        ).select_related(
                            'province_request__poultry_request__poultry',
                            'province_request__city_request_Poultry__poultry_request__poultry__user',
                            'province_request__city_request_Poultry__poultry_request__poultry__user__city',
                            'kill_request__kill_house',
                            'kill_request__kill_house__kill_house_operator__user',
                            'kill_request__kill_house__system_address__city'
                        ).values(
                            "province_request__poultry_request__order_code",
                            "province_request__poultry_request__amount",
                            "province_request__poultry_request__financial_operation",
                            "province_request__poultry_request__Index_weight",
                            "province_request__poultry_request__send_date",
                            "province_request__poultry_request__freezing",
                            "province_request__poultry_request__export",
                            "province_request__poultry_request__poultry__unit_name",
                            "province_request__poultry_request__poultry__user__fullname",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__mobile",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__city__name",
                            "province_request__poultry_request__quantity",
                            "kill_request__kill_house__name",
                            "kill_request__market",
                            "kill_request__kill_house__kill_house_operator__user__mobile",
                            "kill_request__kill_house__system_address__city__name",
                            "create_date",
                            "main_quantity",
                            "quantity",
                            "return_to_province",
                            "returner",
                            "key",
                            "state",
                            "kill_house_price",
                            "province_request__poultry_request__union",
                            "province_request__poultry_request__direct_buying",
                            "province_request__poultry_request__free_sale_in_province",
                            # "allocated_car_state"
                        ).order_by('province_request__poultry_request__send_date')
                        value = request.GET.get('value')
                        search = request.GET.get('search')
                        if value and search == 'filter':
                            if value != 'undefined' and value.strip():
                                province_kill_requests = province_kill_requests.filter(
                                    build_query(self.filterset_class, value)
                                )
                        province_kill_reqs_list_final_state = []
                        for request_data in province_kill_requests:
                            allocated_car_state = True if request_data.get('main_quantity') != request_data.get(
                                'quantity') else False

                            internal_dict = {
                                "order_code": request_data.get('province_request__poultry_request__order_code'),
                                "freezing": request_data.get('province_request__poultry_request__freezing'),
                                "export": request_data.get('province_request__poultry_request__export'),
                                "amount": request_data.get('province_request__poultry_request__amount'),
                                "financial_operation": request_data.get(
                                    'province_request__poultry_request__financial_operation'),
                                "index_weight": request_data.get('province_request__poultry_request__Index_weight'),
                                "total_weight": request_data.get('main_quantity') * request_data.get(
                                    'province_request__poultry_request__Index_weight'),
                                "send_date": request_data.get('province_request__poultry_request__send_date'),
                                "poultry_unit_name": request_data.get(
                                    'province_request__poultry_request__poultry__unit_name'),
                                "poultry_full_name": request_data.get(
                                    'province_request__poultry_request__poultry__user__fullname'),
                                "poultry_mobile": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__mobile'),
                                "poultry_city": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__city__name'),
                                "poultry_quantity": request_data.get('province_request__poultry_request__quantity'),
                                "kill_house_name": request_data.get('kill_request__kill_house__name'),
                                "market": request_data.get('kill_request__market'),
                                "kill_house_mobile": request_data.get(
                                    'kill_request__kill_house__kill_house_operator__user__mobile'),
                                "kill_house_city": request_data.get(
                                    'kill_request__kill_house__system_address__city__name'),
                                "date_of_allocate": request_data.get('create_date'),
                                "allocated_quantity": request_data.get('main_quantity'),
                                "return_to_province": request_data.get('return_to_province'),
                                "returner": request_data.get('returner'),
                                "allocated_remain_quantity": request_data.get('quantity') if request_data.get(
                                    'return_to_province') == False else 0,
                                "province_kill_request_key": request_data.get('key'),
                                "allocated_state": request_data.get('state'),
                                "union": request_data.get('province_request__poultry_request__union'),
                                "direct_buying": request_data.get(
                                    'province_request__poultry_request__direct_buying'),
                                "allocated_car_state": allocated_car_state,
                                "free_sale_in_province": request_data.get(
                                    'province_request__poultry_request__free_sale_in_province'),
                                "kill_house_price": request_data.get('kill_house_price')
                            }

                            province_kill_reqs_list_final_state.append(internal_dict)
                        return Response(province_kill_reqs_list_final_state, status=status.HTTP_200_OK)
                else:
                    province_kill_reqs = ProvinceKillRequest.objects.filter(
                        province_request__poultry_request__send_date__date__gte=date1,
                        province_request__poultry_request__send_date__date__lte=date2, killhouse_user__in=kill_house,
                        province_request__city_request_Poultry__poultry_request__final_state='pending',
                        trash=False,
                        state='pending',
                        dont_show_kill_house=False).select_related('province_request__poultry_request').order_by(
                        'province_request__city_request_Poultry__poultry_request__send_date')

                    # province_kill_reqs = [
                    #     province_request for province_request in province_kill_req_list
                    #     if date1 <= province_request.province_request.poultry_request.send_date.date() <= date2
                    # ]
            elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Supporter']:

                if 'id' in request.GET:
                    poultry_request = PoultryRequest.objects.get(id=int(request.GET['id']))
                    province_kill_reqs = ProvinceKillRequest.objects.filter(state='accepted',
                                                                            province_request__city_request_Poultry__poultry_request=poultry_request,
                                                                            trash=False).order_by(
                        'province_request__city_request_Poultry__poultry_request__send_date')
                elif 'allocations' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                        trash = True if 'deleted_object' in request.GET else False
                        province_kill_requests = ProvinceKillRequest.objects.filter(
                            province_request__city_request_Poultry__poultry_request__poultry__user__province=user.province,
                            trash=trash,
                            delete_message__isnull=False if trash else True,
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            temporary_trash=False, temporary_deleted=False
                        ).select_related(
                            'province_request__poultry_request__poultry',
                            'province_request__city_request_Poultry__poultry_request__poultry__user',
                            'province_request__city_request_Poultry__poultry_request__poultry__user__city',
                            'kill_request__kill_house',
                            'kill_request__kill_house__kill_house_operator__user',
                            'kill_request__kill_house__system_address__city'
                        ).values(
                            "province_request__poultry_request__order_code",
                            "province_request__poultry_request__amount",
                            "province_request__poultry_request__financial_operation",
                            "province_request__poultry_request__Index_weight",
                            "province_request__poultry_request__send_date",
                            "province_request__poultry_request__freezing",
                            "province_request__poultry_request__export",
                            "province_request__poultry_request__poultry__unit_name",
                            "province_request__poultry_request__poultry__user__fullname",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__mobile",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__city__name",
                            "province_request__poultry_request__quantity",
                            "kill_request__kill_house__name",
                            "kill_request__market",
                            "kill_request__kill_house__kill_house_operator__user__mobile",
                            "kill_request__kill_house__system_address__city__name",
                            "create_date",
                            "main_quantity",
                            "quantity",
                            "return_to_province",
                            "returner",
                            "key",
                            "state",
                            "kill_house_price",
                            "province_request__poultry_request__union",
                            "province_request__poultry_request__direct_buying",
                            "province_request__poultry_request__free_sale_in_province",
                            # "allocated_car_state"
                        ).order_by('province_request__poultry_request__send_date')
                        value = request.GET.get('value')
                        search = request.GET.get('filter')
                        if value and search == 'search':
                            if value != 'undefined' and value.strip():
                                province_kill_requests = province_kill_requests.filter(
                                    build_query(self.filterset_class, value)
                                )
                        province_kill_reqs_list_final_state = []
                        for request_data in province_kill_requests:
                            allocated_car_state = True if request_data.get('main_quantity') != request_data.get(
                                'quantity') else False

                            internal_dict = {
                                "order_code": request_data.get('province_request__poultry_request__order_code'),
                                "freezing": request_data.get('province_request__poultry_request__freezing'),
                                "export": request_data.get('province_request__poultry_request__export'),
                                "amount": request_data.get('province_request__poultry_request__amount'),
                                "financial_operation": request_data.get(
                                    'province_request__poultry_request__financial_operation'),
                                "index_weight": request_data.get('province_request__poultry_request__Index_weight'),
                                "total_weight": request_data.get('main_quantity') * request_data.get(
                                    'province_request__poultry_request__Index_weight'),
                                "send_date": request_data.get('province_request__poultry_request__send_date'),
                                "poultry_unit_name": request_data.get(
                                    'province_request__poultry_request__poultry__unit_name'),
                                "poultry_full_name": request_data.get(
                                    'province_request__poultry_request__poultry__user__fullname'),
                                "poultry_mobile": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__mobile'),
                                "poultry_city": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__city__name'),
                                "poultry_quantity": request_data.get('province_request__poultry_request__quantity'),
                                "kill_house_name": request_data.get('kill_request__kill_house__name'),
                                "market": request_data.get('kill_request__market'),
                                "kill_house_mobile": request_data.get(
                                    'kill_request__kill_house__kill_house_operator__user__mobile'),
                                "kill_house_city": request_data.get(
                                    'kill_request__kill_house__system_address__city__name'),
                                "date_of_allocate": request_data.get('create_date'),
                                "allocated_quantity": request_data.get('main_quantity'),
                                "return_to_province": request_data.get('return_to_province'),
                                "returner": request_data.get('returner'),
                                "allocated_remain_quantity": request_data.get('quantity') if request_data.get(
                                    'return_to_province') == False else 0,
                                "province_kill_request_key": request_data.get('key'),
                                "allocated_state": request_data.get('state'),
                                "union": request_data.get('province_request__poultry_request__union'),
                                "direct_buying": request_data.get(
                                    'province_request__poultry_request__direct_buying'),
                                "allocated_car_state": allocated_car_state,
                                "free_sale_in_province": request_data.get(
                                    'province_request__poultry_request__free_sale_in_province'),
                                "kill_house_price": request_data.get('kill_house_price')
                            }

                            province_kill_reqs_list_final_state.append(internal_dict)
                        return Response(province_kill_reqs_list_final_state, status=status.HTTP_200_OK)
                elif 'allocated_car_state' in request.GET:
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                        trash = True if 'deleted_object' in request.GET else False
                        province_kill_requests = ProvinceKillRequest.objects.filter(
                            province_request__city_request_Poultry__poultry_request__poultry__user__province=user.province,
                            trash=trash,
                            delete_message__isnull=False if trash else True,
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            temporary_trash=False, temporary_deleted=False, first_car_allocated_quantity=0
                        ).select_related(
                            'province_request__poultry_request__poultry',
                            'province_request__city_request_Poultry__poultry_request__poultry__user',
                            'province_request__city_request_Poultry__poultry_request__poultry__user__city',
                            'kill_request__kill_house',
                            'kill_request__kill_house__kill_house_operator__user',
                            'kill_request__kill_house__system_address__city'
                        ).values(
                            "province_request__poultry_request__order_code",
                            "province_request__poultry_request__amount",
                            "province_request__poultry_request__financial_operation",
                            "province_request__poultry_request__Index_weight",
                            "province_request__poultry_request__send_date",
                            "province_request__poultry_request__freezing",
                            "province_request__poultry_request__export",
                            "province_request__poultry_request__poultry__unit_name",
                            "province_request__poultry_request__poultry__user__fullname",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__mobile",
                            "province_request__city_request_Poultry__poultry_request__poultry__user__city__name",
                            "province_request__poultry_request__quantity",
                            "kill_request__kill_house__name",
                            "kill_request__market",
                            "kill_request__kill_house__kill_house_operator__user__mobile",
                            "kill_request__kill_house__system_address__city__name",
                            "create_date",
                            "main_quantity",
                            "quantity",
                            "return_to_province",
                            "returner",
                            "key",
                            "state",
                            "kill_house_price",
                            "province_request__poultry_request__union",
                            "province_request__poultry_request__direct_buying",
                            "province_request__poultry_request__free_sale_in_province",
                            # "allocated_car_state"
                        ).order_by('province_request__poultry_request__send_date')
                        value = request.GET.get('value')
                        search = request.GET.get('filter')
                        if value and search == 'search':
                            if value != 'undefined' and value.strip():
                                province_kill_requests = province_kill_requests.filter(
                                    build_query(self.filterset_class, value)
                                )
                        province_kill_reqs_list_final_state = []
                        for request_data in province_kill_requests:
                            allocated_car_state = True if request_data.get('main_quantity') != request_data.get(
                                'quantity') else False

                            internal_dict = {
                                "order_code": request_data.get('province_request__poultry_request__order_code'),
                                "freezing": request_data.get('province_request__poultry_request__freezing'),
                                "export": request_data.get('province_request__poultry_request__export'),
                                "amount": request_data.get('province_request__poultry_request__amount'),
                                "financial_operation": request_data.get(
                                    'province_request__poultry_request__financial_operation'),
                                "index_weight": request_data.get('province_request__poultry_request__Index_weight'),
                                "total_weight": request_data.get('main_quantity') * request_data.get(
                                    'province_request__poultry_request__Index_weight'),
                                "send_date": request_data.get('province_request__poultry_request__send_date'),
                                "poultry_unit_name": request_data.get(
                                    'province_request__poultry_request__poultry__unit_name'),
                                "poultry_full_name": request_data.get(
                                    'province_request__poultry_request__poultry__user__fullname'),
                                "poultry_mobile": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__mobile'),
                                "poultry_city": request_data.get(
                                    'province_request__city_request_Poultry__poultry_request__poultry__user__city__name'),
                                "poultry_quantity": request_data.get('province_request__poultry_request__quantity'),
                                "kill_house_name": request_data.get('kill_request__kill_house__name'),
                                "market": request_data.get('kill_request__market'),
                                "kill_house_mobile": request_data.get(
                                    'kill_request__kill_house__kill_house_operator__user__mobile'),
                                "kill_house_city": request_data.get(
                                    'kill_request__kill_house__system_address__city__name'),
                                "date_of_allocate": request_data.get('create_date'),
                                "allocated_quantity": request_data.get('main_quantity'),
                                "return_to_province": request_data.get('return_to_province'),
                                "returner": request_data.get('returner'),
                                "allocated_remain_quantity": request_data.get('quantity') if request_data.get(
                                    'return_to_province') == False else 0,
                                "province_kill_request_key": request_data.get('key'),
                                "allocated_state": request_data.get('state'),
                                "union": request_data.get('province_request__poultry_request__union'),
                                "direct_buying": request_data.get(
                                    'province_request__poultry_request__direct_buying'),
                                "allocated_car_state": allocated_car_state,
                                "free_sale_in_province": request_data.get(
                                    'province_request__poultry_request__free_sale_in_province'),
                                "kill_house_price": request_data.get('kill_house_price')
                            }

                            province_kill_reqs_list_final_state.append(internal_dict)
                        return Response(province_kill_reqs_list_final_state, status=status.HTTP_200_OK)
            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()

                if 'id' in request.GET:
                    poultry_request = PoultryRequest.objects.get(id=int(request.GET['id']))
                    province_kill_reqs = ProvinceKillRequest.objects.filter(state='accepted',
                                                                            killhouse_user=kill_house_vet.kill_house,
                                                                            province_request__city_request_Poultry__poultry_request=poultry_request,
                                                                            trash=False).order_by(
                        'province_request__city_request_Poultry__poultry_request__send_date')
                else:
                    province_kill_reqs = ProvinceKillRequest.objects.filter(killhouse_user=kill_house_vet.kill_house,
                                                                            trash=False).order_by(
                        'province_request__city_request_Poultry__poultry_request__send_date')
            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)
                    for vet_farm in vet_farms:
                        if vet_farm.poultry in poultries:
                            pass
                        else:
                            poultries.append(vet_farm.poultry)
                if len(poultries) == 0:
                    return Response([], status=status.HTTP_200_OK)
                province_kill_reqs = ProvinceKillRequest.objects.filter(
                    province_request__poultry_request__poultry__in=poultries,
                    province_request__poultry_request__poultry__address__province=vet.user.province,
                    trash=False).order_by(
                    'province_request__city_request_Poultry__poultry_request__send_date')
            elif request.GET['role'] == 'VetSupervisor':
                vet = VetSupervisor.objects.get(user=user, trash=False)

                province_kill_reqs = ProvinceKillRequest.objects.filter(
                    province_request__poultry_request__poultry__address__province=vet.user.province,
                    trash=False).order_by(
                    'province_request__city_request_Poultry__poultry_request__send_date')


        else:
            if 'state' in request.GET:
                if request.GET['state'] == 'accepted':
                    province_kill_reqs = ProvinceKillRequest.objects.filter(state='accepted', trash=False)
            else:
                province_kill_reqs = ProvinceKillRequest.objects.filter(vet_state='accepted', trash=False)
        if len(province_kill_reqs) == 0:
            return Response(province_kill_reqs, status=status.HTTP_200_OK)
        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                province_kill_reqs = province_kill_reqs.filter(
                    build_query(self.filterset_class, value)
                )
        for province_kill_req in province_kill_reqs:
            check_key = KillHouseCheckRequest.objects.filter(province_kill_request=province_kill_req)
            if check_key.count() > 0:
                check_key = check_key.last().key
            else:
                check_key = None
            internal_dict_infos = {
                "poultry_req_id": province_kill_req.province_request.city_request_Poultry.poultry_request.id,
                "freezing": province_kill_req.province_request.city_request_Poultry.poultry_request.freezing,
                "direct_buying": province_kill_req.province_request.city_request_Poultry.poultry_request.direct_buying,
                "export": province_kill_req.province_request.city_request_Poultry.poultry_request.export,
                "amount": province_kill_req.province_request.city_request_Poultry.poultry_request.amount,
                "financial_operation": province_kill_req.province_request.city_request_Poultry.poultry_request.financial_operation,
                "poultry_req_key": province_kill_req.province_request.city_request_Poultry.poultry_request.key,
                "province_kill_req_key": province_kill_req.key,
                "poultry_name": province_kill_req.province_request.city_request_Poultry.poultry_request.poultry.user.fullname,
                "order_code": province_kill_req.province_request.city_request_Poultry.poultry_request.order_code,
                "send_date": province_kill_req.province_request.city_request_Poultry.poultry_request.send_date,
                "city": province_kill_req.province_request.city_request_Poultry.poultry_request.poultry.address.city.name,
                "province": province_kill_req.province_request.city_request_Poultry.poultry_request.poultry.user.province.name,
                "poultry_mobile": province_kill_req.province_request.city_request_Poultry.poultry_request.poultry.user.mobile,
                "kill_house_key": province_kill_req.kill_request.kill_house.key,
                "kill_house_check_key": check_key,
                "kill_house_name": province_kill_req.kill_request.kill_house.name,
                "kill_house_mobile": province_kill_req.kill_request.kill_house.kill_house_operator.user.mobile,
                "quantity": province_kill_req.quantity if province_kill_req.return_to_province == False else 0,
                "main_quantity": province_kill_req.main_quantity,
                "time": province_kill_req.kill_request.recive_time,
                "date": province_kill_req.kill_request.recive_date,
                "age": (
                               datetime.now() - province_kill_req.province_request.city_request_Poultry.poultry_request.hatching.date).days + 1,
                "province_kill_req": province_kill_req.key,
                "return_to_province": province_kill_req.return_to_province,
                "returner": province_kill_req.returner,
                "kill_request_key": province_kill_req.kill_request.key,
                "market": province_kill_req.kill_request.market,
                "province_kill_state": province_kill_req.state,
                "allocated_quantity": province_kill_req.main_quantity - province_kill_req.quantity,
                "remain_quantity": province_kill_req.quantity,
                "chicken_breed": province_kill_req.kill_request.chicken_breed,
                "index_weight": province_kill_req.province_request.poultry_request.Index_weight,
                "total_weight": province_kill_req.main_quantity * province_kill_req.province_request.poultry_request.Index_weight,
                "province_kill_reviewer": province_kill_req.reviewer,
                "province_kill_clearance_code": province_kill_req.clearance_code,
                "exclusive_killer": exclusive_killer,
                "kill_house_price": province_kill_req.kill_house_price,
                "province_kill_request_key": province_kill_req.key,
                "kill_house_assignments": "",
                "free_sale_in_province": province_kill_req.province_request.poultry_request.free_sale_in_province,

            }
            kill_house_check = KillHouseCheckRequest.objects.filter(province_kill_request=province_kill_req,
                                                                    trash=False)
            if kill_house_check:
                kill_house_check = kill_house_check.last()
                internal_dict_infos.update({
                    "kill_house_check_key": kill_house_check.key,
                })
            for kill_house_req_obj in KillHouseRequest.objects.filter(
                    province_kill_request=province_kill_req, trash=False):
                internal_kill_house_request_dict_infos = {
                    "kill_house_req_key": kill_house_req_obj.key,
                    "kill_req_key": kill_house_req_obj.kill_request.key,
                    "barcod": kill_house_req_obj.bar_code,
                    "kill_house_state": kill_house_req_obj.state,
                    "kill_house_name": kill_house_req_obj.kill_request.kill_house.name,
                    "kill_house_user_name": kill_house_req_obj.kill_request.kill_house.kill_house_operator.user.fullname,
                    "kill_house_user_city": kill_house_req_obj.kill_request.kill_house.kill_house_operator.address.city.name,
                    "kill_house_mobile": kill_house_req_obj.kill_request.kill_house.kill_house_operator.user.mobile,
                    "quantity": kill_house_req_obj.quantity,
                    "time": kill_house_req_obj.kill_request.recive_time,
                    "date": kill_house_req_obj.kill_request.recive_date,
                    "cars": kill_house_req_obj.car,
                    "show_kill_house": kill_house_req_obj.show_kill_house,
                    "kill_house_message": kill_house_req_obj.kill_house_message,
                }

                info_list.append(internal_kill_house_request_dict_infos)

            internal_dict_infos["kill_house_assignments"] = info_list

            info_dict_list.append(internal_dict_infos)
        return Response(info_dict_list, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.data['role']
        request.data.pop('role')
        if 'type' in request.data.keys():
            if request.data['type'] == 'archive':
                user_fullname = user.fullname
                date = str(datetime.now())
                archive_province_kill_request_wage_threading = threading.Thread(
                    target=provincearchiveprovincekillrequestforwage,
                    args=(
                        request.data['province_kill_request_list'], request.data['message'], role, user_fullname, date
                    ))
                archive_province_kill_request_wage_threading.start()
                return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)


            elif request.data['type'] == 'return_archive':
                user_fullname = user.fullname
                date = str(datetime.now().date())
                province_kill_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'])
                province_kill_request.archive_by_province = False
                if 'return_archive_message' in request.data.keys():
                    province_kill_request.return_archive_message = request.data['return_archive_message']
                province_kill_request.returner = {
                    "fullname": user_fullname,
                    "date": date,
                    "role": role
                }
                province_kill_request.save()
                return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)
        elif 'edit_allocation_quantity' in request.data.keys():
            wage = 0
            province_kill_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'],
                                                                    trash=False)
            if province_kill_request.market:
                return Response({"result": "امکان ویرایش برای تخصیصات  پنل معاملات وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
            poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key,
                                                         trash=False)
            if poultry_request.freezing == True:
                wage_type = WageType.objects.filter(en_name='province-kill-request-freezing', trash=False).first()
            else:

                wage_type = WageType.objects.filter(en_name='province-kill-request', trash=False).first()
            if wage_type.status == True:
                wage = wage_type.amount
            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
            if KillHouseRequest.objects.filter(trash=False, province_kill_request=province_kill_request).exists():
                return Response({"result": "برای این  تخصیص بارایجاد شده است امکان ویرایش وجود ندارد"},
                                status=status.HTTP_403_FORBIDDEN)
            amount = province_kill_request.main_quantity
            if request.data['quantity'] > amount:
                different_amount = request.data['quantity'] - amount
                province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                                            province_request__poultry_request=poultry_request)
                total_quantity = \
                    province_kill_requests.aggregate(total=Sum('main_quantity'))['total'] or 0
                if different_amount + total_quantity > poultry_request.quantity:
                    return Response({"result": "تعداد وارد شده بیشتر از اعلام نیاز مرغدار است!"},
                                    status=status.HTTP_403_FORBIDDEN)
                total_quantity_for_hatching = province_kill_requests.aggregate(total=Sum('total_killed_quantity'))[
                                                  'total'] or 0
                if different_amount + total_quantity_for_hatching > hatching.left_over:
                    return Response({"result": "تعداد وارد شده بیشتر از باقی مانده جوجه ریزی مرغدار است!"},
                                    status=status.HTTP_403_FORBIDDEN)
                province_kill_requests_for_kill_request = ProvinceKillRequest.objects.filter(trash=False,
                                                                                             return_to_province=False,
                                                                                             kill_request=province_kill_request.kill_request)
                total_quantity_for_kill_request = \
                    province_kill_requests_for_kill_request.aggregate(total=Sum('main_quantity'))['total'] or 0
                if province_kill_request.kill_request.kill_capacity < total_quantity_for_kill_request + different_amount:
                    return Response({"result": "تعداد وارد شده بیشتر از اعلام نیاز کشتارگاه است!"},
                                    status=status.HTTP_403_FORBIDDEN)
                province_kill_request.province_request.quantity -= different_amount
                if province_kill_request.province_request.quantity < 0:
                    province_kill_request.province_request.quantity = 0
                province_kill_request.province_request.save()
                province_kill_request.kill_request.remain_quantity = province_kill_request.kill_request.kill_capacity - total_quantity_for_kill_request
                province_kill_request.kill_request.remain_quantity -= different_amount
                province_kill_request.kill_request.save()
                poultry_request.remain_quantity -= different_amount
                poultry_request.save()
            else:
                province_kill_requests_for_kill_request = ProvinceKillRequest.objects.filter(trash=False,
                                                                                             return_to_province=False,
                                                                                             kill_request=province_kill_request.kill_request)
                total_quantity_for_kill_request = \
                    province_kill_requests_for_kill_request.aggregate(total=Sum('main_quantity'))['total'] or 0
                different_amount = amount - request.data['quantity']
                province_kill_request.province_request.quantity += different_amount
                province_kill_request.province_request.save()
                province_kill_request.kill_request.remain_quantity = province_kill_request.kill_request.kill_capacity - total_quantity_for_kill_request
                province_kill_request.kill_request.remain_quantity += different_amount
                province_kill_request.kill_request.save()
                poultry_request.remain_quantity += different_amount
                poultry_request.save()

            province_kill_request.main_quantity = int(request.data['quantity'])
            province_kill_request.total_killed_quantity = province_kill_request.main_quantity
            province_kill_request.total_killed_weight = int(
                province_kill_request.main_quantity * poultry_request.Index_weight)
            province_kill_request.total_wage_amount = province_kill_request.total_killed_weight * province_kill_request.wage
            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':
                        province_kill_request.union_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.union_share_percent = percentage_wage_type.percent
                    elif percentage_wage_type.share_type.en_name == 'company':
                        province_kill_request.company_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.company_share_percent = percentage_wage_type.percent

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

                    elif percentage_wage_type.share_type.en_name == 'other':
                        province_kill_request.other_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.other_share_percent = percentage_wage_type.percent

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

                    else:
                        province_kill_request.other_share = int(
                            (percentage_wage_type.percent / 100) * province_kill_request.total_wage_amount)
                        province_kill_request.other_share_percent = percentage_wage_type.percent
                    province_kill_request.save()

            province_kill_request.save()
            update_province_kill_requests(hatching)
            poultry_prediction(hatching.poultry)

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

        else:

            province_kill_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'])
            request.data.pop('province_kill_request_key')
            if 'kill_house_price' not in request.data.keys():
                if province_kill_request.prev_total_amount == None:
                    province_kill_request.prev_total_amount = province_kill_request.total_amount
                province_kill_request.total_amount_editor = {
                    "role": role,
                    "fullname": user.fullname,
                    "mobile": user.mobile,
                    "date": str(datetime.now())
                }
                province_kill_request.save()
            
            if 'kill_house_price' in request.data.keys():
                kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                                      province_kill_request=province_kill_request)
                if kill_house_requests:
                    kill_house_requests.update(amount=request.data['kill_house_price'])
            serializer = self.serializer_class(province_kill_request)
            serializer.update(instance=province_kill_request, validated_data=request.data)
            return Response(serializer.data, status=status.HTTP_200_OK)

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

        if 'delete_allocation' in request.GET:

            province_kill_request = ProvinceKillRequest.objects.get(key=request.GET['province_kill_request_key'],
                                                                    trash=False)
            if request.GET['role'] == 'KillHouse':
                if province_kill_request.market:
                    return Response({
                        "result": "امکان حذف برای تخصیص پنل معاملاتی وجود ندارد. در صورت نیاز به کاربر اتحادیه اطلاع دهید."},
                        status=status.HTTP_403_FORBIDDEN)

                now = datetime.now()
                now_time = now.time()
                if now.date() != province_kill_request.kill_request.recive_date.date():
                    return Response({"result": "با توجه به مغایرت تاریخ امکان حذف وجود ندارد!"},
                                    status=status.HTTP_403_FORBIDDEN)

                if now_time.hour >= 16:
                    return Response({"result": "با توجه به اتمام زمان حذف مجاز امکان حذف وجود ندارد!"},
                                    status=status.HTTP_403_FORBIDDEN)

            if province_kill_request.quantity != province_kill_request.main_quantity:
                return Response({"result": "برای تخصیص ماشین ثبت شده امکان حذف وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)

            poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key,
                                                         trash=False)
            province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)

            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
            if poultry_request.export == True:
                hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
                hatching.export_killed_quantity -= int(request.data['quantity'])
            elif poultry_request.free_sale_in_province == True:
                hatching.free_killed_quantity -= province_kill_request.total_killed_weight
                # hatching.free_killed_quantity -= int(province_kill_request.main_quantity * poultry_request.Index_weight)
                hatching.free_quantity -= province_kill_request.total_killed_quantity
                # hatching.free_quantity -= province_kill_request.main_quantity
            else:
                hatching.governmental_killed_quantity -= province_kill_request.total_killed_weight
                # hatching.governmental_killed_quantity -= int(
                #     province_kill_request.main_quantity * poultry_request.Index_weight)

                hatching.governmental_quantity -= province_kill_request.total_killed_quantity
                # hatching.governmental_quantity -= province_kill_request.main_quantity
            # hatching.killed_quantity -= province_kill_request.main_quantity
            hatching.save()

            if poultry_request.remain_quantity > 0:
                # province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity
                poultry_request.save()
            else:

                # province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity
                poultry_request.save()
                # poultry_request.quantity -= province_kill_request.quantity
                # poultry_request.first_quantity -= province_kill_request.quantity
                # poultry_request.previous_quantity -= province_kill_request.quantity
                # poultry_request.save()
                # if poultry_request.quantity == 0:
                # poultry_request.trash = True
                # poultry_request.save()
                # hatching.left_over += province_kill_request.quantity
                # hatching.state = 'pending'
                # hatching.allow_hatching = 'pending'
                # hatching.save()
            kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
            kill_request.remain_quantity += province_kill_request.main_quantity
            if kill_request.market:
                user = SystemUserProfile.objects.get(trash=False, user=request.user)
                kill_request.market_state_message = {
                    "fullname": user.fullname,
                    "mobile": user.mobile,
                    "date": str(datetime.now())
                }
                kill_request.market_state = 'deleted'
            else:
                if kill_request.poultry_request:
                    kill_request.trash = True
            kill_request.save()
            province_kill_request.delete_message = request.GET['message']
            province_kill_request.trash = True
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            province_kill_request.returner = {"fullname": user.fullname, "mobile": user.mobile,
                                              "date": str(datetime.now())}
            province_kill_request.save()
            bot_eitaa_for_each_delete_province_kill_request(province_kill_request)
            return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
        elif 'return_allocation_quantity' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)

            province_kill_request = ProvinceKillRequest.objects.get(key=request.GET['province_kill_request_key'],
                                                                    trash=False)
            if province_kill_request.quantity == 0:
                return Response({"result": "باقی مانده تخصیص صفر است امکان بازگشت تعداد وجود ندارد"},
                                status=status.HTTP_403_FORBIDDEN)
            amount = province_kill_request.quantity

            poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key,
                                                         trash=False)
            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)

            if province_kill_request.main_quantity - province_kill_request.quantity == 0:
                province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity
                poultry_request.save()
                kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
                kill_request.remain_quantity += province_kill_request.main_quantity
                if kill_request.market:
                    kill_request.market_state = 'deleted'
                    user = SystemUserProfile.objects.get(trash=False, user=request.user)
                    kill_request.market_state_message = {
                        "fullname": user.fullname,
                        "mobile": user.mobile,
                        "date": str(datetime.now())
                    }

                else:
                    if kill_request.poultry_request:
                        kill_request.trash = True
                kill_request.save()
                if poultry_request.export == True:
                    hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
                    hatching.export_killed_quantity -= int(request.data['quantity'])
                elif poultry_request.free_sale_in_province == True:
                    hatching.free_killed_quantity -= province_kill_request.total_killed_weight
                    # hatching.free_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.free_quantity -= province_kill_request.total_killed_quantity
                    # hatching.free_quantity -= amount
                else:
                    hatching.governmental_killed_quantity -= province_kill_request.total_killed_weight
                    # hatching.governmental_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.governmental_quantity -= province_kill_request.total_killed_quantity
                    # hatching.governmental_quantity -= amount
                # hatching.killed_quantity -= amount
                hatching.save()
                # province_kill_request.trash = True
                province_kill_request.quantity = 0
                province_kill_request.total_killed_quantity = 0
                province_kill_request.total_killed_weight = 0
                province_kill_request.return_to_province = True
                province_kill_request.returner = {"fullname": user.fullname, "mobile": user.mobile,
                                                  "date": str(datetime.now())}
                province_kill_request.save()
                bot_eitaa_for_each_delete_province_kill_request(province_kill_request)
            else:

                province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity - province_kill_request.quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity - province_kill_request.quantity
                poultry_request.save()
                kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
                kill_request.remain_quantity += province_kill_request.main_quantity - province_kill_request.quantity
                kill_request.save()
                if poultry_request.export == True:
                    hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
                    hatching.export_killed_quantity -= int(request.data['quantity'])
                elif poultry_request.free_sale_in_province == True:
                    hatching.free_killed_quantity -= int((
                                                                 province_kill_request.main_quantity - province_kill_request.quantity) * poultry_request.Index_weight)
                    # hatching.free_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.free_quantity -= province_kill_request.total_killed_quantity
                    # hatching.free_quantity -= amount
                else:
                    hatching.governmental_killed_quantity -= int((
                                                                         province_kill_request.main_quantity - province_kill_request.quantity) * poultry_request.Index_weight)
                    # hatching.governmental_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.governmental_quantity -= province_kill_request.main_quantity - province_kill_request.quantity
                    # hatching.governmental_quantity -= amount
                # hatching.killed_quantity -= amount
                hatching.save()
                province_kill_request.main_quantity = province_kill_request.main_quantity - province_kill_request.quantity
                province_kill_request.quantity = 0
                province_kill_request.save()

            return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)
        queryset = ProvinceKillRequest.objects.get(key=request.GET['key'])
        poultry_request = PoultryRequest.objects.get(key=queryset.province_request.poultry_request.key)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
        check = KillHouseCheckRequest.objects.filter(province_kill_request=queryset, state='accepted')
        if check.count() > 0:
            return Response({"result": "can not delete"}, status=status.HTTP_403_FORBIDDEN)
        province = ProvinceCheckOperatorRequest.objects.get(key=queryset.province_request.key)
        province.quantity += queryset.quantity
        province.save()
        kill_request = KillRequest.objects.get(key=queryset.kill_request.key)
        kill_request.remain_quantity += queryset.quantity
        kill_request.save()
        # queryset.delete()
        poultry_request.remain_quantity += queryset.quantity
        poultry_request.save()
        if poultry_request.export == True:
            hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
            hatching.export_killed_quantity -= int(request.data['quantity'])
        elif poultry_request.free_sale_in_province == True:
            hatching.free_killed_quantity -= queryset.total_killed_weight
            # hatching.free_killed_quantity -= int(queryset.quantity * poultry_request.Index_weight)
            hatching.free_quantity -= queryset.total_killed_quantity
        else:
            hatching.governmental_killed_quantity -= queryset.total_killed_weight
            # hatching.governmental_killed_quantity -= int(
            #     queryset.quantity * poultry_request.Index_weight)
            hatching.governmental_quantity -= queryset.total_killed_quantity
        # hatching.killed_quantity -= queryset.total_killed_quantity
        hatching.save()
        bot_eitaa_for_each_delete_province_kill_request(queryset)
        queryset.delete()
        return Response(status=status.HTTP_200_OK)


class KillHouseWageForTotalDashbordViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseWageForTotalDashbordSerializer
    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).first()
        serializer = self.get_serializer(kill_house)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ProvinceKillRequestProvinceWageViewSet(viewsets.ModelViewSet):
    queryset = ProvinceKillRequest.objects.all()
    serializer_class = ProvinceKillRequestProvinceWageSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = ProvinceKillRequestFilterSet
    filterset_fields = [
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__poultry__address__city__name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',

    ]

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

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

            if request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX', 'Company', 'Guilds', 'Supporter']:
                if request.GET['type'] == 'unpaid':
                    if 'date1' in request.GET:

                        if request.GET['role'] == 'ProvinceOperator':
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                union_share__gt=0,
                                trash=False).order_by('kill_request__recive_date')
                        elif request.GET['role'] == 'Company':
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                company_share__gt=0,
                                trash=False).order_by('kill_request__recive_date')

                        elif request.GET['role'] == 'Guilds':
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                guilds_share__gt=0,
                                trash=False).order_by('kill_request__recive_date')

                        elif request.GET['role'] in ['SuperAdmin', 'AdminX', 'Supporter']:
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                kill_request__recive_date__date__gte=date1,
                                kill_request__recive_date__date__lte=date2,
                                trash=False).order_by('kill_request__recive_date')
                    else:
                        if request.GET['role'] == 'ProvinceOperator':
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                union_share__gt=0,
                                trash=False).order_by('kill_request__recive_date')
                        elif request.GET['role'] == 'Company':
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                company_share__gt=0,
                                trash=False).order_by('kill_request__recive_date')

                        elif request.GET['role'] == 'Guilds':
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                guilds_share__gt=0,
                                trash=False).order_by('kill_request__recive_date')

                        elif request.GET['role'] in ['SuperAdmin', 'AdminX', 'Supporter']:
                            province_kill_request = self.queryset.filter(
                                killhouse_user__key=request.GET['kill_house_key'],
                                state__in=('pending', 'accepted'),
                                return_to_province=False,
                                archive_wage=False,
                                trash=False).order_by('kill_request__recive_date')


            else:
                user = SystemUserProfile.objects.get(user=request.user, trash=False)
                kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)

                if request.GET['type'] == 'unpaid':
                    if 'date1' in request.GET:

                        province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
                                                                     state__in=('pending', 'accepted'),
                                                                     return_to_province=False,
                                                                     archive_wage=False,
                                                                     kill_request__recive_date__date__gte=date1,
                                                                     kill_request__recive_date__date__lte=date2,
                                                                     trash=False).order_by('kill_request__recive_date')
                    else:
                        province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
                                                                     state__in=('pending', 'accepted'), wage_pay=False,
                                                                     archive_wage=False,
                                                                     return_to_province=False,
                                                                     trash=False).order_by('kill_request__recive_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 (self.filterset_class(
                                    data=query,
                                    queryset=province_kill_request
                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=province_kill_request)
                                province_kill_request = ps.filter()
                    else:
                        province_kill_request = province_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(province_kill_request)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)

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


# class ProvinceKillRequestProvinceWageViewSet(viewsets.ModelViewSet):
#     queryset = ProvinceKillRequest.objects.all()
#     serializer_class = ProvinceKillRequestProvinceWageSerializer
#     pagination_class = CustomPagination
#     permission_classes = [TokenHasReadWriteScope]
#     filter_backends = [DjangoFilterBackend]
#     filterset_class = ProvinceKillRequestFilterSet
#     filterset_fields = [
#         'province_request__poultry_request__chicken_breed',
#         'province_request__poultry_request__order_code',
#         'province_request__poultry_request__poultry__address__city__name',
#         'province_request__poultry_request__poultry__user__mobile',
#         'province_request__poultry_request__poultry__user__fullname',
#
#     ]
#
#     def list(self, request, *args, **kwargs):
#         if 'type' in request.GET:
#             if 'date1' in request.GET:
#                 date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
#
#                 date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
#
#             if request.GET['role'] in ['ProvinceOperator', 'SuperAdmin']:
#                 if request.GET['type'] == 'unpaid':
#                     if 'date1' in request.GET:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__key=request.GET['kill_house_key'],
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      kill_request__recive_date__date__gte=date1,
#                                                                      kill_request__recive_date__date__lte=date2,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                     else:
#                         province_kill_request = self.queryset.filter(killhouse_user__key=request.GET['kill_house_key'],
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      trash=False).order_by('kill_request__recive_date')
#
#                 elif request.GET['type'] == 'archive':
#                     if 'date1' in request.GET:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__key=request.GET['kill_house_key'],
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=True,
#                                                                      return_to_province=False,
#                                                                      kill_request__recive_date__date__gte=date1,
#                                                                      kill_request__recive_date__date__lte=date2,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                     else:
#                         province_kill_request = self.queryset.filter(killhouse_user__key=request.GET['kill_house_key'],
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=True,
#                                                                      return_to_province=False,
#
#                                                                      trash=False).order_by('kill_request__recive_date')
#
#
#                 else:
#                     if 'date1' in request.GET:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__key=request.GET['kill_house_key'],
#                                                                      state__in=('pending', 'accepted'), wage_pay=True,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      kill_request__recive_date__date__gte=date1,
#                                                                      kill_request__recive_date__date__lte=date2,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                     else:
#                         province_kill_request = self.queryset.filter(killhouse_user__key=request.GET['kill_house_key'],
#                                                                      state__in=('pending', 'accepted'), wage_pay=True,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      trash=False).order_by('kill_request__recive_date')
#
#             else:
#                 user = SystemUserProfile.objects.get(user=request.user, trash=False)
#                 kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
#
#                 if request.GET['type'] == 'unpaid':
#                     if 'date1' in request.GET:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      kill_request__recive_date__date__gte=date1,
#                                                                      kill_request__recive_date__date__lte=date2,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                     else:
#                         province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                 elif request.GET['type'] == 'archive':
#                     if 'date1' in request.GET:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=True,
#                                                                      return_to_province=False,
#                                                                      kill_request__recive_date__date__gte=date1,
#                                                                      kill_request__recive_date__date__lte=date2,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                     else:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
#                                                                      state__in=('pending', 'accepted'), wage_pay=False,
#                                                                      archive_by_province=True,
#                                                                      return_to_province=False,
#                                                                      trash=False).order_by('kill_request__recive_date')
#
#                 else:
#
#                     if 'date1' in request.GET:
#
#                         province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
#                                                                      state__in=('pending', 'accepted'), wage_pay=True,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      kill_request__recive_date__date__gte=date1,
#                                                                      kill_request__recive_date__date__lte=date2,
#                                                                      trash=False).order_by('kill_request__recive_date')
#                     else:
#                         province_kill_request = self.queryset.filter(killhouse_user__in=kill_house,
#                                                                      state__in=('pending', 'accepted'), wage_pay=True,
#                                                                      archive_by_province=False,
#                                                                      return_to_province=False,
#                                                                      trash=False).order_by('kill_request__recive_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 (self.filterset_class(
#                                     data=query,
#                                     queryset=province_kill_request
#                             )
#                             ).filter():
#                                 ps = self.filterset_class(data=query, queryset=province_kill_request)
#                                 province_kill_request = ps.filter()
#                     else:
#                         province_kill_request = province_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(province_kill_request)
#             if page is not None:
#                 serializer = self.get_serializer(page, many=True)
#                 return self.get_paginated_response(serializer.data)
#
#             serializer = self.get_serializer(province_kill_request, many=True)
#             return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به تایید یا رد تخصیص از سمت استان توسط کشتارگاه
class KillHouseCheckRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHouseCheckRequest.objects.all()
    serializer_class = KillHouseCheckRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به تایید یا رد تخصیص از سمت استان توسط کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        # role = request.data['role']
        province_kill_house_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'],
                                                                      trash=False)
        kill_request = KillRequest.objects.get(id=province_kill_house_request.kill_request.id, trash=False)
        request.data.pop('province_kill_request_key')
        # request.data.pop('role')
        province_check = ProvinceCheckOperatorRequest.objects.get(id=province_kill_house_request.province_request.id,
                                                                  trash=False)
        poultry_request = PoultryRequest.objects.get(key=province_check.poultry_request.key)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            if KillHouseCheckRequest.objects.filter(province_kill_request=province_kill_house_request,
                                                    trash=False).exists():
                return Response({'result': 'already exist'}, status=status.HTTP_403_FORBIDDEN)
            kill_house_check_request = serializer.create(validated_data=request.data)
            kill_house_check_request.province_kill_request = province_kill_house_request

            if kill_house_check_request.state == 'accepted':
                province_kill_house_request.state = 'accepted'
                province_kill_house_request.save()
                # barcode = kill_house_request.bar_code
                # driver_mobile = kill_house_request.car['driver_mobile']
                # driver_name = kill_house_request.car['driver_name']
                # quantity = kill_house_request.quantity
                # kill_house = kill_house_request.kill_request.kill_house.name
                # poultry = kill_house_request.province_request.city_request_Poultry.poultry_request.user.fullname
                # province = kill_house_request.province_request.city_request_Poultry.poultry_request.user.address.province
                # city = kill_house_request.province_request.city_request_Poultry.poultry_request.user.address.city
                # address = kill_house_request.province_request.city_request_Poultry.poultry_request.user.address.address
                # date = kill_house_request.province_request.city_request_Poultry.poultry_request.send_date.date()
                # date = (str(jdatetime.datetime.fromgregorian(year=date.year, month=date.month, day=date.day).date()))
                # time1 = kill_request.recive_time
                # list1 = reversed(date.split('-'))
                # s = "-"
                # date1 = s.join(list1)
                # time = reversed(kill_request.recive_time.split('-'))
                # o = "-"
                # time1 = o.join(time)
                # driver_sms(driver_mobile, driver_name, quantity, poultry, barcode, province, city, address, date,
                #            time1,
                #            kill_house)
            elif kill_house_check_request.state == 'rejected':
                if poultry_request.free_sale_in_province == True:
                    hatching.free_killed_quantity -= int(
                        province_kill_house_request.main_quantity * poultry_request.Index_weight)
                    hatching.free_killed_quantity -= province_kill_house_request.main_quantity
                else:
                    hatching.governmental_killed_quantity -= int(
                        province_kill_house_request.main_quantity * poultry_request.Index_weight)
                    hatching.governmental_quantity -= province_kill_house_request.main_quantity
                # hatching.killed_quantity -= province_kill_house_request.main_quantity
                hatching.save()
                province_kill_house_request.state = 'rejected'
                province_kill_house_request.message = kill_house_check_request.message
                province_kill_house_request.save()
                province_check.quantity += province_kill_house_request.quantity
                province_check.save()
                # kill_request.cars.append(kill_house_request.car)
                kill_request.remain_quantity += province_kill_house_request.quantity
                kill_request.save()
                poultry_request.remain_quantity += province_kill_house_request.quantity
                poultry_request.save()
            # kill_house_check_request.role = {
            #     "role": role,
            #     "name": user.fullname,
            #     "mobile": user.mobile
            # }
            kill_house_check_request.save()
            if kill_house_check_request.state == 'accepted':
                # if SmsLicense.objects.filter().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()
                province_operator_mobile = province_operator.user.mobile
                province_operator_name = province_operator.user.fullname
                kill_house_name = kill_house_check_request.province_kill_request.kill_request.kill_house.name
                kill_house_mobile = kill_house_check_request.province_kill_request.kill_request.kill_house.kill_house_operator.user.mobile
                quantity = kill_house_check_request.province_kill_request.quantity
                chicken_breed = kill_house_check_request.province_kill_request.province_request.poultry_request.chicken_breed
                poultry_name = kill_house_check_request.province_kill_request.province_request.poultry_request.poultry.unit_name
                poultry_mobile = kill_house_check_request.province_kill_request.province_request.poultry_request.poultry.user.mobile
                Index_weight = kill_house_check_request.province_kill_request.province_request.poultry_request.Index_weight
                date_str = str(
                    kill_house_check_request.province_kill_request.province_request.poultry_request.send_date)
                send_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').date()
                send_date = jdatetime.datetime.fromgregorian(year=send_date.year, month=send_date.month,
                                                             day=send_date.day).strftime('%Y-%m-%d')
                date_list = reversed(send_date.split('-'))
                separate = "-"
                send_date = separate.join(date_list)
                province = kill_house_check_request.province_kill_request.province_request.poultry_request.poultry.address.province.name
                city = kill_house_check_request.province_kill_request.province_request.poultry_request.poultry.address.city.name
                # kill_house_province_kill_request_accept_to_province_sms(province_operator_mobile,
                #                                                         province_operator_name, quantity,
                #                                                         chicken_breed, send_date, poultry_name,
                #                                                         poultry_mobile, province, city, kill_house_name,
                #
                #                                                         )

            kill_house_check_request_serializer = self.serializer_class(kill_house_check_request)
            return Response(kill_house_check_request_serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)


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

    def update(self, request, pk=None, *args, **kwargs):
        kill_house_request = KillHouseRequest.objects.get(key=request.data['kill_house_request_key'], trash=False)
        request.data.pop('kill_house_request_key')
        kill_house = kill_house_request.killhouse_user
        bar_date = kill_house_request.kill_request.recive_date.date() + timedelta(days=1)
        now = datetime.now().date()
        product = RolesProducts.objects.filter(parent_product__product_id=2, kill_house=kill_house).first()
        if not product:
            return Response(
                {"result": "جهت افزایش موجودی محصول ابتدا محصول را برای کشتارگاه ثبت کنید! "},
                status=status.HTTP_403_FORBIDDEN)
        if kill_house_request.date_of_ware_house:
            if now != datetime.strptime(kill_house_request.date_of_ware_house, '%Y-%m-%d %H:%M:%S.%f').date():
                return Response(
                    {"result": "بازه زمانی ویرایش این بار به اتمام رسیده ! "},
                    status=status.HTTP_403_FORBIDDEN)
            input_weight = request.data['ware_house_accepted_real_weight'] if request.data[
                                                                                  'input_type'] == 'input_weight' else int(
                kill_house_request.accepted_real_weight - (
                        (kill_house_request.accepted_real_weight * request.data['loss_percent']) / 100))
            if kill_house_request.ware_house_accepted_real_weight > input_weight:
                diffrence = kill_house_request.ware_house_accepted_real_weight - input_weight
                if product.total_remain_weight - diffrence < 0:
                    return Response(
                        {"result": "به علت منفی شدن موجودی انبار امکان ویرایش وجود ندارد! "},
                        status=status.HTTP_403_FORBIDDEN)

        if request.data['input_type'] == 'input_weight':
            kill_house_request.ware_house_accepted_real_quantity = request.data['ware_house_accepted_real_quantity']
            kill_house_request.ware_house_accepted_real_weight = request.data['ware_house_accepted_real_weight']
            kill_house_request.weight_loss = request.data['loss_percent']
        else:
            # kill_house_request.ware_house_accepted_real_quantity = int(kill_house_request.accepted_real_quantity - (
            #         (kill_house_request.accepted_real_quantity * request.data['loss_percent']) / 100))
            kill_house_request.ware_house_accepted_real_quantity = kill_house_request.accepted_real_quantity
            kill_house_request.ware_house_accepted_real_weight = int(kill_house_request.accepted_real_weight - (
                    (kill_house_request.accepted_real_weight * request.data['loss_percent']) / 100))
            kill_house_request.weight_loss = request.data['loss_percent']
        poultry_prediction(kill_house_request.province_request.poultry_request.poultry)

        kill_house_request.ware_house_input_type = request.data['input_type']
        kill_house_request.ware_house_confirmation = True
        kill_house_request.date_of_ware_house = str(datetime.now())
        govermental_commitment_percent = kill_house.in_province_governmental_selling_percent
        free_commitment_percent = kill_house.in_province_free_selling_percent
        if kill_house_request.province_request.poultry_request.free_sale_in_province:
            kill_house_request.warehouse_commitment_weight = int(
                (free_commitment_percent / 100) * kill_house_request.ware_house_accepted_real_weight)
        else:
            kill_house_request.warehouse_commitment_weight = int(
                (govermental_commitment_percent / 100) * kill_house_request.ware_house_accepted_real_weight)
        if 'input_warehouse' in request.data.keys():
            if request.data['input_warehouse'] == 'self':
                kill_house_request.input_warehouse = kill_house_request.killhouse_user
            else:
                kill_house_request.input_warehouse = kill_house_request.killer
                product = RolesProducts.objects.filter(parent_product__product_id=2,
                                                       kill_house=kill_house_request.killer).first()

        else:
            kill_house_request.input_warehouse = kill_house_request.killhouse_user

        kill_house_request.save()
        kill_house_requests_product_warehousing(product)
        return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)


#  ویوست مربوط به ایجاد درخواست کشتار توسط کشتارگاه بعد از تخصیص
class KillHouseRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    #  تابع مربوط به ایجاد درخواست کشتار توسط کشتارگاه بعد از تخصیص
    def create(self, request, *args, **kwargs):

        limitation_direct_purchase = LimitationForDirectPurchaseAndBarInformation.objects.filter(
            trash=False, active=True).first()
        is_in_limitation_range = False

        if limitation_direct_purchase and limitation_direct_purchase.start_time and limitation_direct_purchase.end_time:
            current_time = datetime.now().time()
            if limitation_direct_purchase.start_time <= current_time <= limitation_direct_purchase.end_time:
                is_in_limitation_range = True

        if not is_in_limitation_range:
            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") == "kill_house_request" and t.get("active", False)),
                    None)
                if time:
                    start_hour = datetime.strptime(time.get("start", 0), "%H:%M:%S").time()
                    end_hour = datetime.strptime(time.get("end", 0), "%H:%M:%S").time()
                    current_hour = datetime.now().time().replace(second=0, microsecond=0)
                    if not (start_hour < current_hour < end_hour):
                        return Response(
                            {"result": "لطفا در ساعات مجاز برای ثبت درخواست اقدام نمایید!"},
                            status=status.HTTP_403_FORBIDDEN)
        real_car = None
        killer_for_kill_house = None
        if 'real_car_key' in request.data.keys():
            real_car = KillHouseADDCAR.objects.get(key=request.data['real_car_key'], trash=False)
            request.data.pop('real_car_key')
        date_time_of_now = datetime.now().date()
        tomorrow = datetime.now().date() + timedelta(days=1)
        role = request.data['role']
        request.data.pop('role')
        dict1 = {}
        try:
            kill_house_auction_winner_key = request.data['winner_key']

            kill_house_auction_winner = KillHouseRequestActionWinner.objects.get(key=kill_house_auction_winner_key,
                                                                                 trash=False)
            kill_house = kill_house_auction_winner.kill_house_request_auction.kill_house
            request.data.pop('winner_key')

        except:
            kill_house_auction_winner = None

        try:
            kill_house_check_key = request.data['kill_house_check_key']

            kill_house_check = KillHouseCheckRequest.objects.get(key=kill_house_check_key, trash=False)
            kill_house = kill_house_check.province_kill_request.kill_request.kill_house
            request.data.pop('kill_house_check_key')

        except:
            kill_house_check = None
        if kill_house_check != None:
            kill_house = KillHouse.objects.get(id=kill_house_check.province_kill_request.kill_request.kill_house.id,
                                               trash=False)
            kill_req = KillRequest.objects.get(id=kill_house_check.province_kill_request.kill_request.id, trash=False)
            if OperationLimitation.objects.all().first().kill_house_allocation_limitation == True:

                if date_time_of_now != kill_req.recive_date.date():
                    # if date_time_of_now > kill_req.recive_date.date() + timedelta(days=1):
                    return Response({"result": "مغایرت در تاریخ اعلام نیاز کشتار گاه و تاریخ تخصیص به خودرو !"},
                                    status=status.HTTP_403_FORBIDDEN)
            province_request = ProvinceCheckOperatorRequest.objects.get(
                id=kill_house_check.province_kill_request.province_request.id, trash=False)
            province_kill_request = ProvinceKillRequest.objects.get(id=kill_house_check.province_kill_request.id,
                                                                    trash=False)
            if province_kill_request.market:
                if province_kill_request.first_car_allocated_quantity > 0:
                    if province_kill_request.total_killed_quantity + request.data[
                        'quantity'] > province_kill_request.main_quantity:
                        return Response(
                            {"result": "مجموع  حجم ماشین های ایجاد شده بیشتر از تخصیص  داده شده از پنل معاملات میباشد"},
                            status=status.HTTP_403_FORBIDDEN)
                else:
                    if request.data['quantity'] > province_kill_request.main_quantity:
                        return Response(
                            {"result": "مجموع  حجم ماشین های ایجاد شده بیشتر از تخصیص  داده شده از پنل معاملات میباشد"},
                            status=status.HTTP_403_FORBIDDEN)
            poultry_request = PoultryRequest.objects.get(key=province_request.poultry_request.key)
            poultry_hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)

            user = province_request.city_request_Poultry.poultry_request.poultry.user
            if province_kill_request.quantity == 0:
                return Response({"result": "quantity is 0"}, status=status.HTTP_403_FORBIDDEN)
        elif kill_house_auction_winner != None:
            user = kill_house_auction_winner.kill_house_request_auction.poultry_request.poultry.user
            kill_house = KillHouse.objects.get(id=kill_house_auction_winner.kill_house_request_auction.kill_house.id,
                                               trash=False)
        if 'killer_key' in request.data.keys():
            if request.data['killer_key'] != None:
                killer_for_kill_house = KillHouse.objects.get(key=request.data['killer_key'], trash=False)
                if kill_house.id != killer_for_kill_house.id:
                    kill_house_purchase = KillHousePurchaseRequest.objects.filter(limitation=True,
                                                                                  kill_house=killer_for_kill_house).first()
                    if kill_house_purchase:
                        total_unpaid_wage = 0
                        total_paid_wage = 0

                        total_unpaid_wage = get_finance_info(killer_for_kill_house)['total_price']
                        slaughter_transactions = InternalTransaction.objects.filter(
                            kill_house=killer_for_kill_house, status='completed',
                            trash=False)

                        total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[
                                               'total'] or 0
                        total_amount = total_unpaid_wage - total_paid_wage
                        if total_amount >= kill_house_purchase.limitation_number:
                            return Response(
                                {
                                    "result": "به علت بدهی کشتارکن اختصاصی امکان ایجاد بار برای کشتار کن امکان پذیر نیست!"},
                                status=status.HTTP_403_FORBIDDEN)
            request.data.pop('killer_key')

        car = request.data['car']
        add_car = KillHouseADDCAR.objects.get(key=car['key'], trash=False)
        request.data.pop('car')
        if request.data['quantity'] > (poultry_hatching.left_over + province_kill_request.main_quantity + (
                (poultry_hatching.quantity * 5) / 100)):
            return Response({"result": "تعداد قطعه وارد شده بیشتراز مانده در سالن مرغدار است!"},
                            status=status.HTTP_403_FORBIDDEN)
        if kill_house.max_kill_limit and kill_house.total_kill_capacity > 0:
            extra_bar_kill_percent = (kill_house.extra_bar_kill_percent / 100) * kill_house.total_kill_capacity

            total_province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                                              archive_wage=False,
                                                                              state__in=('pending', 'accepted'),
                                                                              killhouse_user=kill_house,
                                                                              first_car_allocated_quantity=0,
                                                                              kill_request__recive_date__date=kill_req.recive_date.date()).exclude(
                id=kill_house_check.province_kill_request.id)

            total_province_kill_requests_quantity_with_out_bar = \
                total_province_kill_requests.aggregate(total=Sum('total_killed_quantity'))['total'] or 0

            total_kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                                        archive_wage=False,
                                                                        killhouse_user=kill_house,
                                                                        kill_request__recive_date__date=kill_req.recive_date.date())
            total_kill_house_requests_quantity = \
                total_kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0

            if (
                    kill_house.total_kill_capacity + extra_bar_kill_percent) < total_kill_house_requests_quantity + \
                    request.data['quantity'] + total_province_kill_requests_quantity_with_out_bar:
                return Response({"result": "تعداد وارد شده از مانده سهمیه کشتار روزانه کشتارگاه بیشتر است !"},
                                status=status.HTTP_403_FORBIDDEN)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_request = serializer.create(validated_data=request.data)
            kill_house_request.accepted_real_quantity = int(kill_house_request.quantity)
            kill_house_request.accepted_real_weight = float(
                kill_house_request.quantity) * kill_house_check.province_kill_request.province_request.poultry_request.Index_weight
            if kill_house_check != None:
                bar_code = KillHouseRequest.objects.filter(
                    province_request__city_request_Poultry__poultry_request__poultry__user=user, trash=False)

            else:
                bar_code = KillHouseRequest.objects.filter(
                    kill_house_request_auction_winner__kill_house_request_auction__poultry_request__poultry__user=user,
                    trash=False)
            if bar_code.count() > 0:
                bar_code = bar_code.order_by(
                    'create_date')
                if bar_code.last().bar_code != None:
                    kill_house_request.bar_code = bar_code.last().bar_code + 1

            else:
                if kill_house_check != None:
                    kill_house_request.bar_code = int(
                        str(province_request.city_request_Poultry.poultry_request.order_code) + '0001')
                else:
                    kill_house_request.bar_code = int(
                        str(kill_house_auction_winner.kill_house_request_auction.poultry_request.order_code) + '0001')

            if kill_house_check != None:
                kill_house_request.kill_request = kill_req
                kill_house_request.province_request = province_request
                kill_house_request.fee = kill_house_check.province_kill_request.fee
                kill_house_request.province_kill_request = province_kill_request
                kill_house_request.amount = province_kill_request.kill_house_price
                if kill_house_check.state == 'accepted':
                    kill_house_request.state = "accepted"
                kill_house_request.save()

            else:

                kill_house_request.kill_house_request_auction_winner = kill_house_auction_winner
                kill_house_request.state = "accepted"
                kill_house_request.fee = kill_house_auction_winner.fee
                kill_house_request.auction = True
                kill_house_auction_winner.quantity -= int(kill_house_request.quantity)
                kill_house_auction_winner.save()
                kill_house_request.role = {
                    'role': role,
                    'name': user.fullname,
                    'mobile': user.mobile
                }
                kill_house_request.save()

            kill_house_request.car = car
            kill_house_request.add_car = add_car
            if real_car != None:
                kill_house_request.real_add_car = real_car
            if killer_for_kill_house != None:
                kill_house_request.killer = killer_for_kill_house
            kill_house_request.killhouse_user = kill_house
            kill_house_request.show_kill_house = "accepted"
            kill_house_request.save()
            province_kill_request.first_car_allocated_quantity += kill_house_request.quantity
            province_kill_request.save()

            kill_house_request_serializer = self.serializer_class(kill_house_request)

            ware_house = KillHouseWareHouse.objects.filter(kill_house=kill_house, date__date=tomorrow).first()
            if not ware_house:
                ware_house = KillHouseWareHouse(
                    kill_house=kill_house,
                    date=tomorrow
                )
                ware_house.save()

            update_kill_house_requests(province_kill_request, poultry_request)
            update_province_kill_requests(poultry_hatching)
            poultry_prediction(poultry_hatching.poultry)
            vet_farm = VetFarm.objects.filter(trash=False,
                                              poultry=kill_house_request.province_request.poultry_request.poultry).first()
            if vet_farm:
                car_allocation_vet_farm_sms(kill_house_request.kill_request.recive_date.date(),
                                            kill_house_request.province_request.poultry_request.poultry.user.fullname,
                                            kill_house_request.province_request.poultry_request.hatching.chicken_age,
                                            kill_house_request.quantity, kill_house_request.add_car.driver.type_car,
                                            kill_house_request.traffic_code,
                                            kill_house_request.add_car.driver.pelak,
                                            kill_house_request.kill_request.kill_house.name,
                                            vet_farm.vet.user.mobile,
                                            kill_house_request.province_request.poultry_request.amount,
                                            kill_house_request.province_request.poultry_request.free_sale_in_province)

            if kill_house_check != None:

                dict1 = {
                    "kill_house_req_key": str(kill_house_request.key),
                    "kill_req_key": kill_house_request.kill_request.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_city": kill_house_request.kill_request.kill_house.system_address.city.name,
                    "kill_house_mobile": kill_house_request.kill_request.kill_house.kill_house_operator.user.mobile,
                    "quantity": kill_house_request.quantity,
                    "time": kill_house_request.kill_request.recive_time,
                    "date": kill_house_request.kill_request.recive_date,
                    "car": kill_house_request.car,
                }
            elif kill_house_auction_winner != None:

                dict1 = {
                    "kill_house_req_key": str(kill_house_request.key),
                    "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_city": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.system_address.city.name,
                    "kill_house_mobile": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                    "quantity": kill_house_request.quantity,
                    "date": kill_house_request.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.send_date,
                    "car": kill_house_request.car,
                }

            # ارسال بار به ایتای دامپزشک (فقط برای همدان و در ساعات 16 تا 23:59)
            if base_url_for_sms_report == 'ha':
                current_hour = datetime.now().hour
                if 16 <= current_hour <= 23:
                    try:
                        send_single_bar_to_eitaa(kill_house_request)
                    except Exception as e:
                        pass

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

    #  تابع مربوط به نمایش درخواست کشتار های ایجاد شده توسط کشتارگاه بعد از تخصیص
    def list(self, request, *args, **kwargs):
        from django.db.models import Q
        info_dict = []
        info_list = []
        # refresh(request.user.id)

        if request.GET['operator'] == 'ProvinceOperator':
            queryset = KillHouseRequest.objects.filter(trash=False).order_by('create_date')
            serializer = KillHouseRequestSerializer(queryset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        elif request.GET['operator'] == 'VetSupervisor':
            now = datetime.now().date()
            date1 = datetime.strptime(str(request.GET['date1']),
                                      '%Y-%m-%d').date() if 'date1' in request.GET else now
            date2 = datetime.strptime(str(request.GET['date2']),
                                      '%Y-%m-%d').date() if 'date2' in request.GET else now

            querysets_list = KillHouseRequest.objects.filter(
                vet_state__in=('pending', 'accepted'),
                active_state__in=('active', 'inactive'), trash=False).order_by(
                'create_date')
            queryset = [
                queryset_list for queryset_list in querysets_list
                if date1 <= queryset_list.province_request.poultry_request.send_date.date() <= date2
            ]
            if len(queryset) > 0:
                info_list = []

                for kill_house_req_obj in queryset:
                    kill_place = kill_house_req_obj.kill_request.kill_house.name if not kill_house_req_obj.kill_request.slaughter_house else kill_house_req_obj.kill_request.slaughter_house.name
                    real_car = None
                    if kill_house_req_obj.real_add_car != None:
                        real_car = {
                            "real_driver_name": kill_house_req_obj.real_add_car.driver.driver_name,
                            "real_driver_mobile": kill_house_req_obj.real_add_car.driver.driver_mobile,
                            "real_pelak": kill_house_req_obj.real_add_car.driver.pelak,
                            "real_type_car": kill_house_req_obj.real_add_car.driver.type_car
                        }
                    exclusive_killer = None
                    if kill_house_req_obj.killer != None:
                        exclusive_killer = {
                            "killer_name": kill_house_req_obj.killer.name,
                            "killer_mobile": kill_house_req_obj.killer.kill_house_operator.user.mobile,
                            "killer_fullname": kill_house_req_obj.killer.kill_house_operator.user.fullname,
                        }
                    vet_check_date = None
                    vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_req_obj).first()
                    if vet_check:
                        vet_check_date = vet_check.create_date
                    if kill_house_req_obj.province_kill_request != None:

                        internal_dict_infos = {
                            "poultry_request_id": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.id,
                            "poultry_request_key": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.key,
                            "chicken_breed": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.chicken_breed,
                            "index_weight": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.Index_weight,
                            "amount": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.amount,
                            "bar_amount": kill_house_req_obj.amount,
                            "poultry_name": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.fullname,
                            "poultry_mobile": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.mobile,
                            "send_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.send_date,
                            "create_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.create_date,
                            "poultry_request_quantity": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.quantity,
                            "poultry_city": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.city.name,
                            "poultry_province": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.province.name,
                            "barcod": kill_house_req_obj.bar_code,
                            "order_code": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.order_code,
                            "freezing": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.freezing,
                            "kill_house_name": kill_house_req_obj.kill_request.kill_house.name,
                            "kill_house_mobile": kill_house_req_obj.kill_request.kill_house.kill_house_operator.user.mobile,
                            "quantity": kill_house_req_obj.quantity,
                            "time": kill_house_req_obj.kill_request.recive_time,
                            "date": kill_house_req_obj.kill_request.recive_date,
                            "accepted_real_quantity": kill_house_req_obj.accepted_real_quantity,
                            "accepted_real_weight": kill_house_req_obj.accepted_real_weight,
                            "kill_house_request_key": kill_house_req_obj.key,
                            "clearance_code": kill_house_req_obj.clearance_code,
                            "vet_state": kill_house_req_obj.vet_state,
                            "traffic_code": kill_house_req_obj.traffic_code,
                            "driver_name": kill_house_req_obj.add_car.driver.driver_name,
                            "driver_mobile": kill_house_req_obj.add_car.driver.driver_mobile,
                            "pelak": kill_house_req_obj.add_car.driver.pelak,
                            "car_key": kill_house_req_obj.add_car.key,
                            "type_car": kill_house_req_obj.add_car.driver.type_car,
                            "real_car": real_car,
                            "killer": exclusive_killer,
                            "age": (
                                           datetime.now() - kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.hatching.date).days + 1,

                            "vet_check_date": vet_check_date,
                            "first_weight": kill_house_req_obj.quantity * kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.Index_weight,
                            "kill_place": kill_place,
                            "auction": "False"
                        }
                    elif kill_house_req_obj.kill_house_request_auction_winner != None:

                        internal_dict_infos = {
                            "poultry_request_id": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.id,
                            "poultry_request_key": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.key,
                            "poultry_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.fullname,
                            "mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.mobile,
                            "city": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.city.name,
                            "province": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.province.name,
                            "send_date": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.send_date,
                            "freezing": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.freezing,
                            "create_date": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.create_date,
                            "poultry_quantity": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.quantity,
                            "barcod": kill_house_req_obj.bar_code,
                            "kill_house_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.name,
                            "kill_house_mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                            "quantity": kill_house_req_obj.quantity,
                            "time": kill_house_req_obj.kill_request.recive_time,
                            "date": kill_house_req_obj.kill_request.recive_date,
                            "kill_house_request_key": kill_house_req_obj.key,
                            "auction": "True"

                        }

                    info_list.append(internal_dict_infos)
                # info_dict.append(info_list)
            return Response(info_list, status=status.HTTP_200_OK)

        elif request.GET['operator'] == 'KillHouseVet':
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            # vet = Vet.objects.get(user=user, trash=False)
            kill_house_vet = KillHouseVet.objects.filter(vet__user=user, trash=False)
            kill_house_list = kill_house_vet.values_list('kill_house', flat=True).distinct()
            # for kill_house in kill_house_vet:
            #     kill_house_list.append(kill_house.kill_house)

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

            queryset = KillHouseRequest.objects.filter(
                Q(killhouse_user__in=kill_house_list) | Q(
                    kill_request__slaughter_house__in=kill_house_list),
                province_request__poultry_request__send_date__date__gte=date1,
                province_request__poultry_request__send_date__date__lte=date2,
                vet_state__in=('pending', 'accepted'),
                active_state__in=('active', 'inactive'), trash=False).order_by(
                'create_date')
            # queryset = [
            #     queryset_list for queryset_list in querysets_list
            #     if date1 <= queryset_list.province_request.poultry_request.send_date.date() <= date2
            # ]
            if len(queryset) > 0:
                info_dict = []
                info_list = []

                for kill_house_req_obj in queryset:
                    kill_place = kill_house_req_obj.kill_request.kill_house.name if not kill_house_req_obj.kill_request.slaughter_house else kill_house_req_obj.kill_request.slaughter_house.name
                    vet_check_date = None
                    real_car = None
                    if kill_house_req_obj.real_add_car != None:
                        real_car = {
                            "real_driver_name": kill_house_req_obj.real_add_car.driver.driver_name,
                            "real_driver_mobile": kill_house_req_obj.real_add_car.driver.driver_mobile,
                            "real_pelak": kill_house_req_obj.real_add_car.driver.pelak,
                            "real_type_car": kill_house_req_obj.real_add_car.driver.type_car
                        }
                    exclusive_killer = None
                    if kill_house_req_obj.killer != None:
                        exclusive_killer = {
                            "killer_name": kill_house_req_obj.killer.name,
                            "killer_mobile": kill_house_req_obj.killer.kill_house_operator.user.mobile,
                            "killer_fullname": kill_house_req_obj.killer.kill_house_operator.user.fullname,
                        }
                    vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_req_obj).first()
                    if vet_check:
                        vet_check_date = vet_check.create_date
                    if kill_house_req_obj.province_kill_request != None:

                        internal_dict_infos = {
                            "poultry_request_id": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.id,
                            "poultry_request_key": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.key,
                            "chicken_breed": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.chicken_breed,
                            "index_weight": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.Index_weight,
                            "amount": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.amount,
                            "bar_amount": kill_house_req_obj.amount,
                            "poultry_name": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.fullname,
                            "poultry_mobile": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.mobile,
                            "send_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.send_date,
                            "freezing": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.freezing,
                            "create_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.create_date,
                            "poultry_request_quantity": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.quantity,
                            "poultry_city": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.city.name,
                            "poultry_province": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.province.name,
                            "barcod": kill_house_req_obj.bar_code,
                            "order_code": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.order_code,
                            "kill_house_name": kill_house_req_obj.kill_request.kill_house.name,
                            "kill_house_mobile": kill_house_req_obj.kill_request.kill_house.kill_house_operator.user.mobile,
                            "quantity": kill_house_req_obj.quantity,
                            "time": kill_house_req_obj.kill_request.recive_time,
                            "date": kill_house_req_obj.kill_request.recive_date,
                            "accepted_real_quantity": kill_house_req_obj.accepted_real_quantity,
                            "accepted_real_weight": kill_house_req_obj.accepted_real_weight,
                            "kill_house_request_key": kill_house_req_obj.key,
                            "clearance_code": kill_house_req_obj.clearance_code,
                            "vet_state": kill_house_req_obj.vet_state,
                            "traffic_code": kill_house_req_obj.traffic_code,
                            "driver_name": kill_house_req_obj.add_car.driver.driver_name,
                            "driver_mobile": kill_house_req_obj.add_car.driver.driver_mobile,
                            "pelak": kill_house_req_obj.add_car.driver.pelak,
                            "car_key": kill_house_req_obj.add_car.key,
                            "type_car": kill_house_req_obj.add_car.driver.type_car,
                            "real_car": real_car,
                            "killer": exclusive_killer,
                            "first_weight": kill_house_req_obj.quantity * kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.Index_weight,
                            "age": (
                                           datetime.now() - kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.hatching.date).days + 1,

                            "vet_check_date": vet_check_date,
                            "kill_place": kill_place,
                            "auction": "False"
                        }
                    elif kill_house_req_obj.kill_house_request_auction_winner != None:

                        internal_dict_infos = {
                            "poultry_request_id": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.id,
                            "poultry_request_key": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.key,
                            "poultry_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.fullname,
                            "mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.mobile,
                            "city": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.city.name,
                            "province": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.province.name,
                            "send_date": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.send_date,
                            "freezing": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.freezing,
                            "create_date": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.create_date,
                            "poultry_quantity": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.quantity,
                            "barcod": kill_house_req_obj.bar_code,
                            "kill_house_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.name,
                            "kill_house_mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                            "quantity": kill_house_req_obj.quantity,
                            "time": kill_house_req_obj.kill_request.recive_time,
                            "date": kill_house_req_obj.kill_request.recive_date,
                            "kill_house_request_key": kill_house_req_obj.key,
                            "auction": "True"

                        }

                    info_list.append(internal_dict_infos)
                # info_dict.append(info_list)
            return Response(info_list, status=status.HTTP_200_OK)

        elif request.GET['operator'] == 'KillHouse':
            # info_dict = []
            info_list = []
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            now = datetime.now().date()
            date1 = datetime.strptime(str(request.GET['date1']),
                                      '%Y-%m-%d').date() if 'date1' in request.GET else now
            date2 = datetime.strptime(str(request.GET['date2']),
                                      '%Y-%m-%d').date() if 'date2' in request.GET else now
            if 'role' in request.GET:
                if request.GET['role'] == 'KillHouseVet':
                    vet = Vet.objects.filter(user=user, trash=False)
                    if vet.count() > 0:
                        kill_house_list = []
                        vet = vet.last()
                        kill_house_vet = KillHouseVet.objects.filter(vet=vet, trash=False)
                        for k_vet in kill_house_vet:
                            kill_house_list.append(k_vet.kill_house)
                        # kill_house = KillHouse.objects.filter(key=kill_house_vet.kill_house.key, trash=False)
                        kill_house_allow_vet = KillHouseAllowVet.objects.filter(kill_house__in=kill_house_list)

                        if kill_house_allow_vet.count() > 0:

                            kill_house_allow_vet = kill_house_allow_vet.last()
                            if vet != None and kill_house_allow_vet.allow == False:
                                return Response(info_list)

                        kill_requests_list = KillHouseRequest.objects.filter((Q(killhouse_user__in=kill_house_list) | Q(
                            kill_request__slaughter_house__in=kill_house_list)),
                                                                             active_state__in=('active', 'inactive'),
                                                                             trash=False)
                        now = datetime.now().date()
                        date1 = datetime.strptime(str(request.GET['date1']),
                                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
                        date2 = datetime.strptime(str(request.GET['date2']),
                                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
                        kill_requests = [
                            kill_request_list for kill_request_list in kill_requests_list
                            if date1 <= kill_request_list.kill_request.recive_date.date() <= date2
                        ]
                        for kill_house_req_obj in kill_requests:
                            vet_check_date = None
                            real_car = None
                            if kill_house_req_obj.real_add_car != None:
                                real_car = {
                                    "real_driver_name": kill_house_req_obj.real_add_car.driver.driver_name,
                                    "real_driver_mobile": kill_house_req_obj.real_add_car.driver.driver_mobile,
                                    "real_pelak": kill_house_req_obj.real_add_car.driver.pelak,
                                    "real_type_car": kill_house_req_obj.real_add_car.driver.type_car
                                }
                            exclusive_killer = None
                            if kill_house_req_obj.killer != None:
                                exclusive_killer = {
                                    "killer_name": kill_house_req_obj.killer.name,
                                    "killer_mobile": kill_house_req_obj.killer.kill_house_operator.user.mobile,
                                    "killer_fullname": kill_house_req_obj.killer.kill_house_operator.user.fullname,
                                }
                            vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_req_obj).first()
                            if vet_check:
                                vet_check_date = vet_check.create_date
                            if kill_house_req_obj.province_kill_request != None:
                                check = KillHouseCheckRequest.objects.get(
                                    province_kill_request=kill_house_req_obj.province_kill_request)
                                bar_info = KillHouseAssignmentInformation.objects.filter(
                                    kill_house_request=kill_house_req_obj)
                                if bar_info.count() > 0:
                                    bar_info = bar_info.last()
                                    assignment_info = {
                                        "kill_house_assignment_key": bar_info.key,
                                        "kill_house_weight_without_load": bar_info.car_weight_without_load,
                                        "kill_house_weight_with_load": bar_info.car_weight_with_load,
                                        "kill_house_image_without_load": bar_info.car_weight_without_load_image,
                                        "kill_house_image_with_load": bar_info.car_weight_with_load_image,
                                        "kill_house_net_weight": bar_info.net_weight,
                                        "driver_name": bar_info.kill_house_request.add_car.driver.driver_name,
                                        "pelak": bar_info.kill_house_request.add_car.driver.pelak,
                                        "type_car": bar_info.kill_house_request.add_car.driver.type_car,
                                        "kill_house_assignment_state": bar_info.state,
                                        "real_quantity": bar_info.real_quantity,

                                    }
                                else:
                                    assignment_info = None

                                internal_dict_infos = {
                                    "poultry_request_id": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.id,
                                    "poultry_request_key": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.key,
                                    "amount": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.amount,
                                    "bar_amount": kill_house_req_obj.amount,
                                    "poultry_name": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.fullname,
                                    "poultry_mobile": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.mobile,
                                    "send_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.send_date,
                                    "freezing": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.freezing,
                                    "create_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.create_date,
                                    "poultry_request_quantity": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.quantity,
                                    "poultry_city": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.city.name,
                                    "poultry_province": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.province.name,
                                    "barcod": kill_house_req_obj.bar_code,
                                    "order_code": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.order_code,
                                    "kill_house_name": kill_house_req_obj.kill_request.kill_house.name,
                                    "kill_house_mobile": kill_house_req_obj.kill_request.kill_house.kill_house_operator.user.mobile,
                                    "quantity": kill_house_req_obj.quantity,
                                    "time": kill_house_req_obj.kill_request.recive_time,
                                    "date": kill_house_req_obj.kill_request.recive_date,
                                    "kill_house_request_key": kill_house_req_obj.key,
                                    "vet_state": kill_house_req_obj.vet_state,
                                    "traffic_code": kill_house_req_obj.traffic_code,
                                    "driver_name": kill_house_req_obj.add_car.driver.driver_name,
                                    "driver_mobile": kill_house_req_obj.add_car.driver.driver_mobile,
                                    "pelak": kill_house_req_obj.add_car.driver.pelak,
                                    "car_key": kill_house_req_obj.add_car.key,
                                    "type_car": kill_house_req_obj.add_car.driver.type_car,
                                    "real_car": real_car,
                                    "killer": exclusive_killer,
                                    "kill_house_check_key": check.key,
                                    "bar_info": assignment_info,
                                    "auction": "False",
                                    "kill_house_create_date": kill_house_req_obj.create_date,
                                    "accepted_real_quantity": kill_house_req_obj.accepted_real_quantity,
                                    "accepted_real_weight": kill_house_req_obj.accepted_real_weight,
                                    "vet_check_date": vet_check_date,
                                    "first_weight": kill_house_req_obj.quantity * kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.Index_weight,

                                    "age": (
                                                   datetime.now() - kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.hatching.date).days + 1,

                                }

                            elif kill_house_req_obj.kill_house_request_auction_winner != None:

                                internal_dict_infos = {
                                    "poultry_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.fullname,
                                    "poultry_mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.mobile,
                                    "barcod": kill_house_req_obj.bar_code,
                                    "kill_house_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.name,
                                    "kill_house_mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                                    "quantity": kill_house_req_obj.quantity,
                                    "time": kill_house_req_obj.kill_request.recive_time,
                                    "date": kill_house_req_obj.kill_request.recive_date,
                                    "cars": kill_house_req_obj.car,
                                    "kill_house_request_key": kill_house_req_obj.key
                                }

                            info_list.append(internal_dict_infos)
                        # info_dict.append(info_list)
                        return Response(info_list, status=status.HTTP_200_OK)

                else:
                    # kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
                    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                    kill_request_car = KillHouseRequest.objects.filter(
                        (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                            killer__in=kill_house)), kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        active_state__in=('active', 'inactive'),
                        assignment_state_archive='pending',
                        trash=False).select_related('province_request__city_request_Poultry__poultry_request',
                                                    'real_add_car__driver', 'killer',
                                                    'kill_request__kill_house__kill_house_operator')

                    # kill_request_car = [
                    #     kill_request for kill_request in kill_requests
                    #     if date1 <= kill_request.kill_request.recive_date.date() <= date2
                    # ]
                    for kill_house_req_obj in kill_request_car:
                        vet_check_date = None
                        real_car = None
                        if kill_house_req_obj.real_add_car != None:
                            real_car = {
                                "real_driver_name": kill_house_req_obj.real_add_car.driver.driver_name,
                                "real_driver_mobile": kill_house_req_obj.real_add_car.driver.driver_mobile,
                                "real_pelak": kill_house_req_obj.real_add_car.driver.pelak,
                                "real_type_car": kill_house_req_obj.real_add_car.driver.type_car
                            }
                        exclusive_killer = None
                        if kill_house_req_obj.killer != None:
                            exclusive_killer = {
                                "killer_name": kill_house_req_obj.killer.name,
                                "killer_mobile": kill_house_req_obj.killer.kill_house_operator.user.mobile,
                                "killer_fullname": kill_house_req_obj.killer.kill_house_operator.user.fullname,
                            }
                        vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_req_obj).first()
                        if vet_check:
                            vet_check_date = vet_check.create_date
                        if kill_house_req_obj.province_kill_request != None:
                            check = KillHouseCheckRequest.objects.get(
                                province_kill_request=kill_house_req_obj.province_kill_request)
                            bar_info = KillHouseAssignmentInformation.objects.filter(
                                kill_house_request=kill_house_req_obj)
                            if bar_info.count() > 0:
                                bar_info = bar_info.last()
                                assignment_info = {
                                    "kill_house_assignment_key": bar_info.key,
                                    "kill_house_weight_without_load": bar_info.car_weight_without_load,
                                    "kill_house_weight_with_load": bar_info.car_weight_with_load,
                                    "kill_house_image_without_load": bar_info.car_weight_without_load_image,
                                    "kill_house_image_with_load": bar_info.car_weight_with_load_image,
                                    "kill_house_net_weight": bar_info.net_weight,
                                    "driver_name": bar_info.kill_house_request.add_car.driver.driver_name,
                                    "pelak": bar_info.kill_house_request.add_car.driver.pelak,
                                    "type_car": bar_info.kill_house_request.add_car.driver.type_car,
                                    "kill_house_assignment_state": bar_info.state,
                                    "real_quantity": bar_info.real_quantity,

                                }
                            else:
                                assignment_info = None

                            internal_dict_infos = {
                                "poultry_request_id": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.id,
                                "poultry_request_key": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.key,
                                "amount": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.amount,
                                "bar_amount": kill_house_req_obj.amount,
                                "poultry_name": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.fullname,
                                "poultry_mobile": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.mobile,
                                "send_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.send_date,
                                "freezing": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.freezing,
                                "create_date": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.create_date,
                                "poultry_request_quantity": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.quantity,
                                "poultry_city": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.city.name,
                                "poultry_province": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.poultry.user.province.name,
                                "barcod": kill_house_req_obj.bar_code,
                                "order_code": kill_house_req_obj.province_request.city_request_Poultry.poultry_request.order_code,
                                "kill_house_name": kill_house_req_obj.kill_request.kill_house.name,
                                "kill_house_mobile": kill_house_req_obj.kill_request.kill_house.kill_house_operator.user.mobile,
                                "quantity": kill_house_req_obj.quantity,
                                "time": kill_house_req_obj.kill_request.recive_time,
                                "date": kill_house_req_obj.kill_request.recive_date,
                                "kill_house_request_key": kill_house_req_obj.key,
                                "vet_state": kill_house_req_obj.vet_state,
                                "traffic_code": kill_house_req_obj.traffic_code,
                                "driver_name": kill_house_req_obj.add_car.driver.driver_name,
                                "driver_mobile": kill_house_req_obj.add_car.driver.driver_mobile,
                                "pelak": kill_house_req_obj.add_car.driver.pelak,
                                "car_key": kill_house_req_obj.add_car.key,
                                "type_car": kill_house_req_obj.add_car.driver.type_car,
                                "real_car": real_car,
                                "killer": exclusive_killer,
                                "kill_house_check_key": check.key,
                                "free_sale_in_province": kill_house_req_obj.province_request.poultry_request.free_sale_in_province,
                                "bar_info": assignment_info,
                                "age": (
                                               datetime.now() - kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.hatching.date).days + 1,

                                "auction": "False",
                                "kill_house_create_date": kill_house_req_obj.create_date,
                                "accepted_real_quantity": kill_house_req_obj.accepted_real_quantity,
                                "accepted_real_weight": kill_house_req_obj.accepted_real_weight,
                                "vet_check_date": vet_check_date,
                                "first_weight": kill_house_req_obj.quantity * kill_house_req_obj.province_kill_request.province_request.city_request_Poultry.poultry_request.Index_weight,

                            }

                        elif kill_house_req_obj.kill_house_request_auction_winner != None:

                            internal_dict_infos = {
                                "poultry_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.fullname,
                                "poultry_mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.poultry_request.poultry.user.mobile,
                                "barcod": kill_house_req_obj.bar_code,
                                "kill_house_name": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.name,
                                "kill_house_mobile": kill_house_req_obj.kill_house_request_auction_winner.kill_house_request_auction.kill_house.kill_house_operator.user.mobile,
                                "quantity": kill_house_req_obj.quantity,
                                "time": kill_house_req_obj.kill_request.recive_time,
                                "date": kill_house_req_obj.kill_request.recive_date,
                                "cars": kill_house_req_obj.car,
                                "kill_house_request_key": kill_house_req_obj.key
                            }

                        info_list.append(internal_dict_infos)
                    # info_dict.append(info_list)
                    return Response(info_list, status=status.HTTP_200_OK)

    #  تابع مربوط به ویرایش درخواست کشتار های ایجاد شده توسط کشتارگاه بعد از تخصیص
    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        now = datetime.now().date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_request = KillHouseRequest.objects.get(key=request.data['key'], trash=False)

        if 'traffic_code' in request.data.keys():
            if kill_house_request.clearance_code:
                return Response(
                    {"result": "به علت وارد شدن کد قرنطینه، امکان ویرایش وجود ندارد!"},
                    status=status.HTTP_403_FORBIDDEN
                )

            bar_date = kill_house_request.kill_request.recive_date.date()
            if now != bar_date:
                return Response(
                    {"result": "فقط بار همان روز قابل ویرایش است!"},
                    status=status.HTTP_403_FORBIDDEN
                )

        if 'non_receipt' not in request.data.keys():
            if 'bar_document_status_key' in request.data.keys() and request.data['bar_document_status_key'] != None:
                document_status = BarDocumentStatus.objects.get(key=request.data['bar_document_status_key'])
                kill_house_request.bar_document_status = document_status
                kill_house_request.save()
                request.data.pop('bar_document_status_key')

            if 'quarantine_quantity' not in request.data.keys():
                role = request.data['role']
                if role == 'KillHouse' and now > kill_house_request.kill_request.recive_date.date() + timedelta(days=1) \
                        and 'traffic_code' in request.data.keys():
                    return Response(
                        {"result": "تنها یک روز بعد از ثبت اطلاعات امکان تغییر وجود دارد!"},
                        status=status.HTTP_403_FORBIDDEN)
                request.data.pop('role')
                kill_house_request.editor_traffic_code = {
                    "role": role,
                    "full_name": user.first_name,
                    "mobile": user.mobile
                }
                kill_house_request.save()

        # kill_house_request.assignment_state_archive = 'accepted'
        # kill_house_request.save()
        serializer = self.serializer_class(kill_house_request)
        serializer.update(instance=kill_house_request, validated_data=request.data)
        if kill_house_request.bar_document_status is not None and kill_house_request.bar_document_status.sms == True:
            document_discrepancy_sms(kill_house_request.killhouse_user.killer, kill_house_request.killhouse_user.name,
                                     kill_house_request.bar_code, kill_house_request.bar_document_status.title,
                                     kill_house_request.killhouse_user.kill_house_operator.user.mobile,
                                     kill_house_request.kill_request.recive_date.date())
        return Response(serializer.data, status=status.HTTP_200_OK)

    #  تابع مربوط به حذف درخواست کشتار های ایجاد شده توسط کشتارگاه بعد از تخصیص
    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        tomorrow = datetime.now().date() + timedelta(days=1)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if 'delete_bar' in request.GET:

            kill_house_req = KillHouseRequest.objects.get(key=request.GET['kill_house_request_key'], trash=False)

            if KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_req, trash=False).exists():
                return Response({"result": "به علت ورود اطلاعات بار امکان حذف وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)

            # if kill_house_req.vet_state == 'accepted' or kill_house_req.assignment_state_archive == 'True':
            #     return Response({"result": "به علت تایید تخلیه توسط دامپزشک امکان حذف وجود ندارد!"},
            #                     status=status.HTTP_403_FORBIDDEN)
            province_kill_req = ProvinceKillRequest.objects.get(key=kill_house_req.province_kill_request.key,
                                                                trash=False)
            kill_house_req.trash = True
            kill_house_req.save()
            province_kill_req.first_car_allocated_quantity -= kill_house_req.quantity
            if province_kill_req.first_car_allocated_quantity < 0:
                province_kill_req.first_car_allocated_quantity = 0
            province_kill_req.save()
            # kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_req,
            #                                                       trash=False)

            poultry_request = PoultryRequest.objects.get(key=province_kill_req.province_request.poultry_request.key,
                                                         trash=False)
            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
            update_kill_house_requests(province_kill_req, poultry_request)
            update_province_kill_requests(hatching)
            poultry_prediction(hatching.poultry)


        else:
            kill_house_req = KillHouseRequest.objects.get(key=request.GET['kill_house_request_key'], trash=False)
            if KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_req, trash=False).exists():
                return Response({"result": "به علت ورود اطلاعات بار امکان حذف وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
            if kill_house_req.vet_state == 'accepted' or kill_house_req.clearance_code != None:
                return Response({"result": "به علت وارد شدن کد قرنطینه امکان حذف وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
            kill_house_req.trash = True
            kill_house_req.save()

            if kill_house_req.kill_house_request_auction_winner != None:
                kill_house_request_auction_winner = KillHouseRequestActionWinner.objects.get(
                    key=kill_house_req.kill_house_request_auction_winner.key)
                kill_house_request_auction_winner.quantity += kill_house_req.quantity
                kill_house_request_auction_winner.save()
            else:
                province_kill_request = ProvinceKillRequest.objects.get(key=kill_house_req.province_kill_request.key,
                                                                        trash=False)
                province_kill_request.first_car_allocated_quantity -= kill_house_req.quantity
                if province_kill_request.first_car_allocated_quantity < 0:
                    province_kill_request.first_car_allocated_quantity = 0
                province_kill_request.save()
                # kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_request,
                #                                                       trash=False)
                poultry_request = PoultryRequest.objects.get(
                    key=province_kill_request.province_request.poultry_request.key,
                    trash=False)
                hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
                vet_farm = VetFarm.objects.filter(trash=False,
                                                  poultry=kill_house_req.province_request.poultry_request.poultry).first()
                delete_car_allocation_vet_farm_sms(kill_house_req.kill_request.recive_date.date(),
                                                   kill_house_req.province_request.poultry_request.poultry.user.fullname,
                                                   kill_house_req.province_request.poultry_request.hatching.chicken_age,
                                                   kill_house_req.quantity, kill_house_req.add_car.driver.type_car,
                                                   kill_house_req.traffic_code,
                                                   kill_house_req.add_car.driver.pelak,
                                                   kill_house_req.kill_request.kill_house.name,
                                                   vet_farm.vet.user.mobile,
                                                   kill_house_req.province_request.poultry_request.amount,
                                                   kill_house_req.province_request.poultry_request.free_sale_in_province
                                                   )
                update_kill_house_requests(province_kill_request, poultry_request)
                update_province_kill_requests(hatching)
                poultry_prediction(hatching.poultry)

        kill_house_req.trash = True
        if 'message' in request.GET:
            message = request.GET['message']
        else:
            message = 'حذف توسط کشتارگاه'

        kill_house_req.message = message
        role = request.GET['role'] if 'role' in request.GET else 'KillHouse'
        now = datetime.now()
        kill_house_req.bar_remover = {
            "full_name": user.fullname,
            "role": role,
            "mobile": user.mobile,
            "date": str(now)
        }
        kill_house_req.save()

        ware_house = KillHouseWareHouse.objects.filter(kill_house=kill_house_req.killhouse_user,
                                                       date__date=tomorrow).first()
        if ware_house:
            ware_house.final_total_number_of_carcasses -= kill_house_req.accepted_real_quantity
            ware_house.final_total_weight_of_carcasses -= kill_house_req.accepted_real_weight
            ware_house.total_number_of_carcasses -= kill_house_req.accepted_real_quantity
            ware_house.total_weight_of_carcasses -= kill_house_req.accepted_real_weight
            ware_house.remain_total_number_of_carcasses -= kill_house_req.accepted_real_quantity
            ware_house.remain_total_weight_of_carcasses -= kill_house_req.accepted_real_weight
            ware_house.bar_quantity -= 1
            # ware_house.allocated_quantity -= kill_house_req.accepted_real_quantity
            ware_house.bar_live_weight -= kill_house_req.accepted_real_weight
            ware_house.number_of_carcasses -= kill_house_req.accepted_real_quantity
            ware_house.save()
        return Response("object deleted", status=status.HTTP_200_OK)


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

    def update(self, request, pk=None, *args, **kwargs):
        now = datetime.now().date()
        kill_house_request = KillHouseRequest.objects.get(key=request.data['key'], trash=False)
        if 'traffic_code' in request.data.keys() or 'car_key' in request.data.keys():
            if kill_house_request.clearance_code:
                return Response(
                    {"result": "به علت وارد شدن کد قرنطینه، امکان ویرایش وجود ندارد!"},
                    status=status.HTTP_403_FORBIDDEN
                )

            bar_date = kill_house_request.kill_request.recive_date.date()
            if now != bar_date:
                return Response(
                    {"result": "فقط بار همان روز قابل ویرایش است!"},
                    status=status.HTTP_403_FORBIDDEN
                )
        if 'car_key' in request.data.keys():
            add_car = KillHouseADDCAR.objects.get(key=request.data['car_key'], trash=False)
            kill_house_request.add_car = add_car
            kill_house_request.car = {
                "id": add_car.id,
                "key": str(add_car.key),
                "pelak": add_car.driver.pelak,
                "capocity": add_car.driver.capocity,
                "type_car": add_car.driver.type_car,
                "driver_name": add_car.driver.driver_name,
                "driver_mobile": add_car.driver.driver_mobile,
                "weight_without_load": add_car.driver.weight_without_load,
            }
            kill_house_request.save()
            request.data.pop('car_key')

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


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

    def update(self, request, pk=None, *args, **kwargs):
        now = datetime.now()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_request = KillHouseRequest.objects.get(key=request.data['key'], trash=False)
        role = request.data.get('role')
        image = request.FILES.get('file')
        if image:
            file_url = upload_to_liara(image, image.name)
            kill_house_request.image = file_url
        if kill_house_request.price_registerar:
            kill_house_request.price_editor = user.fullname
            kill_house_request.price_editor_role = role
            kill_house_request.price_editor_date = now
        else:
            kill_house_request.price_registerar = user.fullname
            kill_house_request.price_registerar_role = role
            kill_house_request.price_register_date = now
        kill_house_request.save()
        serializer = self.serializer_class(kill_house_request)
        serializer.update(instance=kill_house_request, validated_data=request.data)
        return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)


class KillHouseRequestForCompleteInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForBarManagementSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

    #  تابع مربوط به نمایش درخواست کشتار های ایجاد شده توسط کشتارگاه بعد از تخصیص
    def list(self, request, *args, **kwargs):
        kill_house_request_list = []
        now = datetime.now().date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = datetime.strptime(str(request.GET['date1']),
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(str(request.GET['date2']),
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        if request.GET['role'] == 'KillHouseVet':
            kill_house_vet = KillHouseVet.objects.filter(vet__user=user, trash=False)
            kill_house_list = kill_house_vet.values_list('kill_house', flat=True).distinct()
            kill_house_requests = KillHouseRequest.objects.filter(
                Q(killhouse_user__in=kill_house_list) | Q(
                    kill_request__slaughter_house__in=kill_house_list), kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                assignment_state_archive='pending',
                non_receipt=False,
                trash=False).order_by(
                'create_date')

        else:

            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
            kill_house_requests = KillHouseRequest.objects.filter(
                (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                    killer__in=kill_house)), kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                assignment_state_archive='pending',
                non_receipt=False,
                trash=False)

        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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_request_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_request_list) == 0 else kill_house_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(kill_house_requests)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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


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

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

        now = timezone.now().date()
        ten_days_ago = now - timedelta(days=int(request.GET['day']))

        kill_house_requests_list = []

        for day in range(int(request.GET['day']) + 1):
            date = ten_days_ago + timedelta(days=day)

            total_quantites = KillHouseRequest.objects.filter(
                kill_request__recive_date__date=date,
                trash=False
            ).aggregate(total_quantity=Sum('quantity'))['total_quantity'] or 0

            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)
                    total_quantity = total_quantites.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)
                    total_quantity = total_quantites.filter(
                        province_request__poultry_request__poultry__address__city=user.city)
                else:
                    total_quantity = total_quantites
            else:
                total_quantity = total_quantites

            kill_house_requests_list.append({"date": str(date), "quantity": total_quantity})

        return Response(kill_house_requests_list)


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

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

        now = timezone.now().date()
        ten_days_ago = now - timedelta(days=int(request.GET['day']))

        kill_house_requests_list = []

        for day in range(int(request.GET['day']) + 1):
            date = ten_days_ago + timedelta(days=day)
            total_weight = 0
            kill_house_requestes = KillHouseRequest.objects.filter(
                kill_request__recive_date__date=date,
                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)
                    kill_house_requests = kill_house_requestes.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_requestes.filter(
                        province_request__poultry_request__poultry__address__city=user.city)
                else:
                    kill_house_requests = kill_house_requestes
            else:
                kill_house_requests = kill_house_requestes
            if kill_house_requests:
                for kill_house_request in kill_house_requests:
                    kill_house_request_information = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request=kill_house_request).last()
                    if kill_house_request_information:
                        total_weight += kill_house_request_information.net_weight
                    else:
                        total_weight += kill_house_request.province_request.poultry_request.Index_weight * kill_house_request.quantity

            kill_house_requests_list.append({"date": str(date), "weight": total_weight})

        return Response(kill_house_requests_list)


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

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

        keys = request.data['keys']
        request.data.pop('keys')
        for key in keys:
            kill_house_request = KillHouseRequest.objects.get(key=key, trash=False)
            kill_house_request.show_kill_house = 'accepted'
            kill_house_request.save()
        return Response("objects updated", status=status.HTTP_200_OK)


class KillHouseAssignmentImagesViewSet(viewsets.ModelViewSet):
    queryset = KillHouseAssignmentImages.objects.all()
    serializer_class = KillHouseAssignmentImagesSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به وارد کردن اطلاعات بار توسط کشتارگاه

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        role = request.data['role']
        request.data.pop('role')
        kill_house = KillHouse.objects.get(key=request.data['kill_house_key'], trash=False)
        request.data.pop('kill_house_key')

        try:
            health_certificate_image = request.data['health_certificate_img']
            request.data.pop('health_certificate_img')

        except:
            health_certificate_image = None
        try:
            national_card_image = request.data['national_card_image']
        except:
            national_card_image = None
        try:
            birth_certificate_image = request.data['birth_certificate_image']
        except:
            birth_certificate_image = None
        try:
            police_clearance_image = request.data['police_clearance_image']
        except:
            police_clearance_image = None
        try:
            no_addiction_image = request.data['no_addiction_image']
        except:
            no_addiction_image = None

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_images = KillHouseAssignmentImages.objects.filter(kill_house=kill_house)
            if kill_house_images.count() > 0:
                kill_house_images = kill_house_images.last()
            else:
                kill_house_images = serializer.create(validated_data=request.data)
            if health_certificate_image != None:
                kill_house_images.health_certificate_image = send_image_to_server(health_certificate_image)
            if national_card_image != None:
                kill_house_images.national_card_image = send_image_to_server(national_card_image)
            if birth_certificate_image != None:
                kill_house_images.birth_certificate_image = send_image_to_server(birth_certificate_image)
            if police_clearance_image != None:
                kill_house_images.police_clearance_image = send_image_to_server(police_clearance_image)
            if no_addiction_image != None:
                kill_house_images.no_addiction_image = send_image_to_server(no_addiction_image)
            kill_house_images.save()

            kill_house_images_serializer = self.serializer_class(kill_house_images)
            return Response(kill_house_images_serializer.data, status=status.HTTP_201_CREATED)

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


class KillHouseAssignmentInformationForAggregateLoadViewSet(viewsets.ModelViewSet):
    queryset = KillHouseAssignmentInformation.objects.all()
    serializer_class = KillHouseAssignmentInformationSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        now = datetime.now().date()
        user = SystemUserProfile.objects.get(user=request.user)
        kill_house_request = KillHouseRequest.objects.get(key=request.data['kill_house_request_key'], trash=False)
        province_kill_request = ProvinceKillRequest.objects.get(key=kill_house_request.province_kill_request.key)
        poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
        kill_house_check = KillHouseCheckRequest.objects.get(
            province_kill_request__key=kill_house_request.province_kill_request.key)
        if OperationLimitation.objects.all().first().vet_check_kill_house_assignment_limitation == True:
            if kill_house_request.vet_state == 'pending':
                return Response({"result": "به علت عدم تایید تخلیه دامپزشک کشتارگاه امکان ثبت اطلاعات وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        date_time_of_now = datetime.now().date()
        if OperationLimitation.objects.all().first().kill_house_assignment_limitation == True:

            if date_time_of_now > kill_house_request.kill_request.recive_date.date() + timedelta(days=1):
                return Response({"result": "به علت مغایرت در تاریخ ثبت و تاریخ کشتار امکان ثبت اطلاعات وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        role = request.data['role']
        request.data.pop('kill_house_request_key')
        request.data.pop('role')
        assignment_info = KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_request).first()
        if not assignment_info:
            assignment_info = KillHouseAssignmentInformation()
            assignment_info.save()

            # serializer = self.serializer_class(data=request.data)
            # if serializer.is_valid():
            #     assignment_info = serializer.create(validated_data=request.data)
        assignment_info.kill_house_check = kill_house_check
        assignment_info.kill_house_request = kill_house_request
        assignment_info.car_weight_with_load = int(request.data['net_weight'])
        assignment_info.net_weight = int(request.data['net_weight'])
        assignment_info.real_quantity = int(request.data['real_quantity'])
        assignment_info.importer = {
            "fullname": user.fullname,
            "mobile": user.mobile,
            "date": str(now),
            "role": role
        }
        assignment_info.save()
        kill_house_request.accepted_real_weight = int(request.data['net_weight'])
        kill_house_request.accepted_real_quantity = int(request.data['real_quantity'])
        kill_house_request.accepted_assignment_real_quantity = int(request.data['net_weight'])
        kill_house_request.accepted_assignment_real_weight = int(request.data['real_quantity'])
        kill_house_request.save()
        # kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_request,
        #                                                       trash=False)

        update_kill_house_requests(province_kill_request, poultry_request)
        update_province_kill_requests(hatching)
        poultry_prediction(hatching.poultry)

        kill_house_request.accepted_real_weight = int(request.data['net_weight'])
        kill_house_request.accepted_real_quantity = int(request.data['real_quantity'])
        assignment_info.save()
        if assignment_info.net_weight != 0 and assignment_info.real_quantity != 0 and assignment_info.car_weight_with_load_image != None:
            kill_house_request.assignment_state_archive = 'True'
        kill_house_request.save()

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

    def update(self, request, pk=None, *args, **kwargs):
        image = request.data['image']
        role = request.data['role']
        now = datetime.now()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))
        image_url = send_image_to_server(image)
        # upload_object_resize(image_data=image, bucket_name="profileimagedefault",
        #                      object_name="{0}.jpg".format(str(ran)))
        if 'bar_key' in request.data.keys():
            bar_key = request.data['bar_key']
            request.data.pop('bar_key')
            kill_house_request = KillHouseRequest.objects.get(key=bar_key, trash=False)
            kill_house_check = KillHouseCheckRequest.objects.get(
                province_kill_request__key=kill_house_request.province_kill_request.key)
            assignment_info = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=bar_key).first()
            if OperationLimitation.objects.all().first().vet_check_kill_house_assignment_limitation == True:
                if kill_house_request.vet_state == 'pending':
                    return Response({"result": "به علت عدم تایید تخلیه دامپزشک کشتارگاه امکان ثبت اطلاعات وجود ندارد!"},
                                    status=status.HTTP_403_FORBIDDEN)
            date_time_of_now = datetime.now().date()
            if OperationLimitation.objects.all().first().kill_house_assignment_limitation == True:

                if date_time_of_now > kill_house_request.kill_request.recive_date.date() + timedelta(days=1):
                    return Response(
                        {"result": "به علت مغایرت در تاریخ ثبت و تاریخ کشتار امکان ثبت اطلاعات وجود ندارد!"},
                        status=status.HTTP_403_FORBIDDEN)

            if not assignment_info:
                assignment_info = KillHouseAssignmentInformation(kill_house_check=kill_house_check,
                                                                 kill_house_request=kill_house_request)
                assignment_info.save()
                # serializer = self.serializer_class(data=request.data)
                # if serializer.is_valid():
                #     assignment_info = serializer.create(validated_data=request.data)
            # assignment_info.car_weight_with_load_image = ARVAN_Kill_house_URL + "{0}.jpg".format(str(ran))
            assignment_info.car_weight_with_load_image = image_url
            assignment_info.importer = {
                "fullname": user.fullname,
                "mobile": user.mobile,
                "date": str(now),
                "role": role
            }
            assignment_info.save()
            kill_house_request = KillHouseRequest.objects.get(key=bar_key, trash=False)
            if assignment_info.net_weight != 0 and assignment_info.real_quantity != 0 and assignment_info.car_weight_with_load_image != None:
                kill_house_request.assignment_state_archive = 'True'
                kill_house_request.save()

        else:
            assingment_info_keys = request.data['bar_keys']
            request.data.pop('bar_keys')
            for assingment_info_key in assingment_info_keys:
                kill_house_request = KillHouseRequest.objects.get(key=assingment_info_key, trash=False)
                kill_house_check = KillHouseCheckRequest.objects.get(
                    province_kill_request__key=kill_house_request.province_kill_request.key)
                if OperationLimitation.objects.all().first().vet_check_kill_house_assignment_limitation == True:
                    if kill_house_request.vet_state == 'pending':
                        return Response(
                            {"result": "به علت عدم تایید تخلیه دامپزشک کشتارگاه امکان ثبت اطلاعات وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)
                date_time_of_now = datetime.now().date()
                if OperationLimitation.objects.all().first().kill_house_assignment_limitation == True:

                    if date_time_of_now > kill_house_request.kill_request.recive_date.date() + timedelta(days=1):
                        return Response(
                            {"result": "به علت مغایرت در تاریخ ثبت و تاریخ کشتار امکان ثبت اطلاعات وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

                assignment_info = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request__key=assingment_info_key).first()

                if not assignment_info:
                    assignment_info = KillHouseAssignmentInformation(kill_house_check=kill_house_check,
                                                                     kill_house_request=kill_house_request)
                    assignment_info.save()

                if assignment_info.car_weight_with_load_image == None:
                    # assignment_info.car_weight_with_load_image = ARVAN_Kill_house_URL + "{0}.jpg".format(str(ran))
                    assignment_info.car_weight_with_load_image = image_url
                    assignment_info.importer = {
                        "fullname": user.fullname,
                        "mobile": user.mobile,
                        "date": str(now),
                        "role": role
                    }
                    assignment_info.save()
                kill_house_request = KillHouseRequest.objects.get(key=assignment_info.kill_house_request.key,
                                                                  trash=False)
                if assignment_info.net_weight != 0 and assignment_info.real_quantity != 0 and assignment_info.car_weight_with_load_image != None:
                    kill_house_request.assignment_state_archive = 'True'
                    kill_house_request.save()

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


# class KillHouseAssignmentInformationForcompletedloadsViewSet(viewsets.ModelViewSet):
#     queryset = KillHouseAssignmentInformation.objects.all()
#     serializer_class = KillHouseAssignmentInformationSerializer
#     permission_classes = [TokenHasReadWriteScope]
#
#     def list(self, request, *args, **kwargs):
#         # refresh(request.user.id)
#         user = SystemUserProfile.objects.get(user=request.user, trash=False)
#         now = datetime.now().date()
#         date1 = datetime.strptime(str(request.GET['date1']),
#                                   '%Y-%m-%d').date() if 'date1' in request.GET else now
#         date2 = datetime.strptime(str(request.GET['date2']),
#                                   '%Y-%m-%d').date() if 'date2' in request.GET else now
#         province = user.province.name
#         if request.GET['role'] in ('ProvinceFinancial', 'ProvinceOperator'):
#             kill_house_assignments = KillHouseAssignmentInformation.objects.filter(
#                 Q(car_weight_with_load_image__isnull=False) | Q(car_weight_without_load_image__isnull=False),
#                 kill_house_request__killhouse_user__kill_house_operator__address__province__name=province,
#                 net_weight__gt=0,
#                 real_quantity__gt=0,
#                 kill_house_request__kill_request__recive_date__date__gte=date1,
#                 kill_house_request__kill_request__recive_date__date__lte=date2,
#                 trash=False).select_related(
#                 'kill_house_request__province_request__poultry_request__hatching',
#                 'kill_house_request__province_request__poultry_request__poultry',
#                 'kill_house_request__province_request__poultry_request__poultry__user__city',
#                 'kill_house_request__province_request__poultry_request__poultry__user__province',
#                 'kill_house_request__province_request__poultry_request__poultry__user',
#
#                 'kill_house_request__kill_request__kill_house',
#                 'kill_house_request__kill_request__slaughter_house',
#                 'kill_house_request__killhouse_user',
#                 'kill_house_request__killhouse_user__kill_house_operator__user',
#                 'kill_house_request__add_car__driver',
#                 'kill_house_request__real_add_car__driver',
#             ).values(
#                 "kill_house_request__province_request__poultry_request__poultry__user__province__name",
#                 "kill_house_request__province_request__poultry_request__poultry__user__city__name",
#                 "kill_house_request__province_request__poultry_request__poultry__user__fullname",
#                 "kill_house_request__province_request__poultry_request__poultry__user__mobile",
#                 "kill_house_request__province_request__poultry_request__poultry__unit_name",
#                 "kill_house_request__province_request__poultry_request__poultry__key",
#                 "kill_house_request__province_request__poultry_request__order_code",
#                 "kill_house_request__province_request__poultry_request__quantity",
#                 "kill_house_request__province_request__poultry_request__id",
#                 "kill_house_request__province_request__poultry_request__Index_weight",
#                 "kill_house_request__province_request__poultry_request__chicken_breed",
#                 "kill_house_request__province_request__poultry_request__create_date",
#                 "kill_house_request__province_request__poultry_request__send_date",
#                 "kill_house_request__province_request__poultry_request__cell_type",
#                 "kill_house_request__province_request__poultry_request__hatching__losses",
#                 "kill_house_request__province_request__poultry_request__hatching__date",
#                 "kill_house_request__killhouse_user",
#                 'kill_house_request__kill_request__kill_house__name',
#                 'kill_house_request__kill_request__slaughter_house__name',
#                 "kill_house_request__add_car__driver__driver_name",
#                 "kill_house_request__add_car__driver__driver_mobile",
#                 "kill_house_request__add_car__driver__type_car",
#                 "kill_house_request__add_car__driver__pelak",
#                 "kill_house_request__add_car__driver__health_code",
#                 "kill_house_request__real_add_car__driver__driver_name",
#                 "kill_house_request__real_add_car__driver__driver_mobile",
#                 "kill_house_request__real_add_car__driver__type_car",
#                 "kill_house_request__real_add_car__driver__pelak",
#                 "kill_house_request__real_add_car__driver__health_code",
#                 "kill_house_request__quantity",
#                 "kill_house_request__bar_code",
#                 "kill_house_request__quarantine_quantity",
#                 "kill_house_request__vet_state",
#                 "kill_house_request__assignment_state_archive",
#                 "kill_house_request__clearance_code",
#                 "kill_house_request__traffic_code",
#                 "kill_house_request__accepted_real_quantity",
#                 "kill_house_request__accepted_real_weight",
#                 "kill_house_request",
#                 "car_weight_without_load",
#                 "car_weight_without_load_image",
#                 "car_weight_with_load",
#                 "car_weight_with_load_image",
#                 "net_weight",
#                 "state",
#                 "real_quantity",
#                 "protest_time",
#
#                 # "allocated_car_state"
#             )
#         else:
#             if request.GET['role'] == 'KillHouse':
#                 operator = KillHouseOperator.objects.get(user=user, trash=False)
#                 kill_house = KillHouse.objects.filter(kill_house_operator=operator, trash=False)
#             else:
#                 vet = Vet.objects.get(user=user)
#                 kill_house_vet = KillHouseVet.objects.filter(vet=vet, trash=False)
#                 kill_house_list = [kill_house.kill_house.key for kill_house in kill_house_vet]
#                 kill_house = KillHouse.objects.filter(key__in=kill_house_list)
#
#             kill_house_assignments = KillHouseAssignmentInformation.objects.filter(
#                 # state='pending',
#                 Q(car_weight_with_load_image__isnull=False) | Q(car_weight_without_load_image__isnull=False),
#
#                 kill_house_request__killhouse_user__in=kill_house,
#                 # car_weight_with_load_image__isnull=False,
#                 net_weight__gt=0,
#                 real_quantity__gt=0,
#                 trash=False,
#                 kill_house_request__kill_request__recive_date__date__gte=date1,
#                 kill_house_request__kill_request__recive_date__date__lte=date2,
#                 unusual_casualties=False).select_related(
#                 'kill_house_request__province_request__poultry_request__hatching',
#                 'kill_house_request__province_request__poultry_request__poultry',
#                 'kill_house_request__province_request__poultry_request__poultry__user__city',
#                 'kill_house_request__province_request__poultry_request__poultry__user__province',
#                 'kill_house_request__province_request__poultry_request__poultry__user',
#
#                 'kill_house_request__kill_request__kill_house',
#                 'kill_house_request__kill_request__slaughter_house',
#                 'kill_house_request__killhouse_user',
#                 'kill_house_request__killhouse_user__kill_house_operator__user',
#                 'kill_house_request__add_car__driver',
#                 'kill_house_request__real_add_car__driver',
#             ).values(
#                 "kill_house_request__province_request__poultry_request__poultry__user__province__name",
#                 "kill_house_request__province_request__poultry_request__poultry__user__city__name",
#                 "kill_house_request__province_request__poultry_request__poultry__user__fullname",
#                 "kill_house_request__province_request__poultry_request__poultry__user__mobile",
#                 "kill_house_request__province_request__poultry_request__poultry__unit_name",
#                 "kill_house_request__province_request__poultry_request__poultry__key",
#                 "kill_house_request__province_request__poultry_request__order_code",
#                 "kill_house_request__province_request__poultry_request__quantity",
#                 "kill_house_request__province_request__poultry_request__id",
#                 "kill_house_request__province_request__poultry_request__Index_weight",
#                 "kill_house_request__province_request__poultry_request__chicken_breed",
#                 "kill_house_request__province_request__poultry_request__create_date",
#                 "kill_house_request__province_request__poultry_request__send_date",
#                 "kill_house_request__province_request__poultry_request__cell_type",
#                 "kill_house_request__province_request__poultry_request__hatching__losses",
#                 "kill_house_request__province_request__poultry_request__hatching__date",
#                 "kill_house_request__killhouse_user",
#                 'kill_house_request__kill_request__kill_house__name',
#                 'kill_house_request__kill_request__slaughter_house__name',
#                 "kill_house_request__add_car__driver__driver_name",
#                 "kill_house_request__add_car__driver__driver_mobile",
#                 "kill_house_request__add_car__driver__type_car",
#                 "kill_house_request__add_car__driver__pelak",
#                 "kill_house_request__add_car__driver__health_code",
#                 "kill_house_request__real_add_car__driver__driver_name",
#                 "kill_house_request__real_add_car__driver__driver_mobile",
#                 "kill_house_request__real_add_car__driver__type_car",
#                 "kill_house_request__real_add_car__driver__pelak",
#                 "kill_house_request__real_add_car__driver__health_code",
#                 "kill_house_request__quantity",
#                 "kill_house_request__bar_code",
#                 "kill_house_request__quarantine_quantity",
#                 "kill_house_request__vet_state",
#                 "kill_house_request__assignment_state_archive",
#                 "kill_house_request__clearance_code",
#                 "kill_house_request__traffic_code",
#                 "kill_house_request__accepted_real_quantity",
#                 "kill_house_request__accepted_real_weight",
#                 "kill_house_request",
#                 "car_weight_without_load",
#                 "car_weight_without_load_image",
#                 "car_weight_with_load",
#                 "car_weight_with_load_image",
#                 "net_weight",
#                 "state",
#                 "real_quantity",
#                 "protest_time",
#
#                 # "allocated_car_state"
#             )
#
#         assignments_list_final_state = []
#         allocation = ShareOfAllocation.objects.all()
#         if allocation.count() > 0:
#             allocation = allocation.last().total
#         else:
#             allocation = 0
#         for request_data in kill_house_assignments:
#             poultry_name_of_bank_user = None
#             poultry_bank_name = None
#             poultry_card = None
#             poultry_account = None
#             poultry_shaba = None
#             province_name_of_bank_user = None
#             province_bank_name = None
#             province_card = None
#             province_account = None
#             province_shaba = None
#             kill_house_vet = KillHouseVet.objects.filter(
#                 kill_house=request_data.get('kill_house_request__killhouse_user'), trash=False).select_related('vet__user').values(
#                 'vet__user__fullname',
#                 'vet__user__mobile',
#             )
#             if kill_house_vet.count() > 0:
#                 kill_house_vet = kill_house_vet.last()
#                 kill_house_vet_name = kill_house_vet.get('vet__user__fullname')
#                 kill_house_vet_mobile = kill_house_vet.get('vet__user__mobile')
#             if request_data.get('kill_house_request__kill_request__slaughter_house') != None:
#                 kill_place = request_data.get('kill_house_request__kill_request__slaughter_house__name')
#             else:
#                 kill_place = request_data.get('kill_house_request__kill_request__kill_house__name')
#
#             vet_check = VetCheckRequest.objects.filter(
#                 kill_house_request=request_data.get('kill_house_request'), trash=False).select_related('kill_house_request').values('kill_house_request','create_date').first()
#
#             vet_check_date = vet_check.get('create_date') if vet_check else None
#             poultry = Poultry.objects.filter(
#                 key=request_data.get('kill_house_request__province_request__poultry_request__poultry__key'),
#                 trash=False).select_related('user_bank_info').values(
#                 'user_bank_info',
#                 'user_bank_info__name_of_bank_user',
#                 'user_bank_info__bank_name',
#                 'user_bank_info__card',
#                 'user_bank_info__account',
#                 'user_bank_info__shaba',
#             ).first()
#             if poultry.get('user_bank_info') != None:
#                 poultry_name_of_bank_user = poultry.get('user_bank_info__name_of_bank_user')
#                 poultry_bank_name = poultry.get('user_bank_info__bank_name')
#                 poultry_card = poultry.get('user_bank_info__card')
#                 poultry_account = poultry.get('user_bank_info__account')
#                 poultry_shaba = poultry.get('user_bank_info__shaba')
#             operator = ProvinceOperator.objects.filter(trash=False).select_related('user_bank_info').values(
#                 'user_bank_info',
#                 'user_bank_info__name_of_bank_user',
#                 'user_bank_info__bank_name',
#                 'user_bank_info__card',
#                 'user_bank_info__account',
#                 'user_bank_info__shaba',
#             )
#             if operator.last().get('user_bank_info') != None:
#                 operator = operator.last()
#                 province_name_of_bank_user = operator.get('user_bank_info__name_of_bank_user')
#                 province_bank_name = operator.get('user_bank_info__bank_name')
#                 province_card = operator.get('user_bank_info__card')
#                 province_account = operator.get('user_bank_info__account')
#                 province_shaba = operator.get('user_bank_info__shaba')
#
#             internal_dict = {
#                 "order_code": request_data.get('kill_house_request__province_request__poultry_request__order_code'),
#                 "poultry_province": request_data.get(
#                     'kill_house_request__province_request__poultry_request__poultry__user__province__name'),
#                 "poultry_city": request_data.get(
#                     'kill_house_request__province_request__poultry_request__poultry__user__city__name'),
#                 "poultry_fullname": request_data.get(
#                     'kill_house_request__province_request__poultry_request__poultry__user__fullname'),
#                 "poultry_mobile": request_data.get(
#                     'kill_house_request__province_request__poultry_request__poultry__user__mobile'),
#                 "poultry_name": request_data.get(
#                     'kill_house_request__province_request__poultry_request__poultry__unit_name'),
#                 "poultry_key": request_data.get('kill_house_request__province_request__poultry_request__poultry__key'),
#                 "poultry_request_quantity": request_data.get(
#                     'kill_house_request__province_request__poultry_request__quantity'),
#                 "poultry_request_id": request_data.get('kill_house_request__province_request__poultry_request__id'),
#                 "Index_weight": request_data.get('kill_house_request__province_request__poultry_request__Index_weight'),
#                 "chicken_breed": request_data.get(
#                     'kill_house_request__province_request__poultry_request__chicken_breed'),
#                 "create_date": request_data.get('kill_house_request__province_request__poultry_request__create_date'),
#                 "send_date": request_data.get('kill_house_request__province_request__poultry_request__send_date'),
#                 "cell_type": request_data.get('kill_house_request__province_request__poultry_request__cell_type'),
#                 "losses": request_data.get('kill_house_request__province_request__poultry_request__hatching__losses'),
#                 "hatching__date": request_data.get(
#                     'kill_house_request__province_request__poultry_request__hatching__date'),
#                 "driver_name": request_data.get('kill_house_request__add_car__driver__driver_name'),
#                 "driver_mobile": request_data.get('kill_house_request__add_car__driver__driver_mobile'),
#                 "type_car": request_data.get('kill_house_request__add_car__driver__type_car'),
#                 "pelak": request_data.get('kill_house_request__add_car__driver__pelak'),
#                 "health_code": request_data.get('kill_house_request__add_car__driver__health_code'),
#                 "real_driver_name": request_data.get('kill_house_request__real_add_car__driver__driver_name'),
#                 "real_driver_mobile": request_data.get('kill_house_request__real_add_car__driver__driver_mobile'),
#                 "real_type_car": request_data.get('kill_house_request__real_add_car__driver__type_car'),
#                 "real_pelak": request_data.get('kill_house_request__real_add_car__driver__pelak'),
#                 "real_health_code": request_data.get('kill_house_request__real_add_car__driver__health_code'),
#                 "quantity": request_data.get('kill_house_request__quantity'),
#                 "bar_code": request_data.get('kill_house_request__bar_code'),
#                 "quarantine_quantity": request_data.get('kill_house_request__quarantine_quantity'),
#                 "vet_state": request_data.get('kill_house_request__vet_state'),
#                 "assignment_state_archive": request_data.get('kill_house_request__assignment_state_archive'),
#                 "clearance_code": request_data.get('kill_house_request__clearance_code'),
#                 "traffic_code": request_data.get('kill_house_request__traffic_code'),
#                 "accepted_real_quantity": request_data.get('kill_house_request__accepted_real_quantity'),
#                 "accepted_real_weight": request_data.get('kill_house_request__accepted_real_weight'),
#                 "car_weight_without_load": request_data.get('car_weight_without_load'),
#                 "car_weight_without_load_image": request_data.get('car_weight_without_load_image'),
#                 "car_weight_with_load": request_data.get('car_weight_with_load'),
#                 "car_weight_with_load_image": request_data.get('car_weight_with_load_image'),
#                 "net_weight": request_data.get('net_weight'),
#                 "state": request_data.get('state'),
#                 "real_quantity": request_data.get('real_quantity'),
#                 "protest_time": request_data.get('protest_time'),
#                 "average_weight": request_data.get('net_weight') / request_data.get('real_quantity') ,
#                 "first_weight": request_data.get('kill_house_request__quantity') * request_data.get('kill_house_request__province_request__poultry_request__Index_weight') ,
#                 "poultry_name_of_bank_user": poultry_name_of_bank_user,
#                 "poultry_bank_name": poultry_bank_name,
#                 "poultry_card": poultry_card,
#                 "poultry_account": poultry_account,
#                 "poultry_shaba": poultry_shaba,
#                 "province_name_of_bank_user": province_name_of_bank_user,
#                 "province_bank_name": province_bank_name,
#                 "province_card": province_card,
#                 "province_account": province_account,
#                 "province_shaba": province_shaba,
#                 "kill_house_vet_name": kill_house_vet_name,
#                 "kill_house_vet_mobile": kill_house_vet_mobile,
#                 "kill_place": kill_place,
#                 "vet_check_date": vet_check_date,
#                 "allocation": allocation,
#
#             }
#
#             assignments_list_final_state.append(internal_dict)
#         return Response(len(assignments_list_final_state), status=status.HTTP_200_OK)
class KillHouseAssignmentInformationForcompletedloadsViewSet(viewsets.ModelViewSet):
    queryset = KillHouseAssignmentInformation.objects.all()
    serializer_class = KillHouseAssignmentInformationForCompletedLoadsSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        now = datetime.now().date()
        date1 = datetime.strptime(str(request.GET['date1']),
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(str(request.GET['date2']),
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        province = user.province.name
        if request.GET['role'] in ('ProvinceFinancial', 'ProvinceOperator'):
            kill_house_assignments = KillHouseAssignmentInformation.objects.filter(
                Q(car_weight_with_load_image__isnull=False) | Q(car_weight_without_load_image__isnull=False),
                kill_house_request__killhouse_user__kill_house_operator__address__province__name=province,
                net_weight__gt=0,
                real_quantity__gt=0,
                kill_house_request__kill_request__recive_date__date__gte=date1,
                kill_house_request__kill_request__recive_date__date__lte=date2,
                trash=False)
        else:
            if request.GET['role'] == 'KillHouse':
                operator = KillHouseOperator.objects.get(user=user, trash=False)
                kill_house = KillHouse.objects.filter(kill_house_operator=operator, trash=False)
            else:
                vet = Vet.objects.get(user=user)
                kill_house_vet = KillHouseVet.objects.filter(vet=vet, trash=False)
                kill_house_list = [kill_house.kill_house.key for kill_house in kill_house_vet]
                kill_house = KillHouse.objects.filter(key__in=kill_house_list)

            kill_house_assignments = KillHouseAssignmentInformation.objects.filter(
                # state='pending',
                Q(car_weight_with_load_image__isnull=False) | Q(car_weight_without_load_image__isnull=False),

                kill_house_request__killhouse_user__in=kill_house,
                # car_weight_with_load_image__isnull=False,
                net_weight__gt=0,
                real_quantity__gt=0,
                trash=False,
                kill_house_request__kill_request__recive_date__date__gte=date1,
                kill_house_request__kill_request__recive_date__date__lte=date2,
                unusual_casualties=False)
        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_assignments)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(kill_house_assignments, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به وارد کردن اطلاعات بار توسط کشتارگاه
class KillHouseAssignmentInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseAssignmentInformation.objects.all()
    serializer_class = KillHouseAssignmentInformationSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'bar_code',
        'bar_document_status__title',
    ]

    # تابع مربوط به وارد کردن اطلاعات بار توسط کشتارگاه

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        pic = []
        dict1 = {}
        role = request.data['role']
        request.data.pop('role')
        date_time_of_now = datetime.now().date()
        kill_house_request = KillHouseRequest.objects.get(key=request.data['kill_house_request_key'], trash=False)
        province_kill_request = ProvinceKillRequest.objects.get(key=kill_house_request.province_kill_request.key)
        if OperationLimitation.objects.all().first().vet_check_kill_house_assignment_limitation == True:
            if kill_house_request.vet_state == 'pending':
                return Response({"result": "به علت عدم تایید تخلیه دامپزشک کشتارگاه امکان ثبت اطلاعات وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        if OperationLimitation.objects.all().first().kill_house_assignment_limitation == True:
            if date_time_of_now > kill_house_request.kill_request.recive_date.date() + timedelta(days=1):
                return Response({"result": "به علت مغایرت در تاریخ ثبت و تاریخ کشتار امکان ثبت اطلاعات وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)

        # if kill_house_request.vet_state == 'pending':
        #     return Response({"result": "بار توسط دامپزشک تخلیه نشده است !"}, status=status.HTTP_403_FORBIDDEN)
        if kill_house_request.province_kill_request != None:
            kill_house_check = KillHouseCheckRequest.objects.get(
                province_kill_request__key=kill_house_request.province_kill_request.key)
        else:
            kill_house_check = None
        # if 'car_without_load_image' in request.data.keys() and 'car_with_load_image' in request.data.keys():
        #     if request.data['car_without_load_image'] != None and request.data['car_with_load_image'] != None:
        #         car_without_load_image = request.data['car_without_load_image']
        #         car_with_load_image = request.data['car_with_load_image']
        #         pic.append(car_without_load_image)
        #         pic.append(car_with_load_image)
        #     request.data.pop('car_without_load_image')
        #     request.data.pop('car_with_load_image')

        if 'car_with_load_image' in request.data.keys():
            if request.data['car_with_load_image'] != None:
                car_with_load_image = request.data['car_with_load_image']
                pic.append(car_with_load_image)
            request.data.pop('car_with_load_image')

        request.data.pop('kill_house_request_key')

        if KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_request).exists():
            return Response({'result': 'already exist'}, status=status.HTTP_403_FORBIDDEN)
        if 'killer_key' in request.data.keys():
            if request.data['killer_key'] != None:
                killer = KillHouse.objects.get(key=request.data['killer_key'])
                kill_house_request.killer = killer
            request.data.pop('killer_key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            assignment_info = serializer.create(validated_data=request.data)
            if kill_house_check != None:
                assignment_info.kill_house_check = kill_house_check
            assignment_info.kill_house_request = kill_house_request
            if len(pic) > 0:
                for p in pic:
                    ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))
                    # upload_object_resize(image_data=p, bucket_name="profileimagedefault",
                    #                      object_name="{0}.jpg".format(str(ran)))
                    # if p == car_without_load_image:
                    #     assignment_info.car_weight_without_load_image = ARVAN_Kill_house_URL + "{0}.jpg".format(
                    #         str(ran))
                    #     # os.remove("{0}.jpg".format(str(ran)))
                    # else:
                    # assignment_info.car_weight_with_load_image = ARVAN_Kill_house_URL + "{0}.jpg".format(str(ran))
                    assignment_info.car_weight_with_load_image = send_image_to_server(p)
                    # os.remove("{0}.jpg".format(str(ran)))
            kill_house_request.assignment_state_archive = 'True'
            kill_house_request.save()
            if role == 'Poultry':
                dict1.update({
                    "Poultry": True,
                    "CityOperator": False,
                    "ProvinceOperator": False,
                    "ProvinceFinancial": False,
                    "KillHouse": False,
                })
            elif role == 'CityOperator':
                dict1.update({
                    "Poultry": False,
                    "CityOperator": True,
                    "ProvinceOperator": False,
                    "ProvinceFinancial": False,
                    "KillHouse": False,
                })
            elif role == 'ProvinceFinancial':
                dict1.update({
                    "Poultry": False,
                    "CityOperator": False,
                    "ProvinceOperator": False,
                    "ProvinceFinancial": True,
                    "KillHouse": False,
                })
            elif role == 'ProvinceOperator':
                dict1.update({
                    "Poultry": False,
                    "CityOperator": False,
                    "ProvinceOperator": True,
                    "ProvinceFinancial": False,
                    "KillHouse": False,
                })
            else:
                dict1.update({
                    "Poultry": False,
                    "CityOperator": False,
                    "ProvinceOperator": False,
                    "ProvinceFinancial": False,
                    "KillHouse": True,
                })
            assignment_info.importer = dict1
            now = datetime.now()
            houre = PercentageOfLosses.objects.all()
            if houre.count() > 0:
                houre = houre.last().houre
            assignment_info.protest_time = now + timedelta(hours=int(houre))
            assignment_info.net_weight = float(assignment_info.car_weight_with_load) - float(
                assignment_info.car_weight_without_load)
            assignment_info.save()
            kill_house_request.active_state = 'inactive'
            poultry = PoultryRequest.objects.get(
                key=kill_house_request.province_request.city_request_Poultry.poultry_request.key)
            poultry.assignment = True
            poultry.save()
            kill_house_request.accepted_real_quantity = assignment_info.real_quantity
            kill_house_request.accepted_real_weight = assignment_info.net_weight
            kill_house_request.accepted_assignment_real_quantity = assignment_info.real_quantity
            kill_house_request.accepted_assignment_real_weight = assignment_info.net_weight
            kill_house_request.save()
            hatching = PoultryHatching.objects.get(key=poultry.hatching.key)
            update_kill_house_requests(province_kill_request, poultry)
            update_province_kill_requests(hatching)
            poultry_prediction(hatching.poultry)
            kill_house_request.accepted_real_quantity = assignment_info.real_quantity
            kill_house_request.accepted_real_weight = assignment_info.net_weight
            kill_house_request.save()
            assignment_info_serializer = self.serializer_class(assignment_info)
            return Response(assignment_info_serializer.data, status=status.HTTP_201_CREATED)

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

    # تابع مربوط به نمایش اطلاعات بار وارد شده توسط کشتارگاه
    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        # user = SystemUserProfile.objects.get(user=request.user)
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        kill_house = []
        kill_house_requests_list = []

        if request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)

        elif request.GET['role'] == 'KillHouseVet':
            kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
            for kill_house_vet in kill_house_vets:
                kill_house.append(kill_house_vet.kill_house)

        else:
            kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False)

        if request.GET['role'] in ['CityOperator', 'CityJahad', 'CityPoultry']:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                if 'without_bar_document' in request.GET and request.GET['without_bar_document'] == "true":
                    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,
                        assignment_state_archive='True',
                        bar_document_status__isnull=True,
                        non_receipt=False,
                        trash=False, province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

                    ).order_by('-kill_request__recive_date')
                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,
                        assignment_state_archive='True',
                        non_receipt=False,
                        trash=False, province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

                    ).order_by('-kill_request__recive_date')
            else:
                if 'without_bar_document' in request.GET and request.GET['without_bar_document'] == "true":
                    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,
                        assignment_state_archive='True',
                        bar_document_status__isnull=True,
                        non_receipt=False,
                        trash=False, province_request__poultry_request__poultry__address__city=user.city

                    ).order_by('-kill_request__recive_date')
                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,
                        assignment_state_archive='True',
                        non_receipt=False,
                        trash=False, province_request__poultry_request__poultry__address__city=user.city

                    ).order_by('-kill_request__recive_date')

        else:

            if 'without_bar_document' in request.GET and request.GET['without_bar_document'] == "true":
                kill_house_requests = KillHouseRequest.objects.filter(
                    (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                        killer__in=kill_house)),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    assignment_state_archive='True',
                    bar_document_status__isnull=True,
                    non_receipt=False,
                    trash=False,

                ).order_by('-kill_request__recive_date')
            else:

                kill_house_requests = KillHouseRequest.objects.filter(
                    (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                        killer__in=kill_house)),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    assignment_state_archive='True',
                    non_receipt=False,
                    trash=False,

                ).order_by('-kill_request__recive_date')

        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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_requests_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_requests_list) == 0 else kill_house_requests_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(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)

    # تابع مربوط به نمایش اطلاعات بار وارد شده توسط کشتارگاه
    def update(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)

        role = request.data['role']
        request.data.pop('role')
        kill_house_assignment = KillHouseAssignmentInformation.objects.get(key=request.data['key'], trash=False)
        if kill_house_assignment.state == 'accepted':
            return Response({"result": "به علت تایید اطلاعات از سمت استان امکان ویرایش وجود ندارد!"})
        kill_house_request = KillHouseRequest.objects.get(key=kill_house_assignment.kill_house_request.key)
        province_kill_request = ProvinceKillRequest.objects.get(key=kill_house_request.province_kill_request.key)
        poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key)
        date_time_of_now = datetime.now().date()
        if OperationLimitation.objects.all().first().kill_house_assignment_limitation == True:

            if date_time_of_now > kill_house_request.kill_request.recive_date.date() + timedelta(days=1):
                return Response({"result": "به علت مغایرت در تاریخ ثبت و تاریخ کشتار امکان ثبت اطلاعات وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
        car_with_load_image = request.data['car_with_load_image']
        request.data.pop('key')

        request.data.pop('car_with_load_image')
        if 'killer_key' in request.data.keys():
            if request.data['killer_key'] != None:
                killer = KillHouse.objects.get(key=request.data['killer_key'])
                kill_house_request.killer = killer
            request.data.pop('killer_key')

        pic = []
        # if 'car_without_load_image' in request.data.keys():
        #     car_without_load_image = request.data['car_without_load_image']
        #     request.data.pop('car_without_load_image')
        #     pic.append(car_without_load_image)
        pic.append(car_with_load_image)

        for p in pic:
            ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))
            # upload_object_resize(image_data=p, bucket_name="profileimagedefault",
            #                      object_name="{0}.jpg".format(str(ran)))
            # if p == car_without_load_image:
            #     kill_house_assignment.car_weight_without_load_image = ARVAN_Kill_house_URL + "{0}.jpg".format(str(ran))
            #     # os.remove("{0}.jpg".format(str(ran)))
            #
            # else:
            # kill_house_assignment.car_weight_with_load_image = ARVAN_Kill_house_URL + "{0}.jpg".format(str(ran))
            kill_house_assignment.car_weight_with_load_image = send_image_to_server(p)
            # os.remove("{0}.jpg".format(str(ran)))
        kill_house_assignment.state = 'pending'
        if role == 'Poultry':
            kill_house_assignment.poultry_update = True
        elif role == 'CityOperator':
            kill_house_assignment.city_update = True
        elif role == 'ProvinceFinancial':
            kill_house_assignment.province_update = True

        kill_house_assignment.state = 'pending'
        kill_house_assignment.net_weight = request.data['car_weight_with_load'] - request.data[
            'car_weight_without_load']
        kill_house_assignment.save()
        kill_house_request.accepted_real_quantity = request.data['real_quantity']
        kill_house_request.accepted_real_weight = request.data['car_weight_with_load'] - request.data[
            'car_weight_without_load']
        kill_house_request.accepted_assignment_real_quantity = int(request.data['real_quantity'])
        kill_house_request.accepted_assignment_real_weight = request.data['car_weight_with_load'] - request.data[
            'car_weight_without_load']
        kill_house_request.assignment_state_archive = 'True'
        kill_house_request.save()
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
        update_kill_house_requests(province_kill_request, poultry_request)
        update_province_kill_requests(hatching)
        poultry_prediction(hatching.poultry)
        serializer = self.serializer_class(kill_house_assignment)
        serializer.update(instance=kill_house_assignment, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به ایجاد و ویرایش و جذف و نمایش فاکتور از سمت استان برای کشتارگاه
class ProvinceFactorToKillHouseViewSet(viewsets.ModelViewSet):
    queryset = ProvinceFactorToKillHouse.objects.all()
    serializer_class = ProvinceFactorToKillHouseSerializer
    permission_classes = [TokenHasReadWriteScope]


# ویوست مربوط به ایجاد و ویرایش و جذف و نمایش  نماینده دامپزشکی برای  کشتارگاه
class VetViewSet(viewsets.ModelViewSet):
    queryset = Vet.objects.all()
    serializer_class = VetSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = VetFilterSet
    pagination_class = CustomPagination
    filterset_fields = [
        'user__national_id',
        'user__base_order',
        'user__mobile',

    ]

    # تابع مربوط به ایجاد نماینده دامپزشکی برای  کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)

        user = UserProfile.objects.get(key=request.data['user_key'], trash=False)
        kill_house = KillHouse.objects.get(key=request.data['kill_house_key'], trash=False)
        request.data.pop('user_key')
        request.data.pop('kill_house_key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            vet = serializer.create(validated_data=request.data)
            vet.kill_house = kill_house
            vet.user = user
            vet.save()
            vet_serializer = self.serializer_class(vet)
            return Response(vet_serializer.data, status=status.HTTP_201_CREATED)

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

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

        # refresh(request.user.id)

        if 'kill_house_info' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            vet = Vet.objects.get(user=user, trash=False)
            kill_house_vet = KillHouseVet.objects.filter(vet=vet)
            if kill_house_vet.count() > 0:
                kill_house_vet = kill_house_vet.last()
                profile_info = {
                    'kill_house_name': kill_house_vet.kill_house.name,
                    'kill_house_user': kill_house_vet.kill_house.kill_house_operator.user.fullname,
                    'kill_house_mobile': kill_house_vet.kill_house.kill_house_operator.user.mobile,
                    'kill_house_city': kill_house_vet.kill_house.kill_house_operator.user.city.name,
                    'kill_house_province': kill_house_vet.kill_house.kill_house_operator.user.province.name,
                }
                return Response(profile_info, status=status.HTTP_200_OK)

        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            user_serializer = SystemUserProfileSerializer(user)
            vet = Vet.objects.get(user=user, trash=False)
            vet_serializer = VetSerializer(vet)
            vet_farm = VetFarm.objects.filter(vet=vet, trash=False)
            serializer = VetFarmSerializer(vet_farm, many=True)
            kill_house_vet = KillHouseVet.objects.filter(vet=vet)
            if kill_house_vet.count() > 0:
                kill_house_vet_serializer = KillHouseVetSerializer(kill_house_vet.last())
                profile_info = {
                    # 'profile': user_serializer.data,
                    'vet': vet_serializer.data,
                    'kill_house_vet': kill_house_vet_serializer.data
                }
            else:

                profile_info = {
                    # 'profile': user_serializer.data,
                    'vet': vet_serializer.data
                    # 'vet_farms':serializer.data
                }
            return Response(profile_info, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        vet_farm_flag = request.GET.get('vet_farm')

        excluded_ids = set()
        if vet_farm_flag:
            if vet_farm_flag == 'true':
                excluded_ids = set(VetFarm.objects.filter(trash=False).values_list('vet__id', flat=True).distinct())
            elif vet_farm_flag == 'false':
                excluded_ids = set(
                    KillHouseVet.objects.filter(trash=False).values_list('vet__id', flat=True).distinct())
        else:
            vet_farm_ids = set(VetFarm.objects.filter(trash=False).values_list('vet__id', flat=True).distinct())
            kill_house_ids = set(KillHouseVet.objects.filter(trash=False).values_list('vet__id', flat=True).distinct())
            excluded_ids = vet_farm_ids.union(kill_house_ids)

        vets = Vet.objects.filter(trash=False)
        if vet_farm_flag:
            vets = vets.filter(id__in=excluded_ids)
        else:
            vets = vets.exclude(id__in=excluded_ids)

        if value and search == 'filter' and value.strip() and value != 'undefined':
            vets = vets.filter(build_query(VetFarmAndKillHouseFilterSet, value))

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

        page = self.paginate_queryset(vets)
        if page is not None:
            serializer_class = (
                VetFarmListSerializer if vet_farm_flag == 'true' else VetKillHouseSerializer
                if vet_farm_flag == 'false' else VetSerializer
            )
            serializer = serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = VetKillHouseSerializer(vets, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseVetViewSet(viewsets.ModelViewSet):
    queryset = KillHouseVet.objects.all()
    serializer_class = KillHouseVetSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        if 'role' in request.data.keys():
            if request.data['role'] == 'ProvinceInspector' or request.data['role'] == 'ProvinceOperator':
                user = SystemUserProfile.objects.get(key=request.data['user_key'])
                vet = Vet.objects.get(user=user, trash=False)
                request.data.pop('user_key')
                request.data.pop('role')


        else:
            request.data.pop('role')
            user = SystemUserProfile.objects.get(user=request.user)
            vet = Vet.objects.get(user=user, trash=False)
        kill_house = KillHouse.objects.get(key=request.data['key'])
        request.data.pop('key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_vet = serializer.create(validated_data=request.data)
            kill_house_vet.vet = vet
            kill_house_vet.kill_house = kill_house
            kill_house_vet.save()
            kill_house_vet_serializer = self.serializer_class(kill_house_vet)
            return Response(kill_house_vet_serializer.data, status=status.HTTP_201_CREATED)
        return Response({"result": "مشکلی پیش آمذه است !"}, status=status.HTTP_403_FORBIDDEN)

    def destroy(self, request, pk=None, *args, **kwargs):
        try:
            user = SystemUserProfile.objects.get(key=request.GET['user_key'])
            vet = Vet.objects.get(user=user, trash=False)
            kill_house = KillHouse.objects.get(key=request.GET['key'])
            kill_house_vet = KillHouseVet.objects.get(kill_house=kill_house, vet=vet, trash=False)
            kill_house_vet.trash = True
            kill_house_vet.save()

            return Response(status=status.HTTP_200_OK)
        except:
            return Response({"result": "مشکلی پیش آمده است !"}, status=status.HTTP_403_FORBIDDEN)


# ویوست مربوط به تایید یا رد بار رسیده به کشتارگاه توسط نماینده دامپزشکی
class VetCheckRequestViewSet(viewsets.ModelViewSet):
    queryset = VetCheckRequest.objects.all()
    serializer_class = VetCheckRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    # تابع مربوط به تایید یا رد بار رسیده به کشتارگاه توسط نماینده دامپزشکی
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        vet = Vet.objects.get(user=user, trash=False)
        kill_house_vet = KillHouseVet.objects.filter(vet=vet, trash=False).last()
        kill_house_req = KillHouseRequest.objects.get(key=request.data['kill_house_request_key'], trash=False)
        evacuation_permit = EvacuationPermit.objects.all().first()
        if evacuation_permit:
            if evacuation_permit.type == 'force':
                if kill_house_req.clearance_code == None:
                    return Response(
                        {"result": "قبل از ورود کد قرنطینه توسط دامپزشک فارم امکان تایید تخلیه وجود ندارد!"},
                        status=status.HTTP_403_FORBIDDEN)
        if OperationLimitation.objects.all().first().kill_house_vet_limitation == True:

            if kill_house_req.assignment_state_archive == 'True':
                return Response({"result": "به علت ورود اطلاعات بار امکان تایید تخلیه وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        province_kill_request = ProvinceKillRequest.objects.get(key=kill_house_req.province_kill_request.key,
                                                                trash=False)
        if int(request.data['accepted_real_quantity']) > 0 and request.data['accepted_real_weight'] > 0:
            kill_house_req.accepted_real_quantity = int(request.data['accepted_real_quantity'])
            kill_house_req.accepted_real_weight = request.data['accepted_real_weight']
        kill_house_req.vet_accepted_real_quantity = int(request.data['accepted_real_quantity'])
        kill_house_req.vet_accepted_real_weight = request.data['accepted_real_weight']
        kill_house_req.save()

        poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key)
        request.data.pop('kill_house_request_key')
        if 'accepted_real_quantity' in request.data.keys() and 'accepted_real_weight' in request.data.keys():
            if request.data['accepted_real_quantity'] != None and request.data['accepted_real_weight'] != None:
                if int(request.data['accepted_real_quantity']) > 0 and request.data['accepted_real_weight'] > 0:
                    if kill_house_req.assignment_state_archive == 'pending' and kill_house_req.accepted_assignment_real_quantity == 0:
                        update_kill_house_requests(province_kill_request, poultry_request)
                        update_province_kill_requests(hatching)
                        poultry_prediction(hatching.poultry)

                # kill_house_req.accepted_real_quantity = int(request.data['accepted_real_quantity'])
                kill_house_req.vet_accepted_real_quantity = int(request.data['accepted_real_quantity'])

            request.data.pop('accepted_real_quantity')
        if 'accepted_real_weight' in request.data.keys():
            if request.data['accepted_real_weight'] != None:
                # kill_house_req.accepted_real_weight = request.data['accepted_real_weight']
                kill_house_req.vet_accepted_real_weight = request.data['accepted_real_weight']
            request.data.pop('accepted_real_weight')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            vet_check = serializer.create(validated_data=request.data)
            vet_check.kill_house_request = kill_house_req
            if vet_check.state == 'accepted':
                kill_house_req.vet_state = 'accepted'
                kill_house_req.active_state = 'inactive'
                kill_house_req.save()
            else:
                kill_house_req.vet_state = 'rejected'
                kill_house_req.active_state = 'inactive'
                kill_house_req.save()

            vet_check.kill_house_vet = kill_house_vet
            vet_check.save()
            vet_check_serializer = self.serializer_class(vet_check)
            return Response(vet_check_serializer.data, status=status.HTTP_201_CREATED)

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


# ویوست مربوط به ایجاد نمایش و ویرایش  و حذف درخواست بورسی کشتارگاه
class KillHouseRequestExchangeViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequestExchange.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestExchangeSerializer

    # تابع مربوط به ایجاد درخواست بورسی کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = UserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.get(user=user, trash=False)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_request_exchange = serializer.create(validated_data=request.data)
            kill_house_request_exchange.user = user
            kill_house_request_exchange.kill_house = kill_house
            kill_house_request_exchange.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)


# ویوست مربوط به ایجاد نمایش و ویرایش  و حذف درخواست بورسی رزرو شده کشتارگاه
class KillHouseRequestExchangeReserveViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequestExchangeReserve.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestExchangeReserveSerializer

    # تابع مربوط به ایجاد درخواست بورسی رزرو شده کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = UserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.get(user=user, trash=False)
        poultry_exchange = PoultryRequestExchange.objects.get(key=request.data['key'], trash=False)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_request_exchange_reserve = serializer.create(validated_data=request.data)
            kill_house_request_exchange_reserve.poultry_exchange = poultry_exchange
            kill_house_request_exchange_reserve.kill_house = kill_house
            kill_house_request_exchange_reserve.save()
            poultry_exchange.state = 'reserved'
            poultry_exchange.save()

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


# ویوست مربوط به ایجاد نمایش و ویرایش  و حذف درخواست بورسی رزرو شده کشتارگاه
class KillHouseRequestActionViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequestAction.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestActionSerializer

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.get(kill_house_operator__user=user, trash=False)
        poultry_request = PoultryRequest.objects.get(key=request.data['key'], trash=False)
        request.data.pop('key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_auction = serializer.create(validated_data=request.data)
            kill_house_auction.kill_house = kill_house
            kill_house_auction.poultry_request = poultry_request
            kill_house_auction.date = datetime.now() + timedelta(minutes=10)
            kill_house_auction.save()
            kill_house_auction_serializer = self.serializer_class(kill_house_auction)
            return Response(kill_house_auction_serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
        kill_house = KillHouse.objects.get(kill_house_operator=kill_house_operator, trash=False)
        queryset = KillHouseRequestAction.objects.filter(kill_house=kill_house, trash=False)
        # queryset = WareHouseFactor.objects.all().order_by('-create_date')
        serializer = KillHouseRequestActionSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        queryset = KillHouseRequestAction.objects.get(key__exact=request.GET["key"], trash=False)
        now = datetime.now()
        if now.hour <= queryset.date.hour and now.minute <= queryset.date.minute:
            queryset.delete()
            return Response({"result": "object deleted"}, status=status.HTTP_200_OK)
        else:
            return Response({"result": "object can not deleted"}, status=status.HTTP_403_FORBIDDEN)


# ویوست مربوط به ایجاد نمایش و ویرایش  و حذف درخواست بورسی رزرو شده کشتارگاه
class KillHouseRequestActionWinnerViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequestActionWinner.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestActionWinnerSerializer

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
        kill_house = KillHouse.objects.get(kill_house_operator=kill_house_operator, trash=False)
        queryset = KillHouseRequestActionWinner.objects.filter(kill_house_request_auction__kill_house=kill_house,
                                                               trash=False)
        # queryset = WareHouseFactor.objects.all().order_by('-create_date')
        serializer = KillHouseRequestActionWinnerSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


# ویوست مربوط به ایجاد نمایش و ویرایش و ... اضافه کردن ماشین به درخواست بورسی رزرو شده تایید شده کشتارگاه
class KillHouseRequestExchangeAddCarViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequestExchangeAddCar.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestExchangeAddCarSerializer

    # تابع مربوط به اضافه کردن ماشین به درخواست بورسی رزرو شده تایید شده کشتارگاه
    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        kill_house_reserve = KillHouseRequestExchangeReserve.objects.get(key=request.data['key'], trash=False)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_request_exchange_add_car = serializer.create(validated_data=request.data)
            kill_house_request_exchange_add_car.kill_house_reserve = kill_house_reserve
            kill_house_request_exchange_add_car.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)


class DriverViewSet(viewsets.ModelViewSet):
    queryset = KillHouseDriver.objects.all()
    serializer_class = KillHouseDriverSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        """
        Show Driver Cars Information
        """
        if 'my_car' in request.GET:
            # get user object
            userprofile = SystemUserProfile.objects.get(
                user=request.user, trash=False
            )
            # get driver object & cars information
            # driver = self.queryset.get(user=userprofile, trash=False)
            # cars_objects = driver.Kill_house_add_car
            # serializer = KillHouseADDCARSerializer(cars_objects)
            # return Response(serializer.data, status=status.HTTP_200_OK)
            cars = KillHouseDriver.objects.filter(user=userprofile, trash=False)
            # cars_objects = KillHouseADDCAR.objects.filter(driver=driver, trash=False)
            # serializer = KillHouseADDCARSerializer(cars_objects, many=True)
            serializer = KillHouseDriverSerializer(cars, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        # Show Driver Kill Requests Allocation
        if 'my_allocations' in request.GET:
            driver_allocations = []
            # get user object
            userprofile = SystemUserProfile.objects.get(
                user=request.user, trash=False
            )
            # get driver object & cars information
            # driver = self.queryset.get(user=userprofile, trash=False)
            # cars_object = driver.Kill_house_add_car
            kill_reqs = KillHouseRequest.objects.filter(add_car__driver__user=userprofile, trash=False)
            # for item in kill_req:
            #     if str(cars_object.key) == item.car['key']:
            #         driver_allocations.append(item)
            serializer = KillHouseRequestSerializer(kill_reqs, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response("Enter The Parameter", status=status.HTTP_400_BAD_REQUEST)

    def retrieve(self, request, pk=None, *args, **kwargs):
        # refresh(request.user.id)
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            kill_house_driver = KillHouseDriver.objects.get(user=user, trash=False)
            kill_house_driver_serializer = KillHouseDriverSerializer(kill_house_driver)
            profile_info = {
                'profile': kill_house_driver_serializer.data,
            }
            return Response(profile_info, status=status.HTTP_200_OK)


class DriverRequestCancelViewSet(viewsets.ModelViewSet):
    queryset = DriverRequestCancel.objects.all()
    serializer_class = DriverRequestCancelSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        kill_house_request = KillHouseRequest.objects.get(key=request.data['kill_house_request_key'], trash=False)
        request.data.pop('kill_house_request_key')
        add_car = KillHouseADDCAR.objects.get(key=request.data['Kill_house_add_car_key'], trash=False)
        request.data.pop('Kill_house_add_car_key')
        if KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_request).exists():
            return Response({"result": "can not cancel"}, status=status.HTTP_403_FORBIDDEN)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            driver_cancel = serializer.create(validated_data=request.data)
            if kill_house_request.province_kill_request != None:
                province_kill_request = ProvinceKillRequest.objects.get(
                    key=kill_house_request.province_kill_request.key, trash=False)
                province_kill_request.quantity += kill_house_request.quantity
                province_kill_request.save()
            else:
                kill_house_request_auction = KillHouseRequestActionWinner.objects.get(
                    key=kill_house_request.kill_house_request_auction_winner.key, trash=False)
                kill_house_request_auction.quantity += kill_house_request.quantity
                kill_house_request_auction.save()
            driver_cancel.kill_house_request = kill_house_request
            driver_cancel.Kill_house_add_car = add_car
            driver_cancel.save()
            kill_house_request.trash = True
            kill_house_request.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)


class KillHouseComplaintViewSet(viewsets.ModelViewSet):
    queryset = KillHouseComplaint.objects.all()
    serializer_class = KillHouseComplaintSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        role = request.data['role']
        request.data.pop('role')
        image_list = []
        bar = KillHouseAssignmentInformation.objects.get(key=request.data['bar_key'], trash=False)
        request.data.pop('bar_key')
        percent = request.data['percent']
        request.data.pop('percent')
        try:
            images = request.data['image']
            request.data.pop('image')
        except:
            images = None
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            complaint = serializer.create(validated_data=request.data)
            complaint.bar = bar
            if images != None:
                for image in images:
                    image_list.append(send_image_to_server(image))
                complaint.image = image_list
            if percent != None:
                complaint.percent = percent
            complaint.save()
            bar.unusual_casualties = True
            bar.save()
            if role == 'KillHouse':
                kill_house = KillHouse.objects.get(kill_house_operator__user=user)
                kill_house_name = kill_house.kill_house_operator.user.fullname
                information = {
                    "role": role,
                    "kill_house_name": kill_house.name,
                    "kill_house_operator_name": kill_house_name,
                    "date": str(complaint.create_date)
                }

            elif role == "KillHouseVet":
                vet = Vet.objects.get(user=user)
                kill_house_vet = KillHouseVet.objects.get(vet=vet)
                kill_house_vet_name = kill_house_vet.vet.user.fullname

                information = {
                    "role": role,
                    "kill_house_vet": kill_house_vet_name,
                    "date": str(complaint.create_date)
                }

            complaint.registrar = information
            complaint.save()

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

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

    def list(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        if 'role' in request.GET:
            killhousecomplaints = []
            if request.GET['role'] == 'KillHouse':
                kill_house_operator = KillHouseOperator.objects.get(user=user)
                kill_house = KillHouse.objects.get(kill_house_operator=kill_house_operator)
                killhousecomplaints = KillHouseComplaint.objects.filter(
                    bar__kill_house_request__killhouse_user=kill_house)
                if killhousecomplaints.count() > 0:
                    serializer = KillHouseComplaintSerializer(killhousecomplaints, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)
            elif request.GET['role'] == 'KillHouseVet':
                vet = Vet.objects.get(user=user)
                kill_house_vet = KillHouseVet.objects.get(vet=vet)
                kill_house = KillHouse.objects.get(key=kill_house_vet.kill_house.key)
                killhousecomplaints = KillHouseComplaint.objects.filter(
                    bar__kill_house_request__killhouse_user=kill_house)
                if killhousecomplaints.count() > 0:
                    serializer = KillHouseComplaintSerializer(killhousecomplaints, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)
            else:
                killhousecomplaints = KillHouseComplaint.objects.filter(
                    bar__kill_house_request__killhouse_user__system_address__province__id=user.province.id)
                if killhousecomplaints.count() > 0:
                    serializer = KillHouseComplaintSerializer(killhousecomplaints, many=True)
                    return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(killhousecomplaints, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        # refresh(request.user.id)
        Killhousecomplaint = KillHouseComplaint.objects.get(key=request.data['key'])
        new_bar = KillHouseAssignmentInformation.objects.get(key=request.data['bar_key'], trash=False)
        request.data.pop('key')
        request.data.pop('bar_key')
        percent = request.data['percent']
        new_title = request.data['title']
        new_image = request.data['image']
        new_percent = request.data['percent']
        new_message = request.data['message']

        Killhousecomplaint.bar = new_bar
        Killhousecomplaint.title = new_title
        Killhousecomplaint.image = new_image
        Killhousecomplaint.percent = new_percent
        Killhousecomplaint.message = new_message
        Killhousecomplaint.save()

        return Response(status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        # refresh(request.user.id)
        Killhousecomplaint = KillHouseComplaint.objects.get(key=request.data['key'])
        Killhousecomplaint.trash = True
        Killhousecomplaint.save()

        return Response(status=status.HTTP_200_OK)


class CheckKillHouseComplaintViewSet(viewsets.ModelViewSet):
    queryset = CheckKillHouseComplaint.objects.all()
    serializer_class = CheckKillHouseComplaintSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        complaint = KillHouseComplaint.objects.get(key=request.data['complaint_key'], trash=False)
        request.data.pop('complaint_key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            percent = PercentageOfLosses.objects.all()
            if percent.count() > 0:
                percent = percent.last()
            else:
                return Response('dont have PercentageOfLosses ', status=status.HTTP_403_FORBIDDEN)

            check = serializer.create(validated_data=request.data)
            check.camplaint = complaint
            if check.state == 'accepted':
                bar = KillHouseAssignmentInformation.objects.get(key=complaint.bar.key)
                complaint_percent = complaint.percent
                if float(complaint_percent) > float(percent.percent):
                    main_percent = float(complaint_percent) - float(percent.percent)
                    bar.car_weight_with_load = float(bar.car_weight_with_load) - (
                            (main_percent / 100) * (float(bar.car_weight_with_load)))
                    bar.net_weight = float(bar.net_weight) - (
                            (main_percent / 100) * (float(bar.net_weight)))
                    bar.save()
                province_factor = ProvinceFactorToKillHouse.objects.filter(
                    province_check_info__kill_house_assignment__key=complaint.bar.key)
                poultry_factor = ProvinceFactorToKillHouseForPoultry.objects.filter(
                    province_check_info__kill_house_assignment__key=complaint.bar.key)

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

        return Response(serializer.errors)


class KillHouseBarReportingViewSet(viewsets.ModelViewSet):
    queryset = KillHouseAssignmentInformation.objects.all()
    serializer_class = KillHouseAssignmentInformationSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        return Response(status=status.HTTP_401_UNAUTHORIZED)

    def update(self, request, *args, **kwargs):
        return Response(status=status.HTTP_401_UNAUTHORIZED)

    def destroy(self, request, *args, **kwargs):
        return Response(status=status.HTTP_401_UNAUTHORIZED)

    def partial_update(self, request, *args, **kwargs):
        return Response(status=status.HTTP_401_UNAUTHORIZED)

    def list(self, request, *args, **kwargs):
        total_list = []
        net_weight = 0
        api_key = request.GET['api_key']
        if api_key == PROJECT_API_KEY:
            for kill_house in KillHouse.objects.filter(system_address__province__id=1):
                internal_list = []

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

                assignments = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request__killhouse_user=kill_house, create_date__year=date_time.year,
                    create_date__month=date_time.month, create_date__day=date_time.day)
                if assignments.count() > 0:

                    for assignment in assignments:
                        net_weight += assignment.net_weight

                    internal_dict = {

                        "date": date_time,
                        "weight": net_weight,
                    }
                    internal_list.append(internal_dict)

                    kill_house_dict = {
                        "kill_house_name": kill_house.name,
                        "fullname": kill_house.kill_house_operator.user.fullname,
                        "mobile": kill_house.kill_house_operator.user.mobile,
                        "city": kill_house.system_address.city.name,
                        "province": kill_house.system_address.province.name,
                        "bar_info": internal_list,
                    }
                    total_list.append(kill_house_dict)

            return Response(total_list, status=status.HTTP_200_OK)


class CheckUnusualCasualtiesViewSet(viewsets.ModelViewSet):
    queryset = CheckUnusualCasualties.objects.all()
    serializer_class = CheckUnusualCasualtiesSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        # refresh(request.user.id)
        user = SystemUserProfile.objects.get(user=request.user)
        # return Response(user.fullname)
        kill_house_complaint = KillHouseComplaint.objects.get(key=request.data['key'])
        request.data.pop('key')
        bar_info = KillHouseAssignmentInformation.objects.get(key=kill_house_complaint.bar.key)
        state = request.data['state']
        if state == "accepted":
            percentage_losses = PercentageOfLosses.objects.all()
            if percentage_losses.count() > 0:
                percentage_losses = percentage_losses.last().percent
            else:
                return Response({"result": "enter percentage of losses"}, status=status.HTTP_403_FORBIDDEN)
            weight = kill_house_complaint.bar.net_weight - (kill_house_complaint.bar.net_weight * (
                    (kill_house_complaint.percent / 100) - (percentage_losses / 100)))
            bar_info.weight_withs_losses = weight
            bar_info.save()
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            unusualcasualties = serializer.create(validated_data=request.data)
            unusualcasualties.complaint = kill_house_complaint
            if unusualcasualties.state == 'accepted':
                kill_house_complaint.state = 'accepted'
                kill_house_complaint.save()
            if unusualcasualties.state == 'rejected':
                unusualcasualties.message = request.data['message']
                kill_house_complaint.state = 'rejected'
                kill_house_complaint.message = request.data['message']
                kill_house_complaint.save()
            unusualcasualties.save()
            inter_dict = {
                "operatorname": user.fullname,
                "create_date": str(unusualcasualties.create_date),
                "role": request.data['role'],
                "state": unusualcasualties.state,
            }
            unusualcasualties.role = inter_dict
            unusualcasualties.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)


@api_view(["POST"])
@csrf_exempt
@permission_classes([AllowAny])
def make_kill_request(request):
    user = SystemUserProfile.objects.get(user=request.user)
    now = datetime.now().date()
    for kill_house in KillHouse.objects.filter(system_address__province=user.province):
        debt_amount = 0
        percentage = KillHousePercentage.objects.get(kill_house=kill_house)
        total_poultry_request = TotalPoultryRequestQuantity.objects.filter(create_date__year=now.year,
                                                                           create_date__month=now.month,
                                                                           create_date__day=now.day).order_by('id')
        first_average_weight = 0
        first_assignment_average_weight = 0
        seconde_average_weight = 0
        seconde_assignment_average_weight = 0
        all_assigntments = KillHouseAssignmentInformation.objects.filter(
            kill_house_request__killhouse_user=kill_house).order_by('id')
        if all_assigntments.count() > 0:
            for all_assigntment in all_assigntments:
                first_assignment_average_weight += all_assigntment.net_weight / all_assigntment.real_quantity
            first_average_weight += round(first_assignment_average_weight / all_assigntments.count(), 2)
            four_all_assigntments = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__killhouse_user=kill_house).order_by('id')[:4]

            for four_last_assingment in four_all_assigntments:
                seconde_assignment_average_weight += four_last_assingment.net_weight / four_last_assingment.real_quantity
            seconde_average_weight += round(seconde_assignment_average_weight / four_all_assigntments.count(), 2)

        if total_poultry_request.count() > 0:
            total_poultry_request = total_poultry_request.last()
            if total_poultry_request.input_quantity != 0:
                percentage.quantity = int(((percentage.percent / 100) / 100) * total_poultry_request.input_quantity)
            else:
                percentage.quantity = int(((percentage.percent / 10000) * total_poultry_request.quantity))
            percentage.save()
            poultry_factors = ProvinceFactorToKillHouseForPoultry.objects.filter(
                province_check_info__kill_house_assignment__kill_house_request__killhouse_user=kill_house,
                paid_state='pending')
            province_factors = ProvinceFactorToKillHouse.objects.filter(
                province_check_info__kill_house_assignment__kill_house_request__killhouse_user=kill_house,
                paid_state='pending')
            if poultry_factors.count() > 0:
                for poultry_factor in poultry_factors:
                    debt_amount += poultry_factor.total_price
            if province_factors.count() > 0:

                for province_factor in province_factors:
                    debt_amount += province_factor.total_price

            kill_req = KillRequest(
                kill_capacity=percentage.quantity,
                remain_quantity=percentage.quantity,
                recive_time='06 - 14',
                recive_date=datetime.now(),
                first_average_weight=seconde_average_weight,
                second_average_weight=first_average_weight,
                kill_house=kill_house

            )
            kill_req.save()
            if debt_amount > 0:
                kill_req.debt_amount = debt_amount
                kill_req.debt = True
                kill_req.save()

    return JsonResponse({"msg": "Done"})


class KillHouseNewViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.select_related('kill_house_operator__user').filter(trash=False)
    # queryset = KillHouse.objects.filter(trash=False)
    serializer_class = KillHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

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

        FullName = [kill_house.kill_house_operator.user.fullname for kill_house in kill_houses]

        return Response(FullName, status=status.HTTP_200_OK)


class KillHouseWareHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouseWareHouse.objects.all()
    serializer_class = KillHouseWareHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        date = datetime.strptime(request.GET['date'],
                                 '%Y-%m-%d').date() if 'date' in request.GET else now
        if 'kill_house_key' in request.GET:
            kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'], trash=False)
        else:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()

        kill_house_ware_house = KillHouseWareHouse.objects.filter(kill_house=kill_house,
                                                                  date__date=date,
                                                                  trash=False).last()

        if kill_house_ware_house is None:
            ware_house_date = datetime(year=date.year, month=date.month, day=date.day, hour=1, minute=12, second=20)
            kill_house_ware_house = KillHouseWareHouse(
                kill_house=kill_house,
                date=ware_house_date
            )
            kill_house_ware_house.save()

        bar_quantity = 0
        allocated_quantity = 0
        bar_live_weight = 0
        number_of_carcasses = 0
        update_number_of_carcasses = 0
        weight_of_carcasses = 0
        update_weight_of_carcasses = 0
        ave_weight_of_carcasses = 0
        free_number_of_carcasses = 0
        free_weight_of_carcasses = 0
        free_sale_number_of_carcasses = 0
        free_sale_weight_of_carcasses = 0
        free_bar_quantity = 0
        free_sale_bar_quantity = 0
        total_bar_quantity = 0
        total_number_of_carcasses = 0
        total_weight_of_carcasses = 0

        # assingments = KillHouseAssignmentInformation.objects.filter(kill_house_request__killhouse_user=kill_house,
        #                                                             state__in=('pending', 'accepted'),
        #                                                             kill_house_request__kill_request__recive_date__year=date.year,
        #                                                             kill_house_request__kill_request__recive_date__month=date.month,
        #                                                             kill_house_request__kill_request__recive_date__day=date.day,
        #                                                             trash=False).select_related('kill_house_request')
        one_day_ago = date - timedelta(days=1)

        kill_house_requests = KillHouseRequest.objects.filter(killhouse_user=kill_house,
                                                              kill_request__recive_date__date=one_day_ago,
                                                              ware_house_confirmation=True, trash=False)
        if kill_house_requests.count() > 0:
            for kill_house_request in kill_house_requests:
                bar_quantity += 1
                allocated_quantity += kill_house_request.accepted_real_quantity
                bar_live_weight += kill_house_request.accepted_real_weight
                number_of_carcasses += kill_house_request.ware_house_accepted_real_quantity
                weight_of_carcasses += kill_house_request.ware_house_accepted_real_weight
                # kill_house_loss_percentage = KillHousePercentageOfLosses.objects.all().last()
                # if kill_house_loss_percentage:
                #     weight_of_carcasses += kill_house_request.accepted_real_weight - (
                #             (kill_house_loss_percentage.percent / 100) * kill_house_request.accepted_real_weight)
                # else:
                #     weight_of_carcasses += kill_house_request.accepted_real_weight - (
                #             (25 / 100) * kill_house_request.accepted_real_weight)

                ave_weight_of_carcasses += weight_of_carcasses / number_of_carcasses
        free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, date__date=date, ware_house=True,
                                                               trash=False)
        freezing_quantity = 0
        freezing_weight = 0
        freezing_bars = ColdHouseAllocations.objects.filter(kill_house_ware_house=kill_house_ware_house,
                                                            state__in=('pending', 'accepted'), date__date=date,
                                                            trash=False)
        if len(freezing_bars) > 0:
            for freezing_bar in freezing_bars:
                freezing_quantity += freezing_bar.accepted_quantity if freezing_bar.accepted_quantity > 0 else freezing_bar.quantity
                freezing_weight += freezing_bar.accepted_weight if freezing_bar.accepted_weight > 0 else freezing_bar.weight
        if free_bars.count() > 0:
            for free_bar in free_bars:
                free_bar_quantity += 1
                free_number_of_carcasses += free_bar.number_of_carcasses
                free_weight_of_carcasses += free_bar.weight_of_carcasses
        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house,
                                                                                       date__date=date,
                                                                                       trash=False)
        if kill_house_free_sale_bar_info.count() > 0:
            for kill_house_free_sale in kill_house_free_sale_bar_info:
                free_sale_bar_quantity += 1
                free_sale_number_of_carcasses += kill_house_free_sale.number_of_carcasses
                free_sale_weight_of_carcasses += kill_house_free_sale.weight_of_carcasses

        update_number_of_carcasses = kill_house_ware_house.updated_number_of_carcasses
        update_weight_of_carcasses = kill_house_ware_house.updated_weight_of_carcasses
        total_bar_quantity = bar_quantity + free_bar_quantity + free_sale_bar_quantity
        total_number_of_carcasses = number_of_carcasses + free_number_of_carcasses + kill_house_ware_house.pre_cold_number_of_carcasses_to_ware_house
        update_total_number_of_carcasses = update_number_of_carcasses + free_number_of_carcasses + kill_house_ware_house.pre_cold_number_of_carcasses_to_ware_house if update_number_of_carcasses > 0 else 0
        total_weight_of_carcasses = weight_of_carcasses + free_weight_of_carcasses + kill_house_ware_house.pre_cold_weight_of_carcasses_to_ware_house
        update_total_weight_of_carcasses = update_weight_of_carcasses + free_weight_of_carcasses + kill_house_ware_house.pre_cold_weight_of_carcasses_to_ware_house if update_weight_of_carcasses > 0 else 0

        kill_house_ware_house.bar_quantity = bar_quantity
        kill_house_ware_house.allocated_quantity = allocated_quantity
        kill_house_ware_house.bar_live_weight = bar_live_weight
        kill_house_ware_house.number_of_carcasses = number_of_carcasses
        kill_house_ware_house.update_number_of_carcasses = update_number_of_carcasses
        kill_house_ware_house.weight_of_carcasses = weight_of_carcasses
        kill_house_ware_house.update_weight_of_carcasses = update_weight_of_carcasses
        kill_house_ware_house.ave_weight_of_carcasses = weight_of_carcasses / number_of_carcasses if number_of_carcasses > 0 else 0
        kill_house_ware_house.update_ave_weight_of_carcasses = update_weight_of_carcasses / update_number_of_carcasses if update_number_of_carcasses > 0 else 0
        kill_house_ware_house.free_bar_quantity = free_bar_quantity
        kill_house_ware_house.number_of_free_carcasses = free_number_of_carcasses
        kill_house_ware_house.free_weight_of_carcasses = free_weight_of_carcasses
        kill_house_ware_house.free_sale_quantity = free_sale_number_of_carcasses
        kill_house_ware_house.free_sale_weight = free_sale_weight_of_carcasses
        kill_house_ware_house.total_bar_quantity = total_bar_quantity
        kill_house_ware_house.freezing_quantity = freezing_quantity
        kill_house_ware_house.freezing_weight = freezing_weight
        kill_house_ware_house.total_number_of_carcasses = total_number_of_carcasses
        kill_house_ware_house.update_total_number_of_carcasses = update_total_number_of_carcasses
        kill_house_ware_house.total_weight_of_carcasses = total_weight_of_carcasses
        kill_house_ware_house.update_total_weight_of_carcasses = update_total_weight_of_carcasses
        if update_total_weight_of_carcasses == 0:
            kill_house_ware_house.remain_total_weight_of_carcasses = total_weight_of_carcasses - kill_house_ware_house.allocated_total_weight_of_carcasses if kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house == 0 else 0
        else:
            kill_house_ware_house.remain_total_weight_of_carcasses = update_total_weight_of_carcasses - kill_house_ware_house.allocated_total_weight_of_carcasses if kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house == 0 else 0
        if update_total_number_of_carcasses == 0:
            kill_house_ware_house.remain_total_number_of_carcasses = total_number_of_carcasses - kill_house_ware_house.allocated_total_number_of_carcasses if kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house == 0 else 0
        else:
            kill_house_ware_house.remain_total_number_of_carcasses = update_total_number_of_carcasses - kill_house_ware_house.allocated_total_number_of_carcasses if kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house == 0 else 0
        kill_house_ware_house.final_total_number_of_carcasses = kill_house_ware_house.update_total_number_of_carcasses if kill_house_ware_house.update_total_number_of_carcasses > 0 else kill_house_ware_house.total_number_of_carcasses
        kill_house_ware_house.final_total_weight_of_carcasses = kill_house_ware_house.update_total_weight_of_carcasses if kill_house_ware_house.update_total_weight_of_carcasses > 0 else kill_house_ware_house.total_weight_of_carcasses
        kill_house_ware_house.save()

        if 'state' in request.GET:
            total_number_of_carcasses_temp = kill_house_ware_house.update_total_number_of_carcasses if kill_house_ware_house.update_total_number_of_carcasses > 0 else kill_house_ware_house.total_number_of_carcasses
            total_weight_of_carcasses_temp = kill_house_ware_house.update_total_weight_of_carcasses if kill_house_ware_house.update_total_weight_of_carcasses > 0 else kill_house_ware_house.total_weight_of_carcasses
            update_fields = {
                "ware_house_key": kill_house_ware_house.key,
                "total_number_of_carcasses": kill_house_ware_house.final_total_number_of_carcasses,
                "pre_cold_number_of_carcasses_self_ware_house": kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house,
                "pre_cold_weight_of_carcasses_self_ware_house": kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house,
                "total_weight_of_carcasses": kill_house_ware_house.final_total_weight_of_carcasses,
                "allocated_total_number_of_carcasses": kill_house_ware_house.allocated_total_number_of_carcasses,
                "allocated_total_weight_of_carcasses": kill_house_ware_house.allocated_total_weight_of_carcasses,
                "remain_total_number_of_carcasses": kill_house_ware_house.remain_total_number_of_carcasses,
                "remain_total_weight_of_carcasses": kill_house_ware_house.remain_total_weight_of_carcasses,
                "freezing_quantity": kill_house_ware_house.freezing_quantity,
                "freezing_weight": kill_house_ware_house.freezing_weight,
                "free_sale_quantity": kill_house_ware_house.free_sale_quantity,
                "free_sale_weight": kill_house_ware_house.free_sale_weight,
                "total_average_weight_of_carcasses": round(
                    kill_house_ware_house.final_total_weight_of_carcasses / kill_house_ware_house.final_total_number_of_carcasses,
                    2) if kill_house_ware_house.final_total_number_of_carcasses > 0 else 0,

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

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

    def update(self, request, pk=None, *args, **kwargs):
        ware_house = KillHouseWareHouse.objects.get(key=request.data['key'])
        ware_house.updated_number_of_carcasses = int(request.data['updated_number_of_carcasses'])
        ware_house.updated_weight_of_carcasses = request.data['updated_weight_of_carcasses']
        ware_house.total_weight_of_carcasses = request.data[
                                                   'updated_weight_of_carcasses'] + ware_house.free_weight_of_carcasses
        ware_house.total_number_of_carcasses = int(request.data[
                                                       'updated_number_of_carcasses']) + ware_house.number_of_free_carcasses
        ware_house.save()
        serializer = self.serializer_class(ware_house)
        serializer.update(instance=ware_house, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


class KillHouseWareHouseForDispensersViewSet(viewsets.ModelViewSet):
    queryset = KillHouseWareHouse.objects.all()
    serializer_class = KillHouseWareHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        date1 = datetime.strptime(request.GET['date1'], '%Y-%m-%d').date()
        date2 = datetime.strptime(request.GET['date2'], '%Y-%m-%d').date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if request.GET['role'] in ('CityCommerce', 'CityJahad', 'CityPoultry', 'CityOperator'):
            kill_house_ware_houses = KillHouseWareHouse.objects.filter(kill_house__system_address__city=user.city,
                                                                       date__date__gte=date1, date__date__lte=date2,
                                                                       trash=False)
        else:
            kill_house_ware_houses = KillHouseWareHouse.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                       trash=False)
        result = {
            "kill_houses": len(kill_house_ware_houses.values_list('kill_house', flat=True).distinct()),

            "total_number_of_carcasses": kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
                                             'total'] or 0,
            "total_weight_of_carcasses": kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
                                             'total'] or 0,
            "pre_cold_number_of_carcasses_self_ware_house":
                kill_house_ware_houses.aggregate(total=Sum('pre_cold_number_of_carcasses_self_ware_house'))[
                    'total'] or 0,
            "pre_cold_weight_of_carcasses_self_ware_house":
                kill_house_ware_houses.aggregate(total=Sum('pre_cold_weight_of_carcasses_self_ware_house'))[
                    'total'] or 0,
            "allocated_total_number_of_carcasses":
                kill_house_ware_houses.aggregate(total=Sum('allocated_total_number_of_carcasses'))['total'] or 0,
            "allocated_total_weight_of_carcasses":
                kill_house_ware_houses.aggregate(total=Sum('allocated_total_weight_of_carcasses'))['total'] or 0,
            "remain_total_number_of_carcasses":
                kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))['total'] or 0,
            "remain_total_weight_of_carcasses":
                kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))['total'] or 0,
            "freezing_quantity": kill_house_ware_houses.aggregate(total=Sum('freezing_quantity'))['total'] or 0,
            "freezing_weight": kill_house_ware_houses.aggregate(total=Sum('freezing_weight'))['total'] or 0,
            "free_sale_quantity": kill_house_ware_houses.aggregate(total=Sum('free_sale_quantity'))['total'] or 0,
            "free_sale_weight": kill_house_ware_houses.aggregate(total=Sum('free_sale_weight'))['total'] or 0
        }

        return Response(result, status=status.HTTP_200_OK)


class PreColdKillHouseWareHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouseWareHouse.objects.all()
    serializer_class = KillHouseWareHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

    def create(self, request, *args, **kwargs):
        now = datetime.now().date()
        kill_house_ware_house = KillHouseWareHouse.objects.get(key=request.data['ware_house_key'])
        if kill_house_ware_house.date.date() != now:
            return Response({"result": "به علت مغایرت تاریخ امکان پیش سرد وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

        tomorrow = kill_house_ware_house.date + timedelta(days=1)
        kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house = kill_house_ware_house.remain_total_number_of_carcasses
        kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house = kill_house_ware_house.remain_total_weight_of_carcasses
        kill_house_ware_house.remain_total_number_of_carcasses = 0
        kill_house_ware_house.remain_total_weight_of_carcasses = 0
        kill_house_ware_house.save()
        tomorrow_kill_house_ware_house = KillHouseWareHouse.objects.filter(kill_house=kill_house_ware_house.kill_house,
                                                                           date__date=tomorrow.date()).first()
        if not tomorrow_kill_house_ware_house:
            tomorrow_kill_house_ware_house = KillHouseWareHouse(
                kill_house=kill_house_ware_house.kill_house,
                date=kill_house_ware_house.date + timedelta(days=1)
            )
        tomorrow_kill_house_ware_house.save()
        tomorrow_kill_house_ware_house.final_total_number_of_carcasses += kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.total_number_of_carcasses += kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.final_total_weight_of_carcasses += kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.total_weight_of_carcasses += kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.remain_total_number_of_carcasses += kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.remain_total_weight_of_carcasses += kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.pre_cold_number_of_carcasses_to_ware_house = kill_house_ware_house.pre_cold_number_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.pre_cold_weight_of_carcasses_to_ware_house = kill_house_ware_house.pre_cold_weight_of_carcasses_self_ware_house
        tomorrow_kill_house_ware_house.save()
        return Response({"result": "با موفقیت انجام شد!"}, status=status.HTTP_201_CREATED)


class KillHouseFreeSaleBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeSaleBarInformation.objects.all()
    serializer_class = KillHouseFreeSaleBarInformationSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFreeSaleBarInformationFilterSet
    filterset_fields = [
        'type_car',
        'pelak',
        'clearance_code',
        'kill_house__name',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__mobile',
        'buyer__fullname',
        'buyer__first_name',
        'buyer__last_name',
        'buyer__mobile',
        'buyer__unit_name',
        'buyer_name',
        'buyer_mobile',
        'province',
        'city',

    ]

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        now = datetime.now().date()
        now_time = datetime.now().time()
        quota = request.data['quota']
        buyer = None
        dispenser = request.data.pop('dispenser',None)
        representative = request.data.pop('representative',None)
        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')
        elif 'buyer_key' in request.data.keys():
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
            buyer = OutProvinceCarcassesBuyer.objects.get(key=request.data['buyer_key'])
            request.data.pop('buyer_key')
        product = RolesProducts.objects.get(key=request.data['product_key'])
        request.data.pop('product_key')
        date = datetime.strptime(str(request.data['date']), '%Y-%m-%d').date()
        production_date = datetime.strptime(str(request.data['production_date']), '%Y-%m-%d').date()
        date = datetime(year=date.year, month=date.month, day=date.day, hour=now_time.hour,
                        minute=now_time.minute,
                        second=now_time.second)
        production_date = datetime(year=production_date.year, month=production_date.month, day=production_date.day,
                                   hour=now_time.hour,
                                   minute=now_time.minute,
                                   second=now_time.second)
        request.data.pop('date')
        request.data.pop('production_date')
        if OperationLimitation.objects.all().first().kill_house_free_sale_limitation == True:

            if now != date.date():
                return Response({"result": "به علت مغایرت تاریخ امکان فروش بار وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        carcass_distribution = RestrictionCarcassDistribution.objects.filter(trash=False,
                                                                             distribution_type='KillHouse',
                                                                             allow=True,
                                                                             out=True).first()
        if carcass_distribution and datetime.now().time() > carcass_distribution.time:
            return Response({"result": "لطفا در ساعات مجاز اقدام نمایید!"},
                            status=status.HTTP_403_FORBIDDEN)
        # ware_house = KillHouseWareHouse.objects.get(kill_house=kill_house, date__date=date)
        # if request.data['weight_of_carcasses'] > ware_house.remain_total_weight_of_carcasses:
        #     return Response({"result": "تعداد یا مقدار وارد شده از موجودی انبار بیشتر است !"},
        #                     status=status.HTTP_403_FORBIDDEN)
        kill_house_total_input_warehouse_governmental_weight = kill_house.total_input_warehouse_governmental_weight
        kill_house_total_input_warehouse_free_weight = kill_house.total_input_warehouse_free_weight

        if request.data['sale_type'] == 'free':
            quota = request.data['quota']
            if quota == 'governmental':
                if not kill_house.free_sale_form_governmental_quota:
                    return Response({"result": "مجاز به فروش آزاد از انبار دولتی نمیباشید!"},
                                    status=status.HTTP_403_FORBIDDEN)

        if quota == 'governmental':
            if kill_house.total_input_warehouse_governmental_weight < (
                    kill_house.total_selling_warehouse_governmental_weight + request.data['weight_of_carcasses']):
                return Response({"result": "مجاز به فروش دولتی بیشتر از ورودی دولتی انبار نمیباشید!"},
                                status=status.HTTP_403_FORBIDDEN)
        else:
            if kill_house.total_input_warehouse_free_weight < (
                    kill_house.total_selling_warehouse_free_weight + request.data['weight_of_carcasses']):
                return Response({"result": "مجاز به فروش آزاد بیشتر از ورودی آزاد انبار نمیباشید!"},
                                status=status.HTTP_403_FORBIDDEN)

        if quota == 'governmental':
            free_sale_type = request.data['sale_type']
            if kill_house.governmental_selling_permission:
                if free_sale_type == 'free':
                    if not kill_house.free_sale_form_governmental_quota:
                        if kill_house.total_commitment_selling_in_province_governmental_weight > kill_house.total_selling_in_province_governmental_weight:
                            return Response({"result": "ابتدا تعهد داخل استان رو تکمیل کنید!"},
                                            status=status.HTTP_403_FORBIDDEN)
                else:
                    if kill_house.total_commitment_selling_in_province_governmental_weight > kill_house.total_selling_in_province_governmental_weight:
                        return Response({"result": "ابتدا تعهد داخل استان رو تکمیل کنید!"},
                                        status=status.HTTP_403_FORBIDDEN)
            else:
                return Response({"result": "مجاز به فروش دولتی نمیباشید!"}, status=status.HTTP_403_FORBIDDEN)
            if kill_house.total_commitment_selling_out_province_governmental_weight > 0:
                if kill_house.total_selling_out_province_governmental_weight + request.data[
                    'weight_of_carcasses'] > kill_house.total_commitment_selling_out_province_governmental_weight:
                    return Response({"result": "به دلیل بیشتر از وزن تعهد مجاز به فروش دولتی نمیباشید!"},
                                    status=status.HTTP_403_FORBIDDEN)

        else:
            if kill_house.free_selling_permission:
                if kill_house.total_commitment_selling_in_province_free_weight > kill_house.total_selling_in_province_free_weight:
                    return Response({"result": "ابتدا تعهد داخل استان رو تکمیل کنید!"},
                                    status=status.HTTP_403_FORBIDDEN)
            else:
                return Response({"result": "مجاز به فروش آزاد نمیباشید!"}, status=status.HTTP_403_FORBIDDEN)

            if kill_house.total_commitment_selling_out_province_free_weight > 0:
                if kill_house.total_selling_out_province_free_weight + request.data[
                    'weight_of_carcasses'] > kill_house.total_commitment_selling_out_province_free_weight:
                    return Response({"result": "به دلیل بیشتر از وزن تعهد مجاز به فروش دولتی نمیباشید!"},
                                    status=status.HTTP_403_FORBIDDEN)

        ware_house_remain_weight = product.total_remain_weight
        allocations_weight = StewardAllocation.objects.filter(trash=False, receiver_state__in=('pending', 'accepted'),
                                                              kill_house=kill_house, date__date=now).aggregate(
            total=Sum('real_weight_of_carcasses'))['total'] or 0
        free_sales_weight = \
            KillHouseFreeSaleBarInformation.objects.filter(trash=False, kill_house=kill_house,
                                                           date__date=now).aggregate(
                total=Sum('real_weight_of_carcasses'))['total'] or 0
        total_weight = ware_house_remain_weight + allocations_weight + free_sales_weight
        free_sales_weight += request.data['weight_of_carcasses']

        # if kill_house.in_province_selling_limitation and kill_house.in_province_selling_limitation_percent > 0:
        #     in_province_limitation_weight = int(
        #         total_weight * (kill_house.in_province_selling_limitation_percent / 100))
        #     if allocations_weight < in_province_limitation_weight:
        #         return Response(
        #             {"result": "به دلیل عدم رعایت حداقل فروش/توزیع داخل استان امکان فروش به خارج استان وجود ندارد!"},
        #             status=status.HTTP_403_FORBIDDEN)
        #
        # if kill_house.out_province_selling_limitation and kill_house.out_province_selling_limitation_percent > 0:
        #     max_out_province_limitation_weight = int(
        #         total_weight * (kill_house.out_province_selling_limitation_percent / 100))
        #     if free_sales_weight > max_out_province_limitation_weight:
        #         return Response({"result": "سقف فروش به خارج استان امروز شما پر شده است!"},
        #                         status=status.HTTP_403_FORBIDDEN)
        if KillHouseFreeSaleBarInformation.objects.filter(trash=False, clearance_code=request.data['clearance_code'],
                                                          quarantine_weight_of_carcasses__gt=0).exists():
            return Response({"result": "کد قرنطینه در سامانه ثبت شده است!"},
                            status=status.HTTP_403_FORBIDDEN)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_free_sale_bar_info = serializer.create(validated_data=request.data)
            kill_house_free_sale_bar_info.kill_house = kill_house
            if buyer is not None:
                kill_house_free_sale_bar_info.buyer = buyer
                kill_house_free_sale_bar_info.buyer_name = buyer.fullname
                kill_house_free_sale_bar_info.buyer_mobile = buyer.mobile
                kill_house_free_sale_bar_info.city = buyer.city
                kill_house_free_sale_bar_info.province = buyer.province

            kill_house_free_sale_bar_info.date = date
            kill_house_free_sale_bar_info.production_date = production_date
            kill_house_free_sale_bar_info.product = product
            kill_house_free_sale_bar_info.dispenser = dispenser if dispenser else None
            kill_house_free_sale_bar_info.representative = representative if representative else None
            kill_house_free_sale_bar_info.real_number_of_carcasses = kill_house_free_sale_bar_info.number_of_carcasses
            kill_house_free_sale_bar_info.real_weight_of_carcasses = kill_house_free_sale_bar_info.weight_of_carcasses
            # ware_house.allocated_total_number_of_carcasses += kill_house_free_sale_bar_info.number_of_carcasses
            # ware_house.allocated_total_weight_of_carcasses += kill_house_free_sale_bar_info.weight_of_carcasses
            # ware_house.save()

            wage = 0
            wage_type = WageType.objects.filter(en_name='carcasse-sell', trash=False).first()
            if wage_type.status == True:
                wage = wage_type.amount
            kill_house_free_sale_bar_info.wage = wage
            kill_house_free_sale_bar_info.total_wage_amount = wage * kill_house_free_sale_bar_info.real_weight_of_carcasses

            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':
                        kill_house_free_sale_bar_info.union_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_sale_bar_info.total_wage_amount)
                        kill_house_free_sale_bar_info.union_share_percent = percentage_wage_type.percent
                    elif percentage_wage_type.share_type.en_name == 'company':
                        kill_house_free_sale_bar_info.company_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_sale_bar_info.total_wage_amount)
                        kill_house_free_sale_bar_info.company_share_percent = percentage_wage_type.percent

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

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

                    else:
                        kill_house_free_sale_bar_info.other_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_sale_bar_info.total_wage_amount)
                        kill_house_free_sale_bar_info.other_share_percent = percentage_wage_type.percent
            kill_house_free_sale_bar_info.save()
            allow_register_code = AllowRegisterCodeForKillHouseFreeSaleBarInformation.objects.filter(trash=False,
                                                                                                     active=True).first()
            if allow_register_code:
                number = random.randint(10000, 99000)
                kill_house_free_sale_bar_info.registration_code = number
                kill_house_free_sale_bar_info.system_registration_code = True
                if int(allow_register_code.time) > 0:
                    kill_house_free_sale_bar_info.active_expire_date_time = True
                    kill_house_free_sale_bar_info.expire_date_time_registration_code = datetime.now() + timedelta(
                        minutes=int(allow_register_code.time))
                kill_house_free_sale_bar_info.save()
                send_sms_for_sale_bar(kill_house_free_sale_bar_info)
            get_gid_out_province(kill_house_free_sale_bar_info.id)
            kill_house_free_sale_product_warehousing(product)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

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

                if role in ['ProvinceOperator', 'Commerce', 'ProvinceSupervisor''GuildRoom', 'SuperAdmin',
                            'ImprovingLivestock', 'AdminX', 'Supporter']:
                    if kill_house_key and kill_house_key != 'all':
                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            date__date__gte=date1,
                            date__date__lte=date2,
                            kill_house__key=kill_house_key,
                            trash=False)
                    else:
                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            date__date__gte=date1,
                            date__date__lte=date2,
                            trash=False)


                elif role in ['CityJahad', 'CityPoultry', 'CityOperator']:

                    if kill_house_key and kill_house_key != 'all':

                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            kill_house__system_address__city=user.city,
                            date__date__gte=date1,
                            date__date__lte=date2,
                            kill_house__key=kill_house_key,
                            trash=False)

                    else:

                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            kill_house__system_address__city=user.city,
                            date__date__gte=date1,
                            date__date__lte=date2,
                            trash=False)




                else:
                    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        kill_house=kill_house,
                        date__date__gte=date1,
                        date__date__lte=date2,
                        trash=False)

            else:
                if role in ['ProvinceOperator', 'Commerce', 'ProvinceSupervisor''GuildRoom', 'SuperAdmin',
                            'ImprovingLivestock', 'AdminX', 'Supporter']:

                    if kill_house_key and kill_house_key != 'all':

                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            trash=False, kill_house__key=kill_house_key)
                    else:
                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            trash=False)


                elif role in ['CityJahad', 'CityPoultry', 'CityOperator']:
                    if kill_house_key and kill_house_key != 'all':
                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            kill_house__system_address__city=user.city,
                            trash=False, kill_house__key=kill_house_key)
                    else:
                        kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                            kill_house__system_address__city=user.city,
                            trash=False)



                else:
                    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        kill_house=kill_house,
                        trash=False)

            if 'search' in request.GET:
                kill_house_free_sale_bar_info_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=kill_house_free_sale_bar_info
                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=kill_house_free_sale_bar_info)
                                kill_house_free_sale_bar_info_list = ps.filter()
                        kill_house_free_sale_bar_info = [] if len(
                            kill_house_free_sale_bar_info_list) == 0 else kill_house_free_sale_bar_info_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(kill_house_free_sale_bar_info)
            if page is not None:
                serializer = self.serializer_class(page, many=True)
                return self.get_paginated_response(serializer.data)

        else:
            now = datetime.now().date()
            date = datetime.strptime(str(request.GET['date']),
                                     '%Y-%m-%d').date() if 'date' in request.GET else now
            kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'])
            kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house,
                                                                                           date__year=date.year,
                                                                                           date__month=date.month,
                                                                                           date__day=date.day,
                                                                                           trash=False)

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

    def update(self, request, pk=None, *args, **kwargs):
        free_sale_bar = KillHouseFreeSaleBarInformation.objects.get(key=request.data['key'])
        product = free_sale_bar.product
        kill_house = free_sale_bar.kill_house
        if KillHouseFreeSaleBarInformation.objects.filter(trash=False,
                                                          clearance_code=request.data.get('clearance_code'),
                                                          quarantine_weight_of_carcasses__gt=0).exists() and 'register_code' not in request.data.keys():
            return Response({"result": "کد قرنطینه در سامانه ثبت شده است!"},
                            status=status.HTTP_403_FORBIDDEN)
        now = datetime.now().date()
        if free_sale_bar.quota == 'governmental':
            if free_sale_bar.kill_house.total_input_warehouse_governmental_weight < (
                    (
                            free_sale_bar.kill_house.total_selling_warehouse_governmental_weight - free_sale_bar.weight_of_carcasses) +
                    request.data[
                        'weight_of_carcasses']):
                return Response({"result": "وزن وارد شده بیشتر از باقی مانده دولتی می باشد!"},
                                status=status.HTTP_403_FORBIDDEN)
        else:
            if free_sale_bar.kill_house.total_input_warehouse_free_weight < (
                    (free_sale_bar.kill_house.total_selling_warehouse_free_weight - free_sale_bar.weight_of_carcasses) +
                    request.data[
                        'weight_of_carcasses']):
                return Response({"result": "وزن وارد شده بیشتر از باقی مانده آزاد می باشد!"},
                                status=status.HTTP_403_FORBIDDEN)
        allow_register_code = AllowRegisterCodeForKillHouseFreeSaleBarInformation.objects.filter(trash=False,
                                                                                                 active=True).first()
        if allow_register_code:
            if 'register_code' in request.data.keys():
                code = request.data['register_code']
                if code != free_sale_bar.registration_code:
                    return Response({"result": "کد وارد شده صحیح نیست"}, status=status.HTTP_403_FORBIDDEN)
                free_sale_bar.logged_registration_code = code
                request.data.pop('register_code')
            free_sale_bar.save()
        serializer = self.serializer_class(free_sale_bar)

        serializer.update(instance=free_sale_bar, validated_data=request.data)
        kill_house_free_sale_product_warehousing(product)
        free_sale_bar.real_number_of_carcasses = free_sale_bar.number_of_carcasses
        free_sale_bar.real_weight_of_carcasses = free_sale_bar.weight_of_carcasses
        free_sale_bar.total_wage_amount = free_sale_bar.wage * free_sale_bar.real_weight_of_carcasses
        free_sale_bar.save()
        kill_house_free_sale_product_warehousing(product)

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

        get_gid_out_province(free_sale_bar.id)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        free_sale_bar = KillHouseFreeSaleBarInformation.objects.get(key=request.GET['key'])
        product = free_sale_bar.product

        # ware_house = KillHouseWareHouse.objects.get(kill_house=free_sale_bar.kill_house,
        #                                             date__date=free_sale_bar.date.date(), trash=False)
        #
        # if ware_house.allocated_total_number_of_carcasses != free_sale_bar.real_number_of_carcasses or ware_house.allocated_total_weight_of_carcasses != free_sale_bar.real_weight_of_carcasses:
        #     if ware_house.remain_total_number_of_carcasses < free_sale_bar.real_number_of_carcasses or ware_house.remain_total_weight_of_carcasses < free_sale_bar.real_weight_of_carcasses:
        #         return Response({"result": "به علت تخصیص بار به مباشرین و صنف ها امکان حذف بار وجود ندارد!"},
        #                         status=status.HTTP_403_FORBIDDEN)
        free_sale_bar.trash = True
        free_sale_bar.save()
        kill_house_free_sale_product_warehousing(product)

        #
        # ware_house.allocated_total_number_of_carcasses -= free_sale_bar.real_number_of_carcasses
        # ware_house.allocated_total_weight_of_carcasses -= free_sale_bar.real_weight_of_carcasses
        # ware_house.save()

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


class PosKillHouseFreeSaleBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeSaleBarInformation.objects.all()
    serializer_class = KillHouseFreeSaleBarInformationSerializer
    permission_classes = [AllowAny]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFreeSaleBarInformationFilterSet
    filterset_fields = [
        'type_car',
        'pelak',
        'clearance_code',
        'kill_house__name',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__mobile',
        'buyer__fullname',
        'buyer__first_name',
        'buyer__last_name',
        'buyer__mobile',
        'buyer__unit_name',
        'buyer_name',
        'buyer_mobile',
        'province',
        'city',

    ]

    def create(self, request, *args, **kwargs):
        # user = SystemUserProfile.objects.get(user=request.user, trash=False)
        now = datetime.now().date()
        now_time = datetime.now().time()
        quota = request.data['quota']
        pos = POSMachine.objects.get(pos_id=request.data['pos-id'], trash=False)
        kill_house = pos.kill_house
        buyer = OutProvinceCarcassesBuyer.objects.get(key=request.data['buyer_key'])
        request.data.pop('buyer_key')
        product = RolesProducts.objects.get(key=request.data['product_key'])
        request.data.pop('product_key')
        request.data.pop('pos-id')
        date = datetime.now()
        # date = datetime.strptime(str(request.data['date']), '%Y-%m-%d').date()
        production_date = datetime.strptime(str(request.data['production_date']), '%Y-%m-%d').date()
        # date = datetime(year=date.year, month=date.month, day=date.day, hour=now_time.hour,
        #                 minute=now_time.minute,
        #                 second=now_time.second)
        production_date = datetime(year=production_date.year, month=production_date.month, day=production_date.day,
                                   hour=now_time.hour,
                                   minute=now_time.minute,
                                   second=now_time.second)
        # request.data.pop('date')
        request.data.pop('production_date')
        if OperationLimitation.objects.all().first().kill_house_free_sale_limitation == True:

            if now != date.date():
                return Response({"result": "به علت مغایرت تاریخ امکان فروش بار وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)
        carcass_distribution = RestrictionCarcassDistribution.objects.filter(trash=False,
                                                                             distribution_type='KillHouse',
                                                                             allow=True,
                                                                             out=True).first()
        if carcass_distribution and datetime.now().time() > carcass_distribution.time:
            return Response({"result": "لطفا در ساعات مجاز اقدام نمایید!"},
                            status=status.HTTP_403_FORBIDDEN)

        if request.data['sale_type'] == 'free':
            quota = request.data['quota']
            if quota == 'governmental':
                if not kill_house.free_sale_form_governmental_quota:
                    return Response({"result": "مجاز به فروش آزاد از انبار دولتی نمیباشید!"},
                                    status=status.HTTP_403_FORBIDDEN)

        if quota == 'governmental':
            if kill_house.total_input_warehouse_governmental_weight < (
                    kill_house.total_selling_warehouse_governmental_weight + request.data['weight_of_carcasses']):
                return Response({"result": "مجاز به فروش دولتی بیشتر از ورودی دولتی انبار نمیباشید!"},
                                status=status.HTTP_403_FORBIDDEN)
        else:
            if kill_house.total_input_warehouse_free_weight < (
                    kill_house.total_selling_warehouse_free_weight + request.data['weight_of_carcasses']):
                return Response({"result": "مجاز به فروش آزاد بیشتر از ورودی آزاد انبار نمیباشید!"},
                                status=status.HTTP_403_FORBIDDEN)

        if quota == 'governmental':
            free_sale_type = request.data['sale_type']
            if kill_house.governmental_selling_permission:
                if free_sale_type == 'free':
                    if not kill_house.free_sale_form_governmental_quota:
                        if kill_house.total_commitment_selling_in_province_governmental_weight > kill_house.total_selling_in_province_governmental_weight:
                            return Response({"result": "ابتدا تعهد داخل استان رو تکمیل کنید!"},
                                            status=status.HTTP_403_FORBIDDEN)
                else:
                    if kill_house.total_commitment_selling_in_province_governmental_weight > kill_house.total_selling_in_province_governmental_weight:
                        return Response({"result": "ابتدا تعهد داخل استان رو تکمیل کنید!"},
                                        status=status.HTTP_403_FORBIDDEN)
            else:
                return Response({"result": "مجاز به فروش دولتی نمیباشید!"}, status=status.HTTP_403_FORBIDDEN)
            if kill_house.total_commitment_selling_out_province_governmental_weight > 0:
                if kill_house.total_selling_out_province_governmental_weight + request.data[
                    'weight_of_carcasses'] > kill_house.total_commitment_selling_out_province_governmental_weight:
                    return Response({"result": "به دلیل بیشتر از وزن تعهد مجاز به فروش دولتی نمیباشید!"},
                                    status=status.HTTP_403_FORBIDDEN)

        else:
            if kill_house.free_selling_permission:
                if kill_house.total_commitment_selling_in_province_free_weight > kill_house.total_selling_in_province_free_weight:
                    return Response({"result": "ابتدا تعهد داخل استان رو تکمیل کنید!"},
                                    status=status.HTTP_403_FORBIDDEN)
            else:
                return Response({"result": "مجاز به فروش آزاد نمیباشید!"}, status=status.HTTP_403_FORBIDDEN)

            if kill_house.total_commitment_selling_out_province_free_weight > 0:
                if kill_house.total_selling_out_province_free_weight + request.data[
                    'weight_of_carcasses'] > kill_house.total_commitment_selling_out_province_free_weight:
                    return Response({"result": "به دلیل بیشتر از وزن تعهد مجاز به فروش دولتی نمیباشید!"},
                                    status=status.HTTP_403_FORBIDDEN)

        ware_house_remain_weight = product.total_remain_weight
        allocations_weight = StewardAllocation.objects.filter(trash=False, receiver_state__in=('pending', 'accepted'),
                                                              kill_house=kill_house, date__date=now).aggregate(
            total=Sum('real_weight_of_carcasses'))['total'] or 0
        free_sales_weight = \
            KillHouseFreeSaleBarInformation.objects.filter(trash=False, kill_house=kill_house,
                                                           date__date=now).aggregate(
                total=Sum('real_weight_of_carcasses'))['total'] or 0
        total_weight = ware_house_remain_weight + allocations_weight + free_sales_weight
        free_sales_weight += request.data['weight_of_carcasses']

        if KillHouseFreeSaleBarInformation.objects.filter(trash=False, clearance_code=request.data['clearance_code'],
                                                          quarantine_weight_of_carcasses__gt=0).exists():
            return Response({"result": "کد قرنطینه در سامانه ثبت شده است!"},
                            status=status.HTTP_403_FORBIDDEN)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_free_sale_bar_info = serializer.create(validated_data=request.data)
            kill_house_free_sale_bar_info.kill_house = kill_house
            if buyer is not None:
                kill_house_free_sale_bar_info.buyer = buyer
                kill_house_free_sale_bar_info.buyer_name = buyer.fullname
                kill_house_free_sale_bar_info.buyer_mobile = buyer.mobile
                kill_house_free_sale_bar_info.city = buyer.city
                kill_house_free_sale_bar_info.province = buyer.province

            kill_house_free_sale_bar_info.date = date
            kill_house_free_sale_bar_info.production_date = production_date
            kill_house_free_sale_bar_info.product = product
            kill_house_free_sale_bar_info.real_number_of_carcasses = kill_house_free_sale_bar_info.number_of_carcasses
            kill_house_free_sale_bar_info.real_weight_of_carcasses = kill_house_free_sale_bar_info.weight_of_carcasses

            wage = 0
            wage_type = WageType.objects.filter(en_name='carcasse-sell', trash=False).first()
            if wage_type.status == True:
                wage = wage_type.amount
            kill_house_free_sale_bar_info.wage = wage
            kill_house_free_sale_bar_info.total_wage_amount = wage * kill_house_free_sale_bar_info.real_weight_of_carcasses

            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':
                        kill_house_free_sale_bar_info.union_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_sale_bar_info.total_wage_amount)
                        kill_house_free_sale_bar_info.union_share_percent = percentage_wage_type.percent
                    elif percentage_wage_type.share_type.en_name == 'company':
                        kill_house_free_sale_bar_info.company_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_sale_bar_info.total_wage_amount)
                        kill_house_free_sale_bar_info.company_share_percent = percentage_wage_type.percent

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

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

                    else:
                        kill_house_free_sale_bar_info.other_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_sale_bar_info.total_wage_amount)
                        kill_house_free_sale_bar_info.other_share_percent = percentage_wage_type.percent
            kill_house_free_sale_bar_info.save()
            allow_register_code = AllowRegisterCodeForKillHouseFreeSaleBarInformation.objects.filter(trash=False,
                                                                                                     active=True).first()
            if allow_register_code:
                number = random.randint(10000, 99000)
                kill_house_free_sale_bar_info.registration_code = number
                kill_house_free_sale_bar_info.system_registration_code = True
                if int(allow_register_code.time) > 0:
                    kill_house_free_sale_bar_info.active_expire_date_time = True
                    kill_house_free_sale_bar_info.expire_date_time_registration_code = datetime.now() + timedelta(
                        minutes=int(allow_register_code.time))
                kill_house_free_sale_bar_info.save()
                send_sms_for_sale_bar(kill_house_free_sale_bar_info)
            get_gid_out_province(kill_house_free_sale_bar_info.id)
            kill_house_free_sale_product_warehousing(product)
            return Response(serializer.data, status=status.HTTP_201_CREATED)

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

            kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                kill_house=pos.kill_house,
                date__date__gte=date1,
                date__date__lte=date2,
                trash=False)
        else:

            kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                kill_house=pos.kill_house,
                trash=False)

        if 'search' in request.GET:
            kill_house_free_sale_bar_info_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=kill_house_free_sale_bar_info
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_free_sale_bar_info)
                            kill_house_free_sale_bar_info_list = ps.filter()
                    kill_house_free_sale_bar_info = [] if len(
                        kill_house_free_sale_bar_info_list) == 0 else kill_house_free_sale_bar_info_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(kill_house_free_sale_bar_info)
            if page is not None:
                serializer = self.serializer_class(page, many=True)
                return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(kill_house_free_sale_bar_info, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        free_sale_bar = KillHouseFreeSaleBarInformation.objects.get(key=request.data['key'])
        product = free_sale_bar.product
        kill_house = free_sale_bar.kill_house
        if KillHouseFreeSaleBarInformation.objects.filter(trash=False,
                                                          clearance_code=request.data.get('clearance_code'),
                                                          quarantine_weight_of_carcasses__gt=0).exists():
            return Response({"result": "کد قرنطینه در سامانه ثبت شده است!"},
                            status=status.HTTP_403_FORBIDDEN)
        now = datetime.now().date()

        if free_sale_bar.quota == 'governmental':
            if free_sale_bar.kill_house.total_input_warehouse_governmental_weight < (
                    (
                            free_sale_bar.kill_house.total_selling_warehouse_governmental_weight - free_sale_bar.weight_of_carcasses) +
                    request.data[
                        'weight_of_carcasses']):
                return Response({"result": "وزن وارد شده بیشتر از باقی مانده دولتی می باشد!"},
                                status=status.HTTP_403_FORBIDDEN)
        else:
            if free_sale_bar.kill_house.total_input_warehouse_free_weight < (
                    (free_sale_bar.kill_house.total_selling_warehouse_free_weight - free_sale_bar.weight_of_carcasses) +
                    request.data[
                        'weight_of_carcasses']):
                return Response({"result": "وزن وارد شده بیشتر از باقی مانده آزاد می باشد!"},
                                status=status.HTTP_403_FORBIDDEN)
        allow_register_code = AllowRegisterCodeForKillHouseFreeSaleBarInformation.objects.filter(trash=False,
                                                                                                 active=True).first()
        if allow_register_code:
            if 'register_code' in request.data.keys():
                code = request.data['register_code']
                if code != free_sale_bar.registration_code:
                    return Response({"result": "کد وارد شده صحیح نیست"}, status=status.HTTP_403_FORBIDDEN)
                free_sale_bar.logged_registration_code = code
                request.data.pop('register_code')
            free_sale_bar.save()
        serializer = self.serializer_class(free_sale_bar)

        serializer.update(instance=free_sale_bar, validated_data=request.data)
        kill_house_free_sale_product_warehousing(product)
        free_sale_bar.real_number_of_carcasses = free_sale_bar.number_of_carcasses
        free_sale_bar.real_weight_of_carcasses = free_sale_bar.weight_of_carcasses
        free_sale_bar.total_wage_amount = free_sale_bar.wage * free_sale_bar.real_weight_of_carcasses
        free_sale_bar.save()
        kill_house_free_sale_product_warehousing(product)

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

        get_gid_out_province(free_sale_bar.id)
        return Response(serializer.data, status=status.HTTP_200_OK)

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


class KillHouseFreeSaleBarInformationDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeSaleBarInformation.objects.all()
    serializer_class = KillHouseFreeSaleBarInformationSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFreeSaleBarInformationFilterSet
    filterset_fields = [
        'type_car',
        'pelak',
        'clearance_code',
        'kill_house__name',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__mobile',
        'buyer__fullname',
        'buyer__first_name',
        'buyer__last_name',
        'buyer__mobile',
        'buyer__unit_name',
        'buyer_name',
        'buyer_mobile',
        'province',
        'city',

    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET['role']
        kill_house_key = request.GET.get('kill_house_key')
        date1 = request.GET['date1']
        date2 = request.GET['date2']
        if date1:
            date1 = datetime.strptime(str(date1), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(date2), '%Y-%m-%d').date()
        if role in ['ProvinceOperator', 'Commerce', 'ProvinceSupervisor''GuildRoom', 'SuperAdmin',
                    'ImprovingLivestock', 'AdminX', 'Supporter']:
            if date1:
                ware_houses = KillHouseWareHouse.objects.filter(date__date__gte=date1,
                                                                date__date__lte=date2)
                if kill_house_key and kill_house_key != 'all':
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        date__date__gte=date1,
                        date__date__lte=date2,
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        kill_house__key=kill_house_key,
                        trash=False)
                else:
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        date__date__gte=date1,
                        date__date__lte=date2,
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        trash=False)
            else:
                ware_houses = KillHouseWareHouse.objects.filter(trash=False)

                if kill_house_key and kill_house_key != 'all':

                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        kill_house__key=kill_house_key,
                        trash=False)
                else:
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        trash=False)
            kill_houses = KillHouse.objects.filter(trash=False,
                                                   pk__in=kill_house_free_sale_bar_info.values_list('kill_house',
                                                                                                    flat=True))
            buyers = len(kill_house_free_sale_bar_info.values_list('buyer', flat=True).distinct())




        elif role in ['CityJahad', 'CityPoultry', 'CityOperator']:
            if date1:

                ware_houses = KillHouseWareHouse.objects.filter(kill_house__system_address__city=user.city,
                                                                date__date__gte=date1,
                                                                date__date__lte=date2)

                if kill_house_key and kill_house_key != 'all':

                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        kill_house__system_address__city=user.city,
                        date__date__gte=date1,
                        date__date__lte=date2,
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        kill_house__key=kill_house_key,
                        trash=False)
                else:
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        kill_house__system_address__city=user.city,
                        date__date__gte=date1,
                        date__date__lte=date2,
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        trash=False)
            else:
                ware_houses = KillHouseWareHouse.objects.filter(kill_house__system_address__city=user.city, trash=False)
                if kill_house_key and kill_house_key != 'all':

                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        kill_house__system_address__city=user.city,
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        kill_house__key=kill_house_key,
                        trash=False)
                else:
                    kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                        kill_house__system_address__city=user.city,
                        calculate_status=True,
                        temporary_trash=False,
                        temporary_deleted=False,
                        trash=False)
            kill_houses = KillHouse.objects.filter(trash=False,
                                                   pk__in=kill_house_free_sale_bar_info.values_list('kill_house',
                                                                                                    flat=True))
            buyers = len(kill_house_free_sale_bar_info.values_list('buyer', flat=True).distinct())




        else:
            kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            if date1:
                kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                    kill_house=kill_houses,
                    date__date__gte=date1,
                    date__date__lte=date2,
                    calculate_status=True,
                    temporary_trash=False,
                    temporary_deleted=False,
                    trash=False)
            else:
                kill_house_free_sale_bar_info = KillHouseFreeSaleBarInformation.objects.filter(
                    kill_house=kill_houses,
                    calculate_status=True,
                    temporary_trash=False,
                    temporary_deleted=False,
                    trash=False)

            buyers = len(kill_house_free_sale_bar_info.values_list('buyer', flat=True).distinct())

        if 'search' in request.GET:
            kill_house_free_sale_bar_info_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=kill_house_free_sale_bar_info
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_free_sale_bar_info)
                            kill_house_free_sale_bar_info_list = ps.filter()
                    kill_house_free_sale_bar_info = [] if len(
                        kill_house_free_sale_bar_info_list) == 0 else kill_house_free_sale_bar_info_list

        if role == 'KillHouse':
            result = {
                "number_of_allocations": len(kill_house_free_sale_bar_info),
                "number_of_buyers": buyers,
                "total_number_of_allocation_carcasses":
                    kill_house_free_sale_bar_info.aggregate(total=Sum('number_of_carcasses'))['total'] or 0,
                "total_weight_of_allocation_carcasses":
                    kill_house_free_sale_bar_info.aggregate(total=Sum('weight_of_carcasses'))['total'] or 0,

            }

        else:
            result = {
                "number_of_kill_houses": len(kill_houses),
                "number_of_allocations": len(kill_house_free_sale_bar_info),
                "number_of_buyers": buyers,
                "total_number_of_allocation_carcasses":
                    kill_house_free_sale_bar_info.aggregate(total=Sum('number_of_carcasses'))['total'] or 0,
                "total_weight_of_allocation_carcasses": int(
                    kill_house_free_sale_bar_info.aggregate(total=Sum('weight_of_carcasses'))['total'] or 0),
                "remain_total_number_of_carcasses":
                    ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                        'total'] or 0,
                "remain_total_weight_of_carcasses":
                    ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                        'total'] or 0,

            }

        return Response(result, status=status.HTTP_200_OK)


class KillHousebuyersDashboarForFreeSaleBarInformationdViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForKillHouseVetKillHouseSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        role = request.GET['role']
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if role == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        else:
            kill_house = KillHouse.objects.filter(key=request.GET['kill_house_key'], kill_house_operator__user=user,
                                                  trash=False).first()

        buyers = OutProvinceCarcassesBuyer.objects.filter(Kill_house=kill_house, trash=False)
        free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, kill_house=kill_house)

        total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[
                             'total'] or 0
        total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[
                           'total'] or 0
        result = {
            "buyers": len(buyers),
            "number_of_requests": len(free_sales),
            "total_quantity": total_quantity,
            "total_weight": total_weight,
        }
        return Response({"result": result}, status=status.HTTP_200_OK)


class KillHouseFreeBarInformationforWageTotalViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeBarInformation.objects.all()
    serializer_class = KillHouseFreeBarInformationForWageTotalSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFreeBarInformationFilterSet
    filterset_fields = [
        'kill_house__name',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__mobile',

    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        type = request.GET['type']
        if request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        else:
            kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'])

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

            if request.GET['role'] == 'ProvinceOperator':
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      date__date__gte=date1,
                                                                                      date__date__lte=date2,
                                                                                      union_share__gt=0,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')
            elif request.GET['role'] == 'Company':
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      date__date__gte=date1,
                                                                                      date__date__lte=date2,
                                                                                      company_share__gt=0,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')
            elif request.GET['role'] == 'Guilds':
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      date__date__gte=date1,
                                                                                      date__date__lte=date2,
                                                                                      guilds_share__gt=0,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')
            else:

                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      date__date__gte=date1,
                                                                                      date__date__lte=date2,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')

        else:
            if request.GET['role'] == 'ProvinceOperator':
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      union_share__gt=0,
                                                                                      trash=False).order_by('id')
            elif request.GET['role'] == 'Company':
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      company_share__gt=0,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')
            elif request.GET['role'] == 'Guilds':
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      guilds_share__gt=0,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')
            else:

                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                                      buy_type=type,
                                                                                      archive_wage=False,
                                                                                      trash=False).order_by('id')

        if 'search' in request.GET:
            kill_house_free_bar_info_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=kill_house_free_bar_info
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_free_bar_info)
                            kill_house_free_bar_info_list = ps.filter()
                    kill_house_free_bar_info = [] if len(
                        kill_house_free_bar_info_list) == 0 else kill_house_free_bar_info_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(kill_house_free_bar_info)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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


class KillHouseFreeBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeBarInformation.objects.all()
    serializer_class = KillHouseFreeBarInformationSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFreeBarInformationFilterSet
    filterset_fields = [
        'kill_house__name',
        'poultry_name',
        'poultry_mobile',
        'province',
        'bar_code',
        'city',
        'driver_name',
        'driver_mobile',
        'bar_clearance_code',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',

    ]

    def create(self, request, *args, **kwargs):
        killer = None
        now_time = datetime.now().time()
        dispenser = request.data.pop('dispenser',None)
        representative = request.data.pop('representative',None)
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        free_commitment_percent = kill_house.out_province_free_buying_commitment_percent
        if 'bar_clearance_code' in request.data.keys():
            if KillHouseFreeBarInformation.objects.filter(trash=False, bar_clearance_code=request.data[
                'bar_clearance_code']).exists():
                return Response({'result': 'کد قرنطینه قبلا در سامانه ثبت شده است!'}, status=status.HTTP_403_FORBIDDEN)
        if 'product_key' not in request.data.keys():
            return Response({'result': 'لطفا محصول را انتخاب کنید!'}, status=status.HTTP_403_FORBIDDEN)
        product = RolesProducts.objects.get(key=request.data['product_key'])
        request.data.pop('product_key')
        if 'killer_key' in request.data.keys() and request.data['killer_key'] != None:
            killer = KillHouse.objects.get(key=request.data['killer_key'])
        request.data.pop('killer_key')

        try:
            image = request.data['bar_image']
            request.data.pop('bar_image')
        except:
            image = None
        date = datetime.strptime(str(request.data['date']), '%Y-%m-%d').date()
        date = datetime(year=date.year, month=date.month, day=date.day, hour=now_time.hour,
                        minute=now_time.minute,
                        second=now_time.second)
        request.data.pop('date')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            kill_house_free_bar_info = serializer.create(validated_data=request.data)
            if image != None:
                kill_house_free_bar_info.bar_image = send_image_to_server(image)
            kill_house_free_bar_info.kill_house = kill_house
            kill_house_free_bar_info.date = date
            if kill_house_free_bar_info.buy_type == 'carcass':
                kill_house_free_bar_info.warehouse_commitment_weight = int(
                    (free_commitment_percent / 100) * int(kill_house_free_bar_info.weight_of_carcasses))

                kill_house_free_bar_info.ware_house = True
            if killer:
                if killer.killer and killer.type == 'public':
                    kill_house_free_bar_info.kill_house = killer
                    kill_house_free_bar_info.public_killer = kill_house
                    kill_house_free_bar_info.input_warehouse = killer
                    product = RolesProducts.objects.get(kill_house=killer, trash=False)
                else:
                    kill_house_free_bar_info.exclusive_killer = killer
                    kill_house_free_bar_info.input_warehouse = killer
                    product = RolesProducts.objects.get(kill_house=killer, trash=False)

            else:
                kill_house_free_bar_info.input_warehouse = kill_house
            kill_house_free_bar_info.product = product
            kill_house_free_bar_info.dispenser = dispenser if dispenser else None
            kill_house_free_bar_info.representative = representative if representative else None
            kill_house_free_bar_info.bar_code = generate_unique_bar_code()
            kill_house_free_bar_info.save()
            wage = 0
            type = 'live-buy' if kill_house_free_bar_info.buy_type == 'live' else 'carcasse-buy'
            wage_type = WageType.objects.filter(en_name=type, trash=False).first()
            if wage_type.status == True:
                wage = wage_type.amount
            kill_house_free_bar_info.wage = wage
            kill_house_free_bar_info.total_wage_amount = wage * int(
                kill_house_free_bar_info.live_weight) if kill_house_free_bar_info.buy_type == 'live' else wage * int(
                kill_house_free_bar_info.weight_of_carcasses)
            kill_house_free_bar_info.register_date = datetime.now()
            kill_house_free_bar_info.save()
            kill_house_free_buying_product_warehousing(product)

            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':
                        kill_house_free_bar_info.union_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_bar_info.total_wage_amount)
                        kill_house_free_bar_info.union_share_percent = percentage_wage_type.percent
                        kill_house_free_bar_info.save()
                    elif percentage_wage_type.share_type.en_name == 'company':
                        kill_house_free_bar_info.company_share = int(
                            (percentage_wage_type.percent / 100) * kill_house_free_bar_info.total_wage_amount)
                        kill_house_free_bar_info.company_share_percent = percentage_wage_type.percent
                        kill_house_free_bar_info.save()

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

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

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

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        type = request.GET.get('type')
        date_type = request.GET.get('date_type')
        bar_state = request.GET.get('bar_state')
        kill_house_free_bar_info_list = []
        role = request.GET.get('role')
        kill_houses = None
        order_by_type = '-date'

        if role in ['KillHouse', 'KillHouseVet']:
            if role == 'KillHouse':
                kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
            else:
                kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                      flat=True)
                kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
        if 'date1' in request.GET:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if date_type:
                if date_type == 'buy':

                    filters = {
                        'register_date__date__gte': date1,
                        'register_date__date__lte': date2,
                        'trash': False,
                        'temporary_trash': False,
                        'temporary_deleted': False,
                        'calculate_status': True
                    }
                else:
                    order_by_type = '-date'
                    filters = {
                        'date__date__gte': date1,
                        'date__date__lte': date2,
                        'trash': False,
                        'temporary_trash': False,
                        'temporary_deleted': False,
                        'calculate_status': True
                    }
            else:
                filters = {
                    'register_date__date__gte': date1,
                    'register_date__date__lte': date2,
                    'trash': False,
                    'temporary_trash': False,
                    'temporary_deleted': False,
                    'calculate_status': True
                }
        else:
            filters = {
                'trash': False,
                'temporary_trash': False,
                'temporary_deleted': False,
                'calculate_status': True
            }

        if type:
            filters['buy_type'] = type
            if type == 'live':
                if bar_state:
                    if bar_state == 'entered':
                        filters['weight_of_carcasses__gt'] = 0
                    else:
                        filters['weight_of_carcasses'] = 0
        if kill_houses is not None:
            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                Q(kill_house__in=kill_houses) | Q(exclusive_killer__in=kill_houses) | Q(public_killer__in=kill_houses),
                **filters).order_by(order_by_type)
        else:

            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type)

        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=kill_house_free_bar_info
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_free_bar_info)
                            kill_house_free_bar_info_list = ps.filter()
                    kill_house_free_bar_info = [] if len(
                        kill_house_free_bar_info_list) == 0 else kill_house_free_bar_info_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(kill_house_free_bar_info)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def update(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        free_bar = KillHouseFreeBarInformation.objects.get(key=request.data['key'])
        # product = free_bar.product

        if 'live_weight' in request.data.keys():
            if int(request.data['live_weight']) < free_bar.weight_of_carcasses:
                return Response(
                    {"result": "مقدار وارد شده کمتر از وزن لاشه است! "},
                    status=status.HTTP_403_FORBIDDEN)

        if 'bar_clearance_code' in request.data.keys():
            existing_bar = KillHouseFreeBarInformation.objects.filter(trash=False, bar_clearance_code=request.data[
                'bar_clearance_code']).exclude(id=free_bar.id).first()
            if existing_bar:
                if existing_bar.register_type == 'automatic':
                    existing_bar.trash = True
                    existing_bar.save()
                else:
                    return Response({'result': 'کد قرنطینه قبلا در سامانه ثبت شده است!'},
                                    status=status.HTTP_403_FORBIDDEN)
        if 'number_of_carcasses' in request.data.keys():
            now = datetime.now().date()
            if OperationLimitation.objects.all().first().kill_house_input_bar_limitation == True and \
                    free_bar.register_type != 'automatic':
                if now != free_bar.date.date():
                    return Response({"result": "به علت وجود مفایرت در تاریخ ثبت امکان ویرایش وجود ندارد! "},
                                    status=status.HTTP_403_FORBIDDEN)

            # ware_house = KillHouseWareHouse.objects.filter(kill_house=free_bar.kill_house,
            #                                                date__date=free_bar.date.date(), trash=False).first()
            # allocation = StewardAllocation.objects.filter(ware_house=ware_house, trash=False)
            #
            # if len(allocation) > 0:
            #     if OperationLimitation.objects.all().first().kill_house_input_bar_limitation == True:
            #         return Response(
            #             {"result": "به علت وجود تخصیص به مباشر یا صنف برای امروز امکان ویرایش وجود ندارد! "},
            #             status=status.HTTP_403_FORBIDDEN)
        if 'return_entered_bar' in request.data.keys():
            free_bar.weight_of_carcasses = 0
            free_bar.number_of_carcasses = 0
            free_bar.entered_message = None
            free_bar.ware_house = False
        if 'bar_image' in request.data.keys():
            if request.data['bar_image'] != " ":
                free_bar.bar_image = send_image_to_server(request.data['bar_image'])
                free_bar.save()
            request.data.pop('bar_image')
        if 'kill_house_vet_state' in request.data.keys():
            free_bar.date_of_accept_reject = datetime.now()
            free_bar.acceptor_rejector = user.fullname
        if 'killer_key' in request.data.keys() and request.data['killer_key'] != None and request.data[
            'killer_key'] != '':
            exclusive_killer = KillHouse.objects.filter(trash=False, key=request.data['killer_key']).first()
            if exclusive_killer.killer and exclusive_killer.type == 'public':
                if not free_bar.public_killer:
                    free_bar.public_killer = free_bar.kill_house
                free_bar.kill_house = exclusive_killer
                free_bar.input_warehouse = exclusive_killer
                product = RolesProducts.objects.filter(kill_house=exclusive_killer, trash=False, name='مرغ گرم').first()
                free_bar.product = product
                if free_bar.exclusive_killer:
                    free_bar.exclusive_killer = None
            else:
                free_bar.exclusive_killer = exclusive_killer
                free_bar.input_warehouse = exclusive_killer
                product = RolesProducts.objects.filter(kill_house=exclusive_killer, trash=False, name='مرغ گرم').first()
                free_bar.product = product
                if free_bar.public_killer:
                    free_bar.kill_house = free_bar.public_killer
                    free_bar.public_killer = None
            request.data.pop('killer_key')
        serializer = self.serializer_class(free_bar)
        serializer.update(instance=free_bar, validated_data=request.data)
        free_commitment_percent = free_bar.kill_house.out_province_free_buying_commitment_percent
        free_bar.total_wage_amount = free_bar.wage * int(
            free_bar.live_weight) if free_bar.buy_type == 'live' else free_bar.wage * int(free_bar.weight_of_carcasses)
        free_bar.warehouse_commitment_weight = int((free_commitment_percent / 100) * int(free_bar.weight_of_carcasses))
        if free_bar.exclusive_killer:
            product = RolesProducts.objects.get(kill_house=free_bar.exclusive_killer, trash=False)
            free_bar.product = product
        free_bar.save()
        union_percent = free_bar.union_share_percent / 100 if free_bar.union_share_percent > 0 else 0
        company_percent = free_bar.company_share_percent / 100 if free_bar.company_share_percent > 0 else 0
        guilds_percent = free_bar.guilds_share_percent / 100 if free_bar.guilds_share_percent > 0 else 0
        city_share_percent = free_bar.city_share_percent / 100 if free_bar.city_share_percent > 0 else 0
        wallet_share_percent = free_bar.wallet_share_percent / 100 if free_bar.wallet_share_percent > 0 else 0
        other_share_percent = free_bar.other_share_percent / 100 if free_bar.other_share_percent > 0 else 0
        free_bar.union_share = int(union_percent * free_bar.total_wage_amount)
        free_bar.company_share = int(company_percent * free_bar.total_wage_amount)
        free_bar.guilds_share = int(guilds_percent * free_bar.total_wage_amount)
        free_bar.city_share = int(city_share_percent * free_bar.total_wage_amount)
        free_bar.wallet_share = int(wallet_share_percent * free_bar.total_wage_amount)
        free_bar.other_share = int(other_share_percent * free_bar.total_wage_amount)
        free_bar.save()
        kill_house_free_buying_product_warehousing(free_bar.product)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        free_bar = KillHouseFreeBarInformation.objects.get(trash=False, key=request.GET['key'])
        free_bar.trash = True
        free_bar.save()
        product = free_bar.product
        kill_house_free_buying_product_warehousing(product)

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


class ParentCompanyKillHouseFreeBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeBarInformation.objects.all()
    serializer_class = KillHouseFreeBarInformationSerializer
    permission_classes = [AllowAny]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFreeBarInformationFilterSet
    filterset_fields = [
        'kill_house__name',
        'poultry_name',
        'poultry_mobile',
        'province',
        'city',
        'driver_name',
        'driver_mobile',
        'bar_clearance_code',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',

    ]

    def list(self, request, *args, **kwargs):
        type = request.GET.get('type')
        date_type = request.GET.get('date_type')
        bar_state = request.GET.get('bar_state')
        kill_house_free_bar_info_list = []
        role = request.GET.get('role')
        kill_houses = None
        order_by_type = '-create_date'

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

                    filters = {
                        'create_date__date__gte': date1,
                        'create_date__date__lte': date2,
                        'trash': False,
                    }
                else:
                    order_by_type = '-date'
                    filters = {
                        'date__date__gte': date1,
                        'date__date__lte': date2,
                        'trash': False,
                    }
            else:
                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
        else:
            filters = {
                'trash': False
            }

        if kill_houses is not None:
            filters['kill_house__in'] = kill_houses

        if type:
            filters['buy_type'] = type
            if type == 'live':
                if bar_state:
                    if bar_state == 'entered':
                        filters['weight_of_carcasses__gt'] = 0
                    else:
                        filters['weight_of_carcasses'] = 0

        kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type)

        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=kill_house_free_bar_info
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_free_bar_info)
                            kill_house_free_bar_info_list = ps.filter()
                    kill_house_free_bar_info = [] if len(
                        kill_house_free_bar_info_list) == 0 else kill_house_free_bar_info_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(kill_house_free_bar_info)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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


class KillHouseRequestForBarManagementViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForBarManagementSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'bar_code',
        'traffic_code',
        'clearance_code'
    ]

    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.now().date()

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

                    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.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                        if 'search' in request.GET:
                            if 'deleted_requests' in request.GET:

                                kill_house_requests_list = 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, temporary_trash=False, temporary_deleted=False,
                                    message__isnull=False
                                ).select_related('kill_request')
                            else:
                                kill_house_requests_list = 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,
                                    non_receipt=False,
                                    trash=False
                                ).select_related('kill_request')

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

                                        )
                                        ).filter():
                                            ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                            kill_house_requests = ps.filter()
                                else:
                                    kill_house_requests = kill_house_requests_list
                        else:

                            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')
                            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,
                                    non_receipt=False,
                                    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:
                            kill_house_requests = []
                            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                            if 'search' in request.GET:
                                if 'deleted_requests' in request.GET:
                                    aggregate_permission = VetFarmAggregatePermission.objects.filter(
                                        trash=False).first()
                                    if aggregate_permission and aggregate_permission.allow == True:
                                        kill_house_requests_list = 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')
                                    else:

                                        kill_house_requests_list = 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')
                                else:
                                    aggregate_permission = VetFarmAggregatePermission.objects.filter(
                                        trash=False).first()
                                    if aggregate_permission and aggregate_permission.allow == True:
                                        kill_house_requests_list = KillHouseRequest.objects.filter(
                                            kill_request__recive_date__date__gte=date1,
                                            kill_request__recive_date__date__lte=date2,
                                            province_request__poultry_request__poultry__in=poultries,
                                            non_receipt=False,
                                            trash=False
                                        ).select_related('kill_request').order_by(
                                            'province_request__poultry_request__poultry', 'killhouse_user')
                                    else:
                                        kill_house_requests_list = KillHouseRequest.objects.filter(
                                            kill_request__recive_date__date__gte=date1,
                                            kill_request__recive_date__date__lte=date2,
                                            province_request__poultry_request__poultry__in=poultries,
                                            non_receipt=False,
                                            trash=False
                                        ).select_related('kill_request')

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

                                            )
                                            ).filter():
                                                ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                                kill_house_requests = ps.filter()
                                    else:
                                        kill_house_requests = kill_house_requests_list
                            else:

                                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')
                                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,
                                        non_receipt=False,
                                        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.strptime(request.GET['date'], '%Y-%m-%d')
                    else:
                        date = 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:
                    kill_house_requests = []
                    date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                    date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                    if 'search' in request.GET:
                        if 'deleted_requests' in request.GET:

                            kill_house_requests_list = 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')
                        else:
                            kill_house_requests_list = 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,
                                non_receipt=False,
                                trash=False
                            ).select_related('kill_request')

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

                                    )
                                    ).filter():
                                        ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                        kill_house_requests = ps.filter()
                            else:
                                kill_house_requests = kill_house_requests_list
                    else:

                        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')
                        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,
                                non_receipt=False,
                                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.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                    queryset_list = PoultryRequest.objects.filter(poultry__city_operator=city_operator.unit_name,
                                                                  trash=False, out=False, final_state='pending',
                                                                  ).order_by('send_date')
                    queryset = [
                        poultry_req for poultry_req in queryset_list
                        if date1 <= poultry_req.send_date.date() <= date2
                    ]

            elif request.GET['role'] in ['CityCommerce', 'CityVet', 'CityJahad', 'CityPoultry']:
                if 'check' in request.GET:
                    kill_house_requests = []
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                        if 'search' in request.GET:

                            if 'deleted_requests' in request.GET:

                                kill_house_requests_list = 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')
                            else:
                                kill_house_requests_list = 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,
                                    non_receipt=False,
                                    trash=False
                                ).select_related('kill_request')

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

                                        )
                                        ).filter():
                                            ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                            kill_house_requests = ps.filter()
                                else:
                                    kill_house_requests = kill_house_requests_list
                        else:

                            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')
                            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,
                                    non_receipt=False,
                                    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'] == 'LiveStockSupport':
                if 'check' in request.GET:
                    kill_house_requests = []
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                        if 'search' in request.GET:

                            if 'deleted_requests' in request.GET:

                                kill_house_requests_list = KillHouseRequest.objects.filter(
                                    kill_request__recive_date__date__gte=date1,
                                    kill_request__recive_date__date__lte=date2,
                                    province_request__poultry_request__freezing=True,
                                    trash=True,
                                    message__isnull=False, temporary_trash=False, temporary_deleted=False
                                ).select_related('kill_request')
                            else:
                                kill_house_requests_list = KillHouseRequest.objects.filter(
                                    kill_request__recive_date__date__gte=date1,
                                    kill_request__recive_date__date__lte=date2,
                                    province_request__poultry_request__freezing=True,
                                    non_receipt=False,
                                    trash=False
                                ).select_related('kill_request')

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

                                        )
                                        ).filter():
                                            ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                            kill_house_requests = ps.filter()
                                else:
                                    kill_house_requests = kill_house_requests_list
                        else:

                            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__freezing=True,
                                    trash=True,
                                    message__isnull=False, temporary_trash=False, temporary_deleted=False
                                ).select_related('kill_request')
                            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__freezing=True,
                                    non_receipt=False,
                                    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'] == '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.strptime(request.GET['date'], '%Y-%m-%d')
                    else:
                        date = 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', 'ProvinceSupervisor', 'SuperAdmin', 'AdminX',
                                         'ImprovingLivestock', '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.strptime(request.GET['date'], '%Y-%m-%d')
                    else:
                        date = datetime.now()
                    queryset = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             send_date__year=date.year, send_date__month=date.month,
                                                             send_date__day=date.day,
                                                             trash=False, out=True).order_by('-send_date')
                elif 'check' in request.GET:
                    kill_house_requests = []
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                        if 'search' in request.GET:

                            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, temporary_trash=False, temporary_deleted=False
                                    # message__isnull=False
                                ).select_related('kill_request')
                            else:
                                if 'without_quarantine_code_state' in request.GET and request.GET[
                                    'without_quarantine_code_state'] == 'true':
                                    kill_house_requests = KillHouseRequest.objects.filter(
                                        clearance_code__isnull=False,
                                        kill_request__recive_date__date__gte=date1,
                                        kill_request__recive_date__date__lte=date2,
                                        quarantine_quantity__isnull=True,
                                        quarantine_code_state__isnull=True,
                                        non_receipt=False,
                                        province_request__poultry_request__poultry__address__province=user.province,
                                        trash=False
                                    ).select_related('kill_request')
                                else:
                                    kill_house_requests = KillHouseRequest.objects.filter(
                                        # (Q(trash=False) | Q(trash=True, clearance_code__isnull=False,
                                        #                     temporary_trash=False, temporary_deleted=False)),
                                        kill_request__recive_date__date__gte=date1,
                                        kill_request__recive_date__date__lte=date2,
                                        non_receipt=False,
                                        province_request__poultry_request__poultry__address__province=user.province,

                                        trash=False
                                    ).select_related('kill_request')
                            value = request.GET.get('value')
                            search = request.GET.get('search')
                            if value and search == 'filter':
                                if value != 'undefined' and value.strip():
                                    kill_house_requests = kill_house_requests.filter(
                                        build_query(DashboardEnterLoadInformationFilterSet, value)
                                    )
                        else:

                            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
                                ).select_related('kill_request')
                            else:
                                if 'without_quarantine_code_state' in request.GET and request.GET[
                                    'without_quarantine_code_state'] == 'true':
                                    kill_house_requests = KillHouseRequest.objects.filter(
                                        clearance_code__isnull=False,
                                        kill_request__recive_date__date__gte=date1,
                                        kill_request__recive_date__date__lte=date2,
                                        quarantine_quantity__isnull=True,
                                        quarantine_code_state__isnull=True,
                                        non_receipt=False,
                                        province_request__poultry_request__poultry__address__province=user.province,
                                        trash=False
                                    ).select_related('kill_request')
                                else:
                                    kill_house_requests = KillHouseRequest.objects.filter(
                                        # (Q(trash=False) | Q(trash=True, clearance_code__isnull=False)),
                                        kill_request__recive_date__date__gte=date1,
                                        kill_request__recive_date__date__lte=date2,
                                        non_receipt=False,
                                        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.now().date()
                    date1 = datetime.strptime(str(request.GET['date1']),
                                              '%Y-%m-%d').date() if 'date1' in request.GET else now
                    date2 = datetime.strptime(str(request.GET['date2']),
                                              '%Y-%m-%d').date() if 'date2' in request.GET else now
                    queryset_lists = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                                   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
                    ]

                    # 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.strptime(request.GET['date'], '%Y-%m-%d')
                    else:
                        date = 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:
                    kill_house_requests = []
                    if 'date1' in request.GET and 'date2' in request.GET:
                        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                        if 'search' in request.GET:

                            if 'deleted_requests' in request.GET:

                                kill_house_requests_list = KillHouseRequest.objects.filter(
                                    (Q(killhouse_user__in=kill_house) | Q(
                                        kill_request__slaughter_house__in=kill_house) | Q(killer__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, temporary_trash=False, temporary_deleted=False
                                    # message__isnull=False
                                ).select_related('kill_request')
                            else:
                                kill_house_requests_list = KillHouseRequest.objects.filter(
                                    (Q(killhouse_user__in=kill_house) | Q(
                                        kill_request__slaughter_house__in=kill_house) | Q(killer__in=kill_house)),
                                    # (Q(trash=False) | Q(trash=True, clearance_code__isnull=False, temporary_trash=False,
                                    #                     temporary_deleted=False)),
                                    kill_request__recive_date__date__gte=date1,
                                    kill_request__recive_date__date__lte=date2,
                                    non_receipt=False,
                                    province_request__poultry_request__poultry__address__province=user.province,
                                    trash=False
                                ).select_related('kill_request')

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

                                        )
                                        ).filter():
                                            ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                            kill_house_requests = ps.filter()
                                else:
                                    kill_house_requests = kill_house_requests_list
                        else:

                            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) | Q(killer__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, temporary_trash=False, temporary_deleted=False
                                    # message__isnull=False
                                ).select_related('kill_request')
                            else:
                                kill_house_requests = KillHouseRequest.objects.filter(
                                    (Q(killhouse_user__in=kill_house) | Q(
                                        kill_request__slaughter_house__in=kill_house) | Q(killer__in=kill_house)),
                                    # (Q(trash=False) | Q(trash=True, clearance_code__isnull=False, temporary_trash=False,
                                    #                     temporary_deleted=False)),

                                    kill_request__recive_date__date__gte=date1,
                                    kill_request__recive_date__date__lte=date2,
                                    non_receipt=False,
                                    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)
            else:
                if 'date' in request.GET:
                    date = datetime.strptime(request.GET['date'], '%Y-%m-%d')
                else:
                    date = 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)


class ParentCompanyKillHouseRequestForBarManagementViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForBarManagementSerializer
    pagination_class = CustomPagination
    permission_classes = [AllowAny]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'bar_code',
        'traffic_code',
        'clearance_code'
    ]

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

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

                if 'deleted_requests' in request.GET:

                    kill_house_requests_list = KillHouseRequest.objects.filter(
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        trash=True, temporary_trash=False, temporary_deleted=False
                    ).select_related('kill_request')
                else:
                    if 'without_quarantine_code_state' in request.GET and request.GET[
                        'without_quarantine_code_state'] == 'true':
                        kill_house_requests_list = KillHouseRequest.objects.filter(
                            clearance_code__isnull=False,
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            quarantine_quantity__isnull=True,
                            quarantine_code_state__isnull=True,

                        ).select_related('kill_request')
                    else:
                        kill_house_requests_list = KillHouseRequest.objects.filter(
                            (Q(trash=False) | Q(trash=True, clearance_code__isnull=False, temporary_trash=False,
                                                temporary_deleted=False)),
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                        ).select_related('kill_request')

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

                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=kill_house_requests_list)
                                kill_house_requests = ps.filter()
                    else:
                        kill_house_requests = kill_house_requests_list
            else:

                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,
                        trash=True,
                    ).select_related('kill_request')
                else:
                    if 'without_quarantine_code_state' in request.GET and request.GET[
                        'without_quarantine_code_state'] == 'true':
                        kill_house_requests = KillHouseRequest.objects.filter(
                            clearance_code__isnull=False,
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                            quarantine_quantity__isnull=True,
                            quarantine_code_state__isnull=True,
                        ).select_related('kill_request')
                    else:
                        kill_house_requests = KillHouseRequest.objects.filter(
                            (Q(trash=False) | Q(trash=True, clearance_code__isnull=False)),
                            kill_request__recive_date__date__gte=date1,
                            kill_request__recive_date__date__lte=date2,
                        ).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)


class KillHouseRequestForBarManagementWageViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForBarManagementSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

    def list(self, request, *args, **kwargs):
        if request.GET['role'] == 'KillHouse':
            user = SystemUserProfile.objects.get(user=request.user)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            if 'date1' in request.GET and 'date2' in request.GET:
                date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    trash=False)

            else:
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    trash=False)

        else:

            kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'], trash=False)
            if 'date1' in request.GET and 'date2' in request.GET:
                date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                if request.GET['role'] == 'ProvinceOperator':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        province_kill_request__union_share__gt=0,
                        trash=False)
                elif request.GET['role'] == 'Company':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        province_kill_request__company_share__gt=0,
                        trash=False)

                elif request.GET['role'] == 'Guilds':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        province_kill_request__guilds_share__gt=0,
                        trash=False)
                else:
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        kill_request__recive_date__date__gte=date1,
                        kill_request__recive_date__date__lte=date2,
                        trash=False)

            else:
                if request.GET['role'] == 'ProvinceOperator':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        province_kill_request__union_share__gt=0,
                        trash=False)
                elif request.GET['role'] == 'Company':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        province_kill_request__company_share__gt=0,
                        trash=False)

                elif request.GET['role'] == 'Guilds':
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        province_kill_request__guilds_share__gt=0,
                        trash=False)
                else:
                    kill_house_requests = KillHouseRequest.objects.filter(
                        Q(killhouse_user=kill_house) | Q(killer=kill_house),
                        trash=False)

        if 'search' in request.GET:
            kill_house_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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_request_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_request_list) == 0 else kill_house_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(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)


class KillHouseRequestForAggregateLoadsViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForBarManagementSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

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

        elif request.GET['role'] == 'KillHouseVet':
            kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
            for kill_house_vet in kill_house_vets:
                kill_house.append(kill_house_vet.kill_house)

        else:
            kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False)

        if request.GET['role'] in ['CityOperator', 'CityJahad', 'CityPoultry']:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                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,
                    assignment_state_archive='pending',
                    non_receipt=False,
                    trash=False, province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

                ).order_by('-kill_request__recive_date')
            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,
                    assignment_state_archive='pending',
                    non_receipt=False,
                    trash=False, province_request__poultry_request__poultry__address__city=user.city

                ).order_by('-kill_request__recive_date')

        else:

            kill_house_requests = KillHouseRequest.objects.filter(
                (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                    killer__in=kill_house)),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                assignment_state_archive='pending',
                non_receipt=False,
                trash=False,

            ).order_by('-kill_request__recive_date')

        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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_requests_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_requests_list) == 0 else kill_house_requests_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(kill_house_requests)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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


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

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        province_operator = ProvinceOperator.objects.filter(
            user=SystemUserProfile.objects.get(role__name='ProvinceOperator', province=user.province),
            trash=False).select_related(
            'user').first()
        if request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user, trash=False)
            poultry_requests = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             poultry__city_operator=city_operator.unit_name,
                                                             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').annotate(
                total_quantity=Sum('quantity'),
                total_weight=Sum(F('quantity') * F('Index_weight')),
                total_remain_quantity=Sum('remain_quantity'),
                total_remain_weight=Sum(F('remain_quantity') * F('Index_weight')),

            )
        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            poultry_requests = PoultryRequest.objects.filter(poultry__address__province=user.province,
                                                             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').annotate(
                total_quantity=Sum('quantity'),
                total_weight=Sum(F('quantity') * F('Index_weight')),
                total_remain_quantity=Sum('remain_quantity'),
                total_remain_weight=Sum(F('remain_quantity') * F('Index_weight')),

            )
        else:
            poultry_requests = 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').annotate(
                total_quantity=Sum('quantity'),
                total_weight=Sum(F('quantity') * F('Index_weight')),
                total_remain_quantity=Sum('remain_quantity'),
                total_remain_weight=Sum(F('remain_quantity') * F('Index_weight')),

            )
        poultry_request_total_quantity = poultry_requests.aggregate(total=Sum('total_quantity'))['total']
        poultry_request_total_weight = poultry_requests.aggregate(total=Sum('total_weight'))['total']
        poultry_request_total_remain_quantity = poultry_requests.aggregate(total=Sum('total_remain_quantity'))['total']
        poultry_request_remain_weight = poultry_requests.aggregate(total=Sum('total_remain_weight'))['total']

        province_kill_requests = ProvinceKillRequest.objects.filter(
            province_request__poultry_request__in=poultry_requests, trash=False,
            state__in=('pending', 'accepted')).annotate(
            total_quantity=Sum('main_quantity'),
            total_weight=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight')),
        )

        province_kill_requests_total_quantity = province_kill_requests.aggregate(total=Sum('total_quantity'))['total']
        province_kill_requests_total_weight = province_kill_requests.aggregate(total=Sum('total_weight'))['total']

        province_kill_requests_with_left_over = ProvinceKillRequest.objects.filter(
            province_request__poultry_request__in=poultry_requests, trash=False,
            state__in=('pending', 'accepted'), quantity__gt=0)
        province_kill_requests_serializer = ProvinceKillRequestForKillingInformationDiscrepancyReportSerializer(
            province_kill_requests_with_left_over, many=True)
        # if 'role' in request.GET:
        # if request.GET['role'] == 'ProvinceSupervisor':
        #     last_date = datetime(2024, 4, 14, 7, 33).date()
        #     if date2 > last_date and date1 <= last_date:
        #         kill_house_request_without_clearance_code = KillHouseRequest.objects.filter(
        #             province_kill_request__in=province_kill_requests, kill_request__recive_date__date__gte=date1,
        #             kill_request__recive_date__date__lte=last_date, clearance_code__isnull=True, trash=False)
        #
        #         kill_house_request_diffrent_quarantine_quantity = KillHouseRequest.objects.filter(
        #             Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')),
        #             province_kill_request__in=province_kill_requests, clearance_code__isnull=False,
        #             quarantine_quantity__isnull=False, trash=False)
        #         kill_house_request_without_vet_check = KillHouseRequest.objects.filter(
        #             province_kill_request__in=province_kill_requests, kill_request__recive_date__date__gte=date1,
        #             kill_request__recive_date__date__lte=last_date, vet_state='pending', trash=False)
        #         kill_house_request_without_bar_info = KillHouseRequest.objects.filter(
        #             province_kill_request__in=province_kill_requests, kill_request__recive_date__date__gte=date1,
        #             kill_request__recive_date__date__lte=last_date, vet_state='accepted',
        #             assignment_state_archive='pending',
        #             trash=False)
        #         kill_house_request_diffrent_bar_info = KillHouseRequest.objects.filter(
        #             Q(quantity__gt=F('vet_accepted_real_quantity')) | Q(
        #                 quantity__lt=F('vet_accepted_real_quantity')) | Q(
        #                 quantity__gt=F('accepted_real_quantity')) | Q(quantity__lt=F('accepted_real_quantity')) | Q(
        #                 vet_accepted_real_quantity__gt=F('accepted_real_quantity')) | Q(
        #                 vet_accepted_real_quantity__lt=F('accepted_real_quantity')),
        #             # kill_request__recive_date__date__gte=date1,
        #             # kill_request__recive_date__date__lte=last_date,
        #             province_kill_request__in=province_kill_requests, vet_state='accepted',
        #             assignment_state_archive='True',
        #             trash=False)
        #     elif date2 > last_date and date1 > last_date:
        #         kill_house_request_without_clearance_code = []
        #         kill_house_request_without_vet_check = []
        #         kill_house_request_without_bar_info = []
        #         kill_house_request_diffrent_quarantine_quantity = KillHouseRequest.objects.filter(
        #             Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')),
        #             province_kill_request__in=province_kill_requests, clearance_code__isnull=False,
        #             quarantine_quantity__isnull=False, trash=False)
        #         kill_house_request_diffrent_bar_info = KillHouseRequest.objects.filter(
        #             Q(quantity__gt=F('vet_accepted_real_quantity')) | Q(
        #                 quantity__lt=F('vet_accepted_real_quantity')) | Q(
        #                 quantity__gt=F('accepted_real_quantity')) | Q(quantity__lt=F('accepted_real_quantity')) | Q(
        #                 vet_accepted_real_quantity__gt=F('accepted_real_quantity')) | Q(
        #                 vet_accepted_real_quantity__lt=F('accepted_real_quantity')),
        #             province_kill_request__in=province_kill_requests, vet_state='accepted',
        #             assignment_state_archive='True',
        #             trash=False)
        #     else:
        #
        #         kill_house_request_without_clearance_code = KillHouseRequest.objects.filter(
        #             province_kill_request__in=province_kill_requests, clearance_code__isnull=True, trash=False)
        #
        #         kill_house_request_diffrent_quarantine_quantity = KillHouseRequest.objects.filter(
        #             Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')),
        #             province_kill_request__in=province_kill_requests, clearance_code__isnull=False,
        #             quarantine_quantity__isnull=False, trash=False)
        #         kill_house_request_without_vet_check = KillHouseRequest.objects.filter(
        #             province_kill_request__in=province_kill_requests, vet_state='pending', trash=False)
        #         kill_house_request_without_bar_info = KillHouseRequest.objects.filter(
        #             province_kill_request__in=province_kill_requests, vet_state='accepted',
        #             assignment_state_archive='pending',
        #             trash=False)
        #         kill_house_request_diffrent_bar_info = KillHouseRequest.objects.filter(
        #             Q(quantity__gt=F('vet_accepted_real_quantity')) | Q(
        #                 quantity__lt=F('vet_accepted_real_quantity')) | Q(
        #                 quantity__gt=F('accepted_real_quantity')) | Q(quantity__lt=F('accepted_real_quantity')) | Q(
        #                 vet_accepted_real_quantity__gt=F('accepted_real_quantity')) | Q(
        #                 vet_accepted_real_quantity__lt=F('accepted_real_quantity')),
        #             province_kill_request__in=province_kill_requests, vet_state='accepted',
        #             assignment_state_archive='True',
        #             trash=False)
        # else:
        kill_house_request_without_clearance_code = KillHouseRequest.objects.filter(
            province_kill_request__in=province_kill_requests, clearance_code__isnull=True, trash=False)

        kill_house_request_diffrent_quarantine_quantity = KillHouseRequest.objects.filter(
            Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')),
            province_kill_request__in=province_kill_requests, clearance_code__isnull=False,
            quarantine_quantity__isnull=False, trash=False)
        kill_house_request_without_vet_check = KillHouseRequest.objects.filter(
            province_kill_request__in=province_kill_requests, vet_state='pending', trash=False)
        kill_house_request_without_bar_info = KillHouseRequest.objects.filter(
            province_kill_request__in=province_kill_requests,
            assignment_state_archive='pending',
            trash=False)

        kill_house_request_diffrent_bar_info = KillHouseRequest.objects.filter(
            Q(quantity__gt=F('accepted_real_quantity')) | Q(quantity__lt=F('accepted_real_quantity')),
            province_kill_request__in=province_kill_requests,
            assignment_state_archive='True',
            trash=False)

        # kill_house_request_diffrent_bar_info = KillHouseRequest.objects.filter(
        #     Q(quantity__gt=F('vet_accepted_real_quantity')) | Q(quantity__lt=F('vet_accepted_real_quantity')) | Q(
        #         quantity__gt=F('accepted_real_quantity')) | Q(quantity__lt=F('accepted_real_quantity')) | Q(
        #         vet_accepted_real_quantity__gt=F('accepted_real_quantity') | Q(vet_accepted_real_quantity__lt=F('accepted_real_quantity'))),
        #     province_kill_request__in=province_kill_requests, vet_state='accepted', assignment_state_archive='True',
        #     trash=False)

        # kill_house_request_diffrent_bar_info = KillHouseRequest.objects.filter(
        #     Q(quantity__gt=F('vet_accepted_real_quantity')) | Q(quantity__lt=F('vet_accepted_real_quantity')) | Q(
        #         quantity__gt=F('accepted_real_quantity')) | Q(quantity__lt=F('accepted_real_quantity')) | Q(
        #         vet_accepted_real_quantity__gt=F('accepted_real_quantity')) | Q(
        #         vet_accepted_real_quantity__lt=F('accepted_real_quantity')),
        #     province_kill_request__in=province_kill_requests, vet_state='accepted', assignment_state_archive='True',
        #     trash=False)

        kill_house_request_without_clearance_code_serializer = KillHouseRequestForBarManagementSerializer(
            kill_house_request_without_clearance_code, many=True)
        kill_house_request_diffrent_quarantine_quantitye_serializer = KillHouseRequestForBarManagementSerializer(
            kill_house_request_diffrent_quarantine_quantity, many=True)
        kill_house_request_without_vet_check_serializer = KillHouseRequestForBarManagementSerializer(
            kill_house_request_without_vet_check, many=True)
        kill_house_request_without_bar_info_serializer = KillHouseRequestForBarManagementSerializer(
            kill_house_request_without_bar_info, many=True)
        kill_house_request_diffrent_bar_info_serializer = KillHouseRequestForDiffrentBarInfoSerializer(
            kill_house_request_diffrent_bar_info, many=True)

        return Response({
            "part_one": {
                "total_requests": poultry_requests.count(),
                "poultry_request_total_quantity": poultry_request_total_quantity if poultry_request_total_quantity != None else 0,
                "poultry_request_total_weight": poultry_request_total_weight if poultry_request_total_weight != None else 0,
                "province_kill_requests_total_quantity": province_kill_requests_total_quantity if province_kill_requests_total_quantity != None else 0,
                "province_kill_requests_total_weight": province_kill_requests_total_weight if province_kill_requests_total_weight != None else 0,
                "poultry_request_total_remain_quantity": poultry_request_total_remain_quantity if poultry_request_total_remain_quantity != None else 0,
                "poultry_request_remain_weight": poultry_request_remain_weight if poultry_request_remain_weight != None else 0,
                "operator_fullname": province_operator.user.fullname,
                "operator_mobile": province_operator.user.mobile,
                "role": "ProvinceOperator",
            },
            "part_two": province_kill_requests_serializer.data,
            "part_three": kill_house_request_without_clearance_code_serializer.data,
            "part_seven": kill_house_request_diffrent_quarantine_quantitye_serializer.data,
            "part_four": kill_house_request_without_vet_check_serializer.data,
            "part_five": kill_house_request_without_bar_info_serializer.data,
            "part_six": kill_house_request_diffrent_bar_info_serializer.data,
        })


class PoultryRequestForTotalInformationInTableViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    kill_house_requests_queryset = KillHouseRequest.objects.all()
    serializer_class = PoultryRequestForTotalInformationInTableSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = PoultryRequestFilterSet
    filterset_fields = poultry_request_new_fields
    kill_house_requests_filter_class = KillHouseRequestFilterSet
    kill_house_requests_filterset_fields = kill_house_request_filterset_fields

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

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if 'clearance_code' in request.GET:

            kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                  kill_request__recive_date__date__lte=date2,
                                                                  clearance_code__isnull=request.GET[
                                                                      'clearance_code']).select_related(
                'province_request__poultry_request')

            poultry_requests = PoultryRequest.objects.filter(
                pk__in=kill_house_requests.values('province_request__poultry_request'),
                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')
        elif 'assignment' in request.GET:
            kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                  kill_request__recive_date__date__lte=date2,
                                                                  assignment_state_archive=request.GET[
                                                                      'assignment']).select_related(
                'province_request__poultry_request')

            poultry_requests = PoultryRequest.objects.filter(
                pk__in=kill_house_requests.values('province_request__poultry_request'),
                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')


        elif 'discharge' in request.GET:
            if request.GET['discharge'] == 'pending':
                kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                      kill_request__recive_date__date__lte=date2,
                                                                      vet_state='pending',
                                                                      assignment_state_archive='pending').select_related(
                    'province_request__poultry_request')
            else:
                kill_house_requests = KillHouseRequest.objects.filter(
                    (Q(vet_state='pending') | Q(vet_state='pending', assignment_state_archive='True')),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2, ).select_related(
                    'province_request__poultry_request')

            poultry_requests = PoultryRequest.objects.filter(
                pk__in=kill_house_requests.values('province_request__poultry_request'),
                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')

        else:
            poultry_requests = 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')
            kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                  kill_request__recive_date__date__lte=date2,
                                                                  province_request__poultry_request__in=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 (self.filterset_class(
                            data=query,
                            queryset=poultry_requests

                    )
                    ).filter():
                        ps = self.filterset_class(data=query, queryset=poultry_requests)
                        poultry_requests_for_search = ps.filter()

                poultry_requests = [] if len(poultry_requests_for_search) == 0 else poultry_requests_for_search

                for item in self.kill_house_requests_filterset_fields:
                    kill_house_request_query = QueryDict('{0}={1}'.format(item, request.GET['value']))
                    if (self.kill_house_requests_filter_class(
                            data=kill_house_request_query,
                            queryset=kill_house_requests

                    )
                    ).filter():
                        ks = self.kill_house_requests_filter_class(data=kill_house_request_query,
                                                                   queryset=kill_house_requests)
                        kill_house_request_for_search = ks.filter()
                kill_house_requests = [] if len(kill_house_request_for_search) == 0 else kill_house_request_for_search
                if len(kill_house_requests) > 0:
                    for kill_house_request in kill_house_requests:
                        if kill_house_request.province_request.poultry_request not in poultry_requests:
                            poultry_requests.append(kill_house_request.province_request.poultry_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(poultry_requests)
        if page is not None:
            serializer = PoultryRequestForTotalInformationInTableSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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


class PoultryRequestForTotalInformationViewSet(viewsets.ModelViewSet):
    queryset = PoultryRequest.objects.all()
    kill_house_requests_queryset = KillHouseRequest.objects.all()
    serializer_class = PoultryRequestForTotalInformationSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = PoultryRequestFilterSet
    filterset_fields = poultry_request_new_fields
    kill_house_requests_filter_class = KillHouseRequestFilterSet
    kill_house_requests_filterset_fields = kill_house_request_filterset_fields

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

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if 'clearance_code' in request.GET:

            kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                  kill_request__recive_date__date__lte=date2,
                                                                  clearance_code__isnull=request.GET[
                                                                      'clearance_code']).select_related(
                'province_request__poultry_request')

            poultry_requests = PoultryRequest.objects.filter(
                pk__in=kill_house_requests.values('province_request__poultry_request'),
                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')
        elif 'assignment' in request.GET:
            kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                  kill_request__recive_date__date__lte=date2,
                                                                  assignment_state_archive=request.GET[
                                                                      'assignment']).select_related(
                'province_request__poultry_request')

            poultry_requests = PoultryRequest.objects.filter(
                pk__in=kill_house_requests.values('province_request__poultry_request'),
                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')


        elif 'discharge' in request.GET:
            if request.GET['discharge'] == 'pending':
                kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                      kill_request__recive_date__date__lte=date2,
                                                                      vet_state='pending',
                                                                      assignment_state_archive='pending').select_related(
                    'province_request__poultry_request')
            else:
                kill_house_requests = KillHouseRequest.objects.filter(
                    (Q(vet_state='pending') | Q(vet_state='pending', assignment_state_archive='True')),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2, ).select_related(
                    'province_request__poultry_request')

            poultry_requests = PoultryRequest.objects.filter(
                pk__in=kill_house_requests.values('province_request__poultry_request'),
                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')

        else:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                poultry_requests = PoultryRequest.objects.filter(
                    poultry__address__province=user.province,
                    poultry__city_operator=city_operator.unit_name,
                    # final_state='pending',
                    trash=False,
                    # out=False,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                ).order_by('-send_date')
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                poultry_requests = PoultryRequest.objects.filter(
                    poultry__address__city=user.city,
                    # final_state='pending',
                    trash=False,
                    # out=False,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                ).order_by('-send_date')
            elif request.GET['role'] == 'LiveStockSupport':
                poultry_requests = PoultryRequest.objects.filter(
                    poultry__address__province=user.province,
                    freezing=True,
                    final_state='pending',
                    trash=False, out=False,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                ).order_by('-send_date')
            else:
                poultry_requests = PoultryRequest.objects.filter(
                    poultry__address__province=user.province,
                    # final_state='pending',
                    trash=False,
                    # out=False,
                    send_date__date__gte=date1,
                    send_date__date__lte=date2,
                ).order_by('-send_date')
            kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                  kill_request__recive_date__date__lte=date2,
                                                                  province_request__poultry_request__in=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 (self.filterset_class(
                            data=query,
                            queryset=poultry_requests

                    )
                    ).filter():
                        ps = self.filterset_class(data=query, queryset=poultry_requests)
                        poultry_requests_for_search = ps.filter()

                poultry_requests = [] if len(poultry_requests_for_search) == 0 else poultry_requests_for_search

                for item in self.kill_house_requests_filterset_fields:
                    kill_house_request_query = QueryDict('{0}={1}'.format(item, request.GET['value']))
                    if (self.kill_house_requests_filter_class(
                            data=kill_house_request_query,
                            queryset=kill_house_requests

                    )
                    ).filter():
                        ks = self.kill_house_requests_filter_class(data=kill_house_request_query,
                                                                   queryset=kill_house_requests)
                        kill_house_request_for_search = ks.filter()
                kill_house_requests = [] if len(kill_house_request_for_search) == 0 else kill_house_request_for_search
                if len(kill_house_requests) > 0:
                    for kill_house_request in kill_house_requests:
                        if kill_house_request.province_request.poultry_request not in poultry_requests:
                            poultry_requests.append(kill_house_request.province_request.poultry_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(poultry_requests)
        if page is not None:
            serializer = PoultryRequestForTotalInformationSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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


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

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date = datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date()
        if request.GET['type'] == 'broadcast':
            date_one_day_ago = date - timedelta(days=1)
        else:
            date_one_day_ago = date

        poultry_requests_first_letter = 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=date_one_day_ago
                                                                      ).order_by('-send_date')
        serializer_poultry_requests_first_letter = PoultryRequestForKillingInformationSerializer(
            poultry_requests_first_letter, many=True)
        poultry_requests_seconde_letter = PoultryRequest.objects.filter(send_date__date=date_one_day_ago,
                                                                        quantity__gt=F('remain_quantity'),
                                                                        trash=False)
        serializer_poultry_requests_seconde_letter = PoultryRequestLetterForProvinceVetSerializer(
            poultry_requests_seconde_letter, many=True)

        kill_house_requests_third_letter_part_two = KillHouseRequest.objects.filter(
            Q(vet_state='accepted') | Q(assignment_state_archive='True'),
            kill_request__recive_date__date=date_one_day_ago,
            province_request__poultry_request__poultry__address__province=user.province,
            trash=False
        ).only('accepted_real_quantity', 'accepted_real_weight')
        kill_house_requests_third_letter_part_two_quantity = \
            kill_house_requests_third_letter_part_two.aggregate(total=Sum('accepted_real_quantity'))[
                'total']
        kill_house_requests_third_letter_part_two_weight = \
            kill_house_requests_third_letter_part_two.aggregate(total=Sum('accepted_real_weight'))[
                'total']
        kill_house_requests_third_letter_part_three = KillHouseRequest.objects.filter(
            clearance_code__isnull=False,
            kill_request__recive_date__date=date_one_day_ago,
            province_request__poultry_request__poultry__address__province=user.province,
            trash=False
        ).only('accepted_real_quantity', 'accepted_real_weight')

        # total_weight = kill_house_requests_third_letter.aggregate(total=Sum('accepted_real_weight'))[
        #     'total']
        # total_quantity = kill_house_requests_third_letter.aggregate(total=Sum('accepted_real_quantity'))[
        #     'total']

        kill_house_requests_third_letter = KillHouseRequest.objects.filter(
            kill_request__recive_date__date=date_one_day_ago,
            province_request__poultry_request__poultry__address__province=user.province,
            trash=False
        ).select_related('kill_request')
        kill_house_requests_third_letter_quantity = kill_house_requests_third_letter.aggregate(total=Sum('quantity'))[
            'total']
        kill_house_requests_third_letter_weight = kill_house_requests_third_letter.aggregate(
            total=Sum(F('accepted_real_weight') * F('province_request__poultry_request__Index_weight')))[
            'total']
        serializer_kill_house_requests_third_letter = KillHouseRequestForBarManagementSerializer(
            kill_house_requests_third_letter, many=True)

        province_kill_requests = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                                    kill_request__recive_date__date=date_one_day_ago).select_related(
            'killhouse_user')
        kill_houses = KillHouse.objects.filter(
            pk__in=province_kill_requests.values('killhouse_user')
        )
        kill_house_ware_houses = KillHouseWareHouse.objects.filter(kill_house__in=kill_houses, date__date=date)
        steward_allocations = StewardAllocation.objects.filter(
            system_registration_code=True,
            ware_house__in=kill_house_ware_houses, trash=False,
            date__date=date).order_by('id')

        total_number_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
            'total']
        total_weight_of_carcasses = kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
            'total']
        allocated_total_number_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('allocated_total_number_of_carcasses'))['total']
        allocated_total_weight_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('allocated_total_weight_of_carcasses'))['total']
        remain_total_number_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))['total']
        remain_total_weight_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))['total']

        province_kill_requests = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                                    kill_request__recive_date__date=date_one_day_ago).select_related(
            'killhouse_user')
        kill_houses = KillHouse.objects.filter(
            pk__in=province_kill_requests.values('killhouse_user')
        )

        serializer_kill_house_requests_fourth_part_two = KillHouseForAutomaticStewardAllocationSerializer(kill_houses,
                                                                                                          context={
                                                                                                              'request': request},
                                                                                                          many=True)

        allocations = StewardAllocation.objects.filter(trash=False, system_registration_code=True,
                                                       date__date=date).order_by('id')
        real_number_of_carcasses = \
            allocations.aggregate(total=Sum('real_number_of_carcasses'))['total']
        real_weight_of_carcasses = \
            allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total']
        serializer_kill_house_requests_fourth_part_three = StewardAllocationSerializer(allocations, many=True)

        return Response({
            "serializer_poultry_requests_first_letter": serializer_poultry_requests_first_letter.data,
            "serializer_poultry_requests_seconde_letter": serializer_poultry_requests_seconde_letter.data,
            "serializer_kill_house_requests_third_letter": serializer_kill_house_requests_third_letter.data,
            "kill_house_requests_third_letter_quantity": kill_house_requests_third_letter_quantity if kill_house_requests_third_letter_quantity != None else 0,
            "kill_house_requests_third_letter_weight": int(
                kill_house_requests_third_letter_weight) if kill_house_requests_third_letter_weight != None else 0,
            "serializer_kill_house_requests_third_letter_part_two": len(kill_house_requests_third_letter_part_two),
            "kill_house_requests_third_letter_part_two_quantity": kill_house_requests_third_letter_part_two_quantity if kill_house_requests_third_letter_part_two_quantity != None else 0,
            "kill_house_requests_third_letter_part_two_weight": kill_house_requests_third_letter_part_two_weight if kill_house_requests_third_letter_part_two_weight != None else 0,
            "serializer_kill_house_requests_third_letter_part_three": len(kill_house_requests_third_letter_part_three),
            "serializer_kill_house_requests_fourth_part_one": {
                "buyers": len(kill_house_ware_houses),
                "allocations": len(steward_allocations),
                "total_number_of_carcasses": total_number_of_carcasses if total_number_of_carcasses != None else 0,
                "total_weight_of_carcasses": total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                "allocated_total_number_of_carcasses": allocated_total_number_of_carcasses if allocated_total_number_of_carcasses != None else 0,
                "allocated_total_weight_of_carcasses": allocated_total_weight_of_carcasses if allocated_total_weight_of_carcasses != None else 0,
                "remain_total_number_of_carcasses": remain_total_number_of_carcasses if remain_total_number_of_carcasses != None else 0,
                "remain_total_weight_of_carcasses": remain_total_weight_of_carcasses if remain_total_weight_of_carcasses != None else 0,
            },
            "serializer_kill_house_requests_fourth_part_two": serializer_kill_house_requests_fourth_part_two.data,
            "serializer_kill_house_requests_fourth_part_three": serializer_kill_house_requests_fourth_part_three.data,
            "serializer_kill_house_requests_fourth_part_fourth": real_number_of_carcasses if real_number_of_carcasses != None else 0,
            "serializer_kill_house_requests_fourth_part_fifth": real_weight_of_carcasses if real_weight_of_carcasses != None else 0,
            "serializer_kill_house_requests_fourth_part_sixth": len(allocations),
        })


class StewardGuildsAllocationsForStatisticalProfileViewSet(viewsets.ModelViewSet):
    queryset = StewardAllocation.objects.all()
    serializer_class = StewardAllocationSerializer
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        date = datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date()
        allocations = StewardAllocation.objects.filter(trash=False, system_registration_code=True,
                                                       date__date=date).order_by('id')
        real_number_of_carcasses = \
            allocations.aggregate(total=Sum('real_number_of_carcasses'))['total']
        real_weight_of_carcasses = \
            allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total']
        serializer_kill_house_requests_fourth_part_three = StewardAllocationSerializer(allocations, many=True)

        return Response({
            "real_number_of_carcasses": real_number_of_carcasses if real_number_of_carcasses != None else 0,
            "real_weight_of_carcasses": real_weight_of_carcasses if real_weight_of_carcasses != None else 0,
            "allocations": len(allocations),
        })


# kill_house_requests=KillHouseRequest.objects.filter(killhouse_user__id=5,trash=True,clearance_code__isnull=False,message__isnull=True)
# for kill_house_request in kill_house_requests:
#     kill_house_request.message='عدم ارسال راننده توسط کشتارگاه'
#     kill_house_request.bar_remover={
#         "date": str(kill_house_request.create_date.date()),
#         "role":"KillHouse",
#         "mobile": "09143488339",
#         "full_name": "حامد صمدی"
#     }
#     kill_house_request.save()


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

    def hatching_55_90_data(self, request):
        if 'role' in request.GET:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user__user=request.user)
                hatching_between_50_70 = PoultryHatching.objects.filter(trash=False, left_over__gt=F('quantity') * 0.1,
                                                                        chicken_age__range=(55, 90),
                                                                        poultry__city_operator=city_operator.unit_name, ).order_by(
                    'id')
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                hatching_between_50_70 = PoultryHatching.objects.filter(trash=False, left_over__gt=F('quantity') * 0.1,
                                                                        chicken_age__range=(55, 90),
                                                                        poultry__user__city=user.city).order_by('id')
            else:
                hatching_between_50_70 = PoultryHatching.objects.filter(trash=False, left_over__gt=F('quantity') * 0.1,
                                                                        chicken_age__range=(55, 90)).order_by('id')
        else:
            hatching_between_50_70 = PoultryHatching.objects.filter(trash=False, left_over__gt=F('quantity') * 0.1,
                                                                    chicken_age__range=(55, 90)).order_by('id')
        min_list = []

        all_poultry_hatching_quantity = hatching_between_50_70.aggregate(total=Sum('quantity'))['total']
        all_poultry_hatching_killed_quantity = hatching_between_50_70.aggregate(total=Sum('killed_quantity'))['total']
        all_poultry_hatching_left_over = hatching_between_50_70.aggregate(total=Sum('left_over'))['total']
        all_left_over_ninty_percent = \
            hatching_between_50_70.aggregate(total=Sum(F('quantity') * 90 / 100) - Sum(F('killed_quantity')))['total']
        archive_hatch = hatching_between_50_70.filter(archive=True, allow_hatching='True')
        active_hatch = hatching_between_50_70.filter(archive=False, allow_hatching='pending')
        archive_hatching_quantity = \
            archive_hatch.aggregate(total=Sum('quantity'))['total']
        left_over_active_hatch = \
            active_hatch.aggregate(total=Sum('quantity'))['total'] or 0
        for poultry_hatching in hatching_between_50_70:
            if poultry_hatching.chicken_age not in min_list:
                min_list.append(poultry_hatching.chicken_age)

        min_list = sorted(min_list)
        all_total_commitment = hatching_between_50_70.aggregate(total_quantity=Sum('total_commitment')).get(
            'total_quantity', 0)
        all_governmental_killed_quantity = hatching_between_50_70.aggregate(
            total_quantity=Sum('governmental_killed_quantity')).get(
            'total_quantity', 0)
        all_free_killed_quantity = hatching_between_50_70.aggregate(
            total_quantity=Sum('free_killed_quantity')).get(
            'total_quantity', 0)
        all_total_killed_weight = hatching_between_50_70.aggregate(
            total_quantity=Sum('total_killed_weight')).get(
            'total_quantity', 0)
        all_governmental_quantity = hatching_between_50_70.aggregate(
            total_quantity=Sum('governmental_quantity')).get(
            'total_quantity', 0)
        all_free_quantity = hatching_between_50_70.aggregate(
            total_quantity=Sum('free_quantity')).get(
            'total_quantity', 0)
        all_out_province_killed_quantity = hatching_between_50_70.aggregate(
            total_quantity=Sum('out_province_killed_quantity')).get(
            'total_quantity', 0)
        all_out_province_killed_weight = hatching_between_50_70.aggregate(
            total_quantity=Sum('out_province_killed_weight')).get(
            'total_quantity', 0)

        return {
            'poultry': len(hatching_between_50_70),
            'hatching_quantity': all_poultry_hatching_quantity,
            'len_archive_hatching': len(archive_hatch),
            'archive_hatching_quantity': archive_hatching_quantity,
            'len_active_hatching': len(active_hatch),
            'active_hatching_quantity': left_over_active_hatch,
            'hatching_killed_quantity': all_poultry_hatching_killed_quantity,
            'hatching_killed_weight': int(all_total_killed_weight),
            'hatching_left_over': all_poultry_hatching_left_over,
            'hatching_left_over_ninty_percent': all_left_over_ninty_percent,
            'min_age': min_list[0] if len(min_list) > 0 else None,
            'max_age': min_list[len(min_list) - 1] if len(min_list) > 0 else None,
            'total_commitment': all_total_commitment,
            'governmental_quantity': all_governmental_quantity,
            'governmental_weight': int(all_governmental_killed_quantity),
            'free_quantity': all_free_quantity,
            'free_weight': all_free_killed_quantity,
            'out_province_killed_quantity': all_out_province_killed_quantity,
            'out_province_killed_weight': all_out_province_killed_weight
        }

    def get_kill_house_for_detail(self, kill_req):
        poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=kill_req.values(
            'province_request__poultry_request'))
                           .only('quantity', 'Index_weight')).annotate(
            total_quantity=Sum('quantity'),
            total_weight=Sum(F('quantity') * F('Index_weight'))
        )
        total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total']
        total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total']
        all_quantity = kill_req.aggregate(total=Sum('accepted_real_quantity'))[
                           'total'] or 0
        all_weighte = kill_req.aggregate(total=Sum('accepted_real_weight'))[
                          'total'] or 0
        all_governmental_quantity = \
            kill_req.filter(province_request__poultry_request__free_sale_in_province=False).aggregate(
                total=Sum('accepted_real_quantity'))[
                'total'] or 0
        all_governmental_weight = \
            kill_req.filter(province_request__poultry_request__free_sale_in_province=False).aggregate(
                total=Sum('accepted_real_weight'))[
                'total'] or 0
        all_free_quantity = kill_req.filter(province_request__poultry_request__free_sale_in_province=True).aggregate(
            total=Sum('accepted_real_quantity'))[
                                'total'] or 0
        all_free_weight = kill_req.filter(province_request__poultry_request__free_sale_in_province=True).aggregate(
            total=Sum('accepted_real_weight'))[
                              'total'] or 0

        all_age = []

        if kill_req:
            for kill in kill_req:
                # weight = kill.get('quantity') * kill.get(
                #     'province_kill_request__province_request__poultry_request__Index_weight')
                # all_weighte += weight
                age = (kill.get('province_request__poultry_request__send_date').date() -
                       kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                if age not in all_age:
                    all_age.append(age)
        # difference_bars = kill_req.filter(
        #     Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')),quarantine_quantity__gt=0)
        #
        #
        # final_real_quantity=-0
        # difference_bar = len(difference_bars)
        # greater_bars_quantity = difference_bars.filter(quantity__gt=F('quarantine_quantity'))
        # real_greater_bars_quantity = (greater_bars_quantity.aggregate(total=Sum('quarantine_quantity'))['total'] or 0 )  - (greater_bars_quantity.aggregate(total=Sum('quantity'))['total'] or 0 )
        # less_bars_quantity = difference_bars.filter(quantity__lt=F('quarantine_quantity'))
        # real_less_bars_quantity = (less_bars_quantity.aggregate(total=Sum('quarantine_quantity'))['total'] or 0 )  - (less_bars_quantity.aggregate(total=Sum('quantity'))['total'] or 0 )
        #
        # final_real_quantity = real_greater_bars_quantity +  real_less_bars_quantity if real_greater_bars_quantity > 0 else (-1 * real_greater_bars_quantity) +  real_less_bars_quantity

        difference_bars = kill_req.filter(
            Q(accepted_real_quantity__gt=F('quarantine_quantity')) | Q(
                accepted_real_quantity__lt=F('quarantine_quantity')), quarantine_quantity__gt=0)

        final_real_quantity = -0
        difference_bar = len(difference_bars)
        greater_bars_quantity = difference_bars.filter(accepted_real_quantity__gt=F('quarantine_quantity'))
        real_greater_bars_quantity = (greater_bars_quantity.aggregate(total=Sum('quarantine_quantity'))[
                                          'total'] or 0) - (
                                             greater_bars_quantity.aggregate(total=Sum('accepted_real_quantity'))[
                                                 'total'] or 0)
        less_bars_quantity = difference_bars.filter(accepted_real_quantity__lt=F('quarantine_quantity'))
        real_less_bars_quantity = (less_bars_quantity.aggregate(total=Sum('quarantine_quantity'))['total'] or 0) - (
                less_bars_quantity.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0)

        final_real_quantity = real_greater_bars_quantity + real_less_bars_quantity if real_greater_bars_quantity > 0 else (
                                                                                                                                  -1 * real_greater_bars_quantity) + real_less_bars_quantity

        hasnt_code = kill_req.filter(clearance_code__isnull=True)
        all_quarantine_quantity_hasnt_code = hasnt_code.aggregate(total_quantity=Sum('quantity')).get(
            'total_quantity', 0)
        has_code = kill_req.filter(clearance_code__isnull=False)
        all_quarantine_quantity_has_code = has_code.aggregate(total_quantity=Sum('quantity')).get(
            'total_quantity', 0)
        has_qarantine = kill_req.filter(quarantine_quantity__isnull=False)
        all_has_qarantine = has_qarantine.aggregate(total_quantity=Sum('quarantine_quantity')).get(
            'total_quantity', 0)
        all_age1 = sorted(all_age)

        return {
            'poultry_request': len(poultry_request),
            'poultry_request_quantity': total_requests_quantity if total_requests_quantity != None else 0,
            'poultry_request_weight': int(total_requests_weight) if total_requests_weight != None else 0,
            'min_age': all_age1[0] if len(all_age1) > 0 else '-',
            'max_age': all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-',
            'avg_age': int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-',
            'len_kill_request': len(kill_req),
            'kill_request_quantity': all_quantity if all_quantity != None else 0,
            'kill_request_weight': int(all_weighte),
            'avg_weight': round(all_weighte / all_quantity, 1) if all_weighte > 0 and all_quantity > 0 else 0,
            'len_kill_request_has_code': len(has_code),
            'quantity_of_kill_request_has_code': all_quarantine_quantity_has_code if all_quarantine_quantity_has_code != None else 0,
            'len_kill_request_has_quarantine': len(has_qarantine),
            'quantity_of_kill_request_has_quarantine': all_has_qarantine if all_has_qarantine != None else 0,
            'len_kill_request_has_not_code': len(hasnt_code),
            'quantity_of_kill_request_has_not_code': all_quarantine_quantity_hasnt_code if all_quarantine_quantity_hasnt_code != None else 0,
            'difference_bar': difference_bar,
            'final_real_quantity': final_real_quantity,
            'all_governmental_quantity': all_governmental_quantity,
            'all_governmental_weight': all_governmental_weight,
            'all_free_quantity': all_free_quantity,
            'all_free_weight': all_free_weight,

        }

    def steward_ware_house_total_report_daily_broad_cast(self, steward):
        number_of_steward1 = Steward.objects.filter(
            pk__in=steward.values('steward')
        )

        steward_allocations = StewardAllocation.objects.filter(
            Q(type='manual') | Q(type='auto', system_registration_code=True),
            steward_ware_house__in=steward, receiver_state__in=('pending', 'accepted'),
            trash=False).order_by(
            'id')

        guild_allocations1 = steward_allocations.filter(guilds__isnull=False, trash=False)
        number_of_guild1 = guild_allocations1.values('guilds').distinct().count() if guild_allocations1 else 0

        total_number_of_free_carcasses1 = steward.aggregate(total=Sum('number_of_free_carcasses'))[
                                              'total'] or 0
        total_free_weight_of_carcasses1 = steward.aggregate(total=Sum('weight_of_free_carcasses'))[
                                              'total'] or 0
        total_number_of_carcasses1 = steward.aggregate(total=Sum('number_of_carcasses'))[
                                         'total'] or 0
        total_weight_of_carcasses1 = steward.aggregate(total=Sum('weight_of_carcasses'))[
                                         'total'] or 0

        final_total_number_of_carcasses1 = \
            steward.aggregate(total=Sum('real_number_of_carcasses'))[
                'total'] or 0
        final_total_weight_of_carcasses1 = \
            steward.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_remain_quantity1 = \
            steward.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                'total'] or 0

        total_remain_weight1 = \
            steward.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                'total'] or 0

        total_allocated_quantity1 = \
            steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[
                'total'] or 0

        total_allocated_weight1 = \
            steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_accepted_allocated_quantity1 = \
            steward_allocations.aggregate(total=Sum('receiver_real_number_of_carcasses'))[
                'total'] or 0

        total_accepted_allocated_weight1 = \
            steward_allocations.aggregate(total=Sum('receiver_real_weight_of_carcasses'))[
                'total'] or 0

        return {
            "buyers": len(number_of_steward1),
            "incoming_quantity_of_cold_house": 0,
            "incoming_weight_of_cold_house": 0,
            "total_pre_cold_quantity": 0,
            "total_pre_cold_weight": 0,
            "total_number_of_free_carcasses": total_number_of_free_carcasses1,
            "total_free_weight_of_carcasses": total_free_weight_of_carcasses1,
            "total_number_of_carcasses": total_number_of_carcasses1,
            "total_weight_of_carcasses": int(total_weight_of_carcasses1),
            "final_total_number_of_carcasses": final_total_number_of_carcasses1,
            "final_total_weight_of_carcasses": int(final_total_weight_of_carcasses1),
            "total_allocated_quantity": total_allocated_quantity1,
            "total_allocated_weight": int(total_allocated_weight1),
            "total_accepted_allocated_quantity": total_accepted_allocated_quantity1,
            "total_accepted_allocated_weight": int(total_accepted_allocated_weight1),
            "total_remain_quantity": total_remain_quantity1,
            "total_remain_weight": int(total_remain_weight1),
            "number_of_guild": number_of_guild1,
        }

    def kill_house_ware_house_total_report_daily_broad_cast(self, kill):
        number_of_kill_houses = KillHouse.objects.filter(
            pk__in=kill.values('kill_house')
        )

        steward_allocations = StewardAllocation.objects.filter(
            Q(type='manual') | Q(type='auto', system_registration_code=True),
            ware_house__in=kill, receiver_state__in=('pending', 'accepted'), trash=False).order_by(
            'id')

        guild_allocations = steward_allocations.filter(guilds__isnull=False, trash=False)
        number_of_guild = guild_allocations.values('guilds').distinct().count() if guild_allocations else 0

        steward_allocations_for_number_of_steward = steward_allocations.filter(steward__isnull=False, trash=False)
        number_of_steward = steward_allocations_for_number_of_steward.values(
            'steward').distinct().count() if steward_allocations_for_number_of_steward else 0

        total_pre_cold_quantity = \
            kill.aggregate(total=Sum('pre_cold_number_of_carcasses_to_ware_house'))[
                'total'] or 0
        total_pre_cold_weight = \
            kill.aggregate(total=Sum('pre_cold_weight_of_carcasses_to_ware_house'))[
                'total'] or 0
        total_number_of_free_carcasses = kill.aggregate(total=Sum('number_of_free_carcasses'))[
                                             'total'] or 0
        total_free_weight_of_carcasses = kill.aggregate(total=Sum('free_weight_of_carcasses'))[
                                             'total'] or 0
        total_number_of_carcasses = kill.aggregate(total=Sum('number_of_carcasses'))[
                                        'total'] or 0
        total_weight_of_carcasses = kill.aggregate(total=Sum('weight_of_carcasses'))[
                                        'total'] or 0

        final_total_number_of_carcasses = \
            kill.aggregate(total=Sum('final_total_number_of_carcasses'))[
                'total'] or 0
        final_total_weight_of_carcasses = \
            kill.aggregate(total=Sum('final_total_weight_of_carcasses'))[
                'total'] or 0

        total_remain_quantity = \
            kill.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                'total'] or 0

        total_remain_weight = \
            kill.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                'total'] or 0

        total_allocated_quantity = \
            steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[
                'total'] or 0

        total_allocated_weight = \
            steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_accepted_allocated_quantity = \
            steward_allocations.aggregate(total=Sum('receiver_real_number_of_carcasses'))[
                'total'] or 0

        total_accepted_allocated_weight = \
            steward_allocations.aggregate(total=Sum('receiver_real_weight_of_carcasses'))[
                'total'] or 0

        return {
            "buyers": len(number_of_kill_houses),
            "incoming_quantity_of_cold_house": 0,
            "incoming_weight_of_cold_house": 0,
            "total_pre_cold_quantity": total_pre_cold_quantity,
            "total_pre_cold_weight": int(total_pre_cold_weight),
            "total_number_of_free_carcasses": total_number_of_free_carcasses,
            "total_free_weight_of_carcasses": int(total_free_weight_of_carcasses),
            "total_number_of_carcasses": total_number_of_carcasses,
            "total_weight_of_carcasses": int(total_weight_of_carcasses),
            "final_total_number_of_carcasses": final_total_number_of_carcasses,
            "final_total_weight_of_carcasses": int(final_total_weight_of_carcasses),
            "total_allocated_quantity": total_allocated_quantity,
            "total_allocated_weight": int(total_allocated_weight),
            "total_accepted_allocated_quantity": total_accepted_allocated_quantity,
            "total_accepted_allocated_weight": int(total_accepted_allocated_weight),
            "total_remain_quantity": total_remain_quantity,
            "total_remain_weight": int(total_remain_weight),
            "number_of_guild": number_of_guild,
            "number_of_steward": number_of_steward,
        }

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()

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

            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user__user=request.user)
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name,
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2).order_by(
                    '-create_date').select_related(

                    'province_request__poultry_request',
                    'add_car__driver',
                ).only('province_request', 'province_request__poultry_request',

                       'province_request__poultry_request__send_date',
                       'province_kill_request__province_request__poultry_request__Index_weight',
                       'clearance_code',
                       'quantity',
                       'accepted_real_weight',
                       'accepted_real_quantity',
                       'vet_state', 'vet_accepted_real_quantity',
                       'vet_accepted_real_weight', 'quarantine_quantity',
                       'province_request__poultry_request__hatching__date',
                       'province_request__poultry_request__send_date').values(
                    'province_request',
                    'province_request__poultry_request',

                    'province_request__poultry_request__send_date',
                    'province_kill_request__province_request__poultry_request__Index_weight',
                    'clearance_code',
                    'quantity',
                    'accepted_real_weight',
                    'accepted_real_quantity',
                    'vet_state',
                    'vet_accepted_real_quantity',
                    'vet_accepted_real_weight',
                    'quarantine_quantity',
                    'province_request__poultry_request__hatching__date',
                    'province_request__poultry_request__send_date'
                )

                out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                         out_province_request_cancel=False,
                                                                         province_state='accepted',
                                                                         poultry__city_operator=city_operator.unit_name,
                                                                         send_date__date__gte=date1,
                                                                         send_date__date__lte=date2)

            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(user=request.user)
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
                    province_request__poultry_request__poultry__user__city=user.city,
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2).order_by(
                    '-create_date').select_related(

                    'province_request__poultry_request',
                    'add_car__driver',
                ).only('province_request', 'province_request__poultry_request',

                       'province_request__poultry_request__send_date',
                       'province_kill_request__province_request__poultry_request__Index_weight',
                       'clearance_code',
                       'quantity',
                       'accepted_real_weight',
                       'accepted_real_quantity',
                       'vet_state', 'vet_accepted_real_quantity',
                       'vet_accepted_real_weight', 'quarantine_quantity',
                       'province_request__poultry_request__hatching__date',
                       'province_request__poultry_request__send_date').values(
                    'province_request',
                    'province_request__poultry_request',

                    'province_request__poultry_request__send_date',
                    'province_kill_request__province_request__poultry_request__Index_weight',
                    'clearance_code',
                    'quantity',
                    'accepted_real_weight',
                    'accepted_real_quantity',
                    'vet_state',
                    'vet_accepted_real_quantity',
                    'vet_accepted_real_weight',
                    'quarantine_quantity',
                    'province_request__poultry_request__hatching__date',
                    'province_request__poultry_request__send_date'
                )

                out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                         out_province_request_cancel=False,
                                                                         poultry__user__city=user.city,
                                                                         province_state='accepted',
                                                                         send_date__date__gte=date1,
                                                                         send_date__date__lte=date2)
            else:
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2).order_by(
                    '-create_date').select_related(

                    'province_request__poultry_request',
                    'add_car__driver',
                ).only('province_request', 'province_request__poultry_request',

                       'province_request__poultry_request__send_date',
                       'province_kill_request__province_request__poultry_request__Index_weight',
                       'clearance_code',
                       'quantity',
                       'accepted_real_weight',
                       'accepted_real_quantity',
                       'vet_state', 'vet_accepted_real_quantity',
                       'vet_accepted_real_weight', 'quarantine_quantity',
                       'province_request__poultry_request__hatching__date',
                       'province_request__poultry_request__send_date').values(
                    'province_request',
                    'province_request__poultry_request',

                    'province_request__poultry_request__send_date',
                    'province_kill_request__province_request__poultry_request__Index_weight',
                    'clearance_code',
                    'quantity',
                    'accepted_real_weight',
                    'accepted_real_quantity',
                    'vet_state',
                    'vet_accepted_real_quantity',
                    'vet_accepted_real_weight',
                    'quarantine_quantity',
                    'province_request__poultry_request__hatching__date',
                    'province_request__poultry_request__send_date'
                )

                out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                         out_province_request_cancel=False,
                                                                         province_state='accepted',
                                                                         send_date__date__gte=date1,
                                                                         send_date__date__lte=date2)
        else:
            filtered_kill_reqs = KillHouseRequest.objects.filter(
                Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2).order_by(
                '-create_date').select_related(

                'province_request__poultry_request',
                'add_car__driver',
            ).only('province_request', 'province_request__poultry_request',

                   'province_request__poultry_request__send_date',
                   'province_kill_request__province_request__poultry_request__Index_weight',
                   'clearance_code',
                   'quantity',
                   'accepted_real_weight',
                   'accepted_real_quantity',
                   'vet_state', 'vet_accepted_real_quantity',
                   'vet_accepted_real_weight', 'quarantine_quantity',
                   'province_request__poultry_request__hatching__date',
                   'province_request__poultry_request__send_date').values(
                'province_request',
                'province_request__poultry_request',

                'province_request__poultry_request__send_date',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )

            out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                     out_province_request_cancel=False,
                                                                     province_state='accepted',
                                                                     send_date__date__gte=date1,
                                                                     send_date__date__lte=date2)

        kill_req = self.get_kill_house_for_detail(filtered_kill_reqs)

        filtered_kill_reqs_not_code_but_have_assigment = filtered_kill_reqs.filter(
            Q(assignment_state_archive='True', vet_state='pending')
            | Q(vet_state='accepted'), clearance_code__isnull=True)

        bar_government = filtered_kill_reqs.filter(
            province_request__poultry_request__free_sale_in_province=False)

        accepted_real_quantity_bar_government = bar_government.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity', 0) or 0
        accepted_real_wight_bar_government = bar_government.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity', 0) or 0

        bar_government_quarantine_quantity = bar_government.filter(quarantine_quantity__isnull=False)

        accepted_real_quantity_bar_government_quarantine_quantity = bar_government_quarantine_quantity.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0

        bar_free = filtered_kill_reqs.filter(province_request__poultry_request__free_sale_in_province=True)
        accepted_real_quantity_bar_free = bar_free.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        accepted_real_wight_bar_free = bar_free.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        bar_free_quarantine_quantity = bar_free.filter(quarantine_quantity__isnull=False)

        accepted_real_quantity_bar_free_quarantine_quantity = bar_free_quarantine_quantity.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0

        bar_free_has_code = len(bar_free.filter(clearance_code__isnull=False))

        quantity_out_true_poultry_request = out_true_poultry_request.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0

        bar_complete_with_kill_house_and_vet = filtered_kill_reqs.filter(
            trash=False)
        bar_complete_with_vet = filtered_kill_reqs.filter(
            vet_state='accepted')
        accepted_real_quantity_with_kill_house_and_vet = bar_complete_with_kill_house_and_vet.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        accepted_real_wight_with_kill_house_and_vet = bar_complete_with_kill_house_and_vet.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0
        all_vet_accepted_real_quantity_with_kill_house_and_vet = bar_complete_with_vet.aggregate(
            total_quantity=Sum('vet_accepted_real_quantity')).get(
            'total_quantity') or 0
        all_vet_accepted_real_weight_with_kill_house_and_vet = bar_complete_with_vet.aggregate(
            total_quantity=Sum('vet_accepted_real_weight')).get(
            'total_quantity') or 0
        bar_complete_with_kill_house = filtered_kill_reqs.filter(
            assignment_state_archive='True')

        accepted_real_wight_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        accepted_real_quantity_no_code = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        accepted_real_wight_no_code = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        if accepted_real_wight_with_kill_house_and_vet != None:
            less_25 = (accepted_real_wight_with_kill_house_and_vet * 75) / 100
        else:
            less_25 = 0

        filtered_kill_reqs_not_assigment_all = filtered_kill_reqs.filter(
            assignment_state_archive='pending', vet_state='pending')

        accepted_real_quantity_not_assigment_all = filtered_kill_reqs_not_assigment_all.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity', 0) or 0
        accepted_real_wight_not_assigment_all = filtered_kill_reqs_not_assigment_all.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity', 0) or 0

        filtered_kill_reqs_havent_kill_house = filtered_kill_reqs.filter(
            assignment_state_archive='pending'
            , vet_state='accepted')

        accepted_real_quantity_havent_kill_house = filtered_kill_reqs_havent_kill_house.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        accepted_real_wight_havent_kill_house = filtered_kill_reqs_havent_kill_house.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        accepted_real_quantity_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity', 0) or 0
        accepted_real_weight_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity', 0) or 0
        accepted_real_quantity_final1 = filtered_kill_reqs.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity', 0) or 0
        accepted_real_weight_final1 = filtered_kill_reqs.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity', 0) or 0
        kill_house_ware_houses = KillHouseWareHouse.objects.filter(
            Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
                pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=date1,
            date__date__lte=date2, trash=False)

        kill_house_data = self.kill_house_ware_house_total_report_daily_broad_cast(kill_house_ware_houses)

        steward_ware_houses = StewardWareHouse.objects.filter(
            Q(weight_of_carcasses__gt=0) | Q(weight_of_free_carcasses__gt=0), date__date__gte=date1,
            date__date__lte=date2, trash=False)

        steward = self.steward_ware_house_total_report_daily_broad_cast(steward_ware_houses)
        return Response({
            'age55_age90': self.hatching_55_90_data(request),
            'kill_request': kill_req,
            'free_and_government_kill_request': {
                'len_government': len(bar_government),
                'quantity_government': accepted_real_quantity_bar_government,
                'weight_government': int(accepted_real_wight_bar_government),
                'len_government_quarantine_quantity': len(bar_government_quarantine_quantity),
                'real_quantity_bar_government_quarantine_quantity': accepted_real_quantity_bar_government_quarantine_quantity,
                'len_free': len(bar_free),
                'quantity_free': accepted_real_quantity_bar_free,
                'weight_free': accepted_real_wight_bar_free,
                'len_free_quarantine_quantity': len(bar_free_quarantine_quantity),
                'real_quantity_bar_free_quarantine_quantity': accepted_real_quantity_bar_free_quarantine_quantity,
                'len_free_has_code': bar_free_has_code,
                'len_out_kill_request': len(out_true_poultry_request),
                'quantity_out_kill_request': quantity_out_true_poultry_request,
            },
            'complete_kill_request': {
                'len_complete_with_kill_house_and_vet': len(bar_complete_with_kill_house_and_vet),
                'quantity_with_kill_house_and_vet': accepted_real_quantity_with_kill_house_and_vet,
                'weight_with_kill_house_and_vet': int(accepted_real_wight_with_kill_house_and_vet),
                "avg_weight": round(
                    accepted_real_wight_with_kill_house_and_vet / accepted_real_quantity_with_kill_house_and_vet,
                    1) if accepted_real_wight_with_kill_house_and_vet > 0 else 0,
                'less_25': int(less_25),
                'len_complete_with_vet': len(bar_complete_with_vet),
                'quantity_complete_with_vet': all_vet_accepted_real_quantity_with_kill_house_and_vet,
                'weight_complete_with_vet': int(all_vet_accepted_real_weight_with_kill_house_and_vet),
                'len_complete_with_kill_house': len(bar_complete_with_kill_house),
                'quantity_final_kill_house': accepted_real_quantity_final,
                'weight_final_kill_house': int(accepted_real_wight_final),
                'len_kill_reqs_has_not_code': len(filtered_kill_reqs_not_code_but_have_assigment),
                'quantity_kill_reqs_has_not_code': accepted_real_quantity_no_code,
                'weight_kill_reqs_has_not_code': int(accepted_real_wight_no_code),
            },
            'kill_request_has_not_assigment': {
                'len_kill_reqs_not_assigment': len(filtered_kill_reqs_not_assigment_all),
                'quantity_kill_reqs_not_assigment': accepted_real_quantity_not_assigment_all,
                'weight_kill_reqs_not_assigment': int(accepted_real_wight_not_assigment_all),
                'len_kill_request_has_not_complete': len(filtered_kill_reqs_havent_kill_house),
                'quantity_kill_request_has_not_complete': accepted_real_quantity_havent_kill_house,
                'weight_kill_request_has_not_complete': int(accepted_real_wight_havent_kill_house),
            },
            'final_quantity_and_weight': {
                'final_quantity': accepted_real_quantity_final1,
                'final_weight': int(accepted_real_weight_final1),
            },
            'kill_house_ware_house_total_report_daily_broad_cast': kill_house_data,
            'steward_ware_house_total_report_daily_broad_cast': steward

        })


class ComprehensiveReportOfTheSlaughterhouseViewSet(viewsets.ViewSet):
    permission_classes = [AllowAny]

    def all_kill_request(self, date1, date2):
        filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False,
                                                             kill_request__recive_date__date__gte=date1,
                                                             kill_request__recive_date__date__lte=date2,
                                                             ).order_by(
            '-create_date').select_related(
            'province_request__poultry_request__hatching', 'province_request__poultry_request').only(
            'province_kill_request__province_request__poultry_request__Index_weight',
            'quantity',
            'accepted_real_weight',
            'accepted_real_quantity',
            'ware_house_accepted_real_weight',
            'ware_house_accepted_real_quantity')

        all_kill_req_quantity = filtered_kill_reqs.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0

        weight = filtered_kill_reqs.aggregate(
            total_quantity=Sum(
                F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[
                     'total_quantity'] or 0

        all_kill_req_quantity_reciver = filtered_kill_reqs.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        all_kill_req_weight_reciver = filtered_kill_reqs.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0
        all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate(
            total_quantity=Sum('ware_house_accepted_real_quantity')).get(
            'total_quantity') or 0
        all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate(
            total_quantity=Sum('ware_house_accepted_real_weight')).get(
            'total_quantity') or 0

        return {
            "quantity_of_create_bar": all_kill_req_quantity,
            "weight_of_create_bar": int(weight),
            "quantity_of_receive_bar": all_kill_req_quantity_reciver,
            "weight_of_receive_bar": int(all_kill_req_weight_reciver),
            "weight_with_twenty_five_percent_receive": int(
                (all_kill_req_weight_reciver * 75) / 100) if all_kill_req_weight_reciver > 0 else 0,
            "quantity_warehouse": all_ware_house_accepted_real_quantity,
            "weight_warehouse": int(all_ware_house_accepted_real_weight),
            "quantity_percent_warehouse": int(
                all_ware_house_accepted_real_quantity * 100 / all_kill_req_quantity_reciver) if all_ware_house_accepted_real_quantity > 0 else 0,
            "weight_percent_warehouse": int(
                all_ware_house_accepted_real_weight * 100 / all_kill_req_weight_reciver) if all_ware_house_accepted_real_weight > 0 else 0,
            "quantity_percent_receive": int(
                all_kill_req_quantity_reciver * 100 / all_kill_req_quantity) if all_kill_req_quantity_reciver > 0 else 0,
            "weight_percent_receive": int(
                (all_kill_req_weight_reciver * 100) / weight) if all_kill_req_weight_reciver > 0 else 0
        }

    def general_broadcast_information(self, tomorrow_date1, tomorrow_date2, filtered_kill_reqs, kill_free_info):

        number_of_kill_house = filtered_kill_reqs.values(
            'killhouse_user').distinct().count() if filtered_kill_reqs else 0

        all_quantity_out_false = filtered_kill_reqs.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0

        weight = filtered_kill_reqs.aggregate(
            total_quantity=Sum(
                F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[
                     'total_quantity'] or 0
        all_quantity_out_true = kill_free_info.aggregate(
            total_quantity=Sum('number_of_carcasses')).get(
            'total_quantity') or 0
        all_weight_out_true = kill_free_info.aggregate(
            total_quantity=Sum('weight_of_carcasses')).get(
            'total_quantity') or 0

        kill_house_ware_houses = KillHouseWareHouse.objects.filter(
            Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
                pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=tomorrow_date1,
            date__date__lte=tomorrow_date2, trash=False)
        final_total_number_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
                'total'] or 0
        final_total_weight_of_carcasses = \
            kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
                'total'] or 0
        steward_allocations = StewardAllocation.objects.filter(
            Q(type='manual') | Q(type='auto', system_registration_code=True),
            ware_house__in=kill_house_ware_houses, receiver_state__in=('pending', 'accepted'),
            trash=False).order_by(
            'id')
        total_allocated_quantity = \
            steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[
                'total'] or 0

        total_allocated_weight = \
            steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_accepted_allocated_quantity = \
            steward_allocations.aggregate(total=Sum('receiver_real_number_of_carcasses'))[
                'total'] or 0

        total_accepted_allocated_weight = \
            steward_allocations.aggregate(total=Sum('receiver_real_weight_of_carcasses'))[
                'total'] or 0

        total_remain_quantity = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                'total'] or 0

        total_remain_weight = \
            kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                'total'] or 0
        steward_allocations_for_number_of_steward = steward_allocations.filter(steward__isnull=False,
                                                                               trash=False)
        number_of_steward = steward_allocations_for_number_of_steward.values(
            'steward').distinct().count() if steward_allocations_for_number_of_steward else 0

        guild_allocations = steward_allocations.filter(guilds__isnull=False, trash=False)
        number_of_guild = guild_allocations.values('guilds').distinct().count() if guild_allocations else 0

        return {
            "number_of_buyer": number_of_kill_house,
            "quantity_of_kill_request_in_province": all_quantity_out_false,
            "weight_of_kill_request_in_province": int(weight),
            "quantity_of_kill_request_out_province": all_quantity_out_true,
            "weight_of_kill_request_out_province": int(all_weight_out_true),
            "quantity_carcasses": final_total_number_of_carcasses,
            "weight_carcasses": int(final_total_weight_of_carcasses),
            "allocated_quantity": total_allocated_quantity,
            "allocated_weight": int(total_allocated_weight),
            "accepted_allocated_quantity": total_accepted_allocated_quantity,
            "accepted_allocated_weight": int(total_accepted_allocated_weight),
            "remain_quantity": total_remain_quantity,
            "remain_weight": int(total_remain_weight),
            "percent_warehouse": int((
                                             total_allocated_quantity * 100) / final_total_number_of_carcasses) if total_allocated_quantity and final_total_number_of_carcasses > 0 else 0,
            "number_of_stewards": number_of_steward,
            "number_of_giulds": number_of_guild,
            "date1": tomorrow_date1,
            "date2": tomorrow_date2,

        }

    def kill_request_and_broadcast(self, tomorrow_date1, tomorrow_date2, filtered_kill_reqs, kill_free_info):
        list1 = []
        kill_houses = KillHouse.objects.filter(trash=False).select_related('kill_house_operator__user__city').exclude(
            out_province=True)
        for kill_house in kill_houses:
            kill_free_information = kill_free_info.filter(kill_house=kill_house)
            tomorrow_kill_request = filtered_kill_reqs.filter(killhouse_user=kill_house)
            if tomorrow_kill_request:
                tomorrow_kill_request_not_assigment = tomorrow_kill_request.filter(assignment_state_archive='pending',
                                                                                   vet_state='accepted')
                all_kill_req_quantity = tomorrow_kill_request.aggregate(
                    total_quantity=Sum('quantity')).get(
                    'total_quantity') or 0

                all_kill_req_quantity_reciver = tomorrow_kill_request.aggregate(
                    total_quantity=Sum('accepted_real_quantity')).get(
                    'total_quantity') or 0
                all_kill_req_weight_reciver = tomorrow_kill_request.aggregate(
                    total_quantity=Sum('accepted_real_weight')).get(
                    'total_quantity') or 0
                all_ware_house_accepted_real_quantity = tomorrow_kill_request.aggregate(
                    total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                    'total_quantity') or 0

                weight = tomorrow_kill_request.aggregate(
                    total_quantity=Sum(
                        F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[
                             'total_quantity'] or 0
                kill_house_ware_houses = KillHouseWareHouse.objects.filter(
                    Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
                        pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=tomorrow_date1,
                    date__date__lte=tomorrow_date2, kill_house=kill_house, trash=False)

                steward_allocations = StewardAllocation.objects.filter(
                    Q(type='manual') | Q(type='auto', system_registration_code=True),
                    ware_house__in=kill_house_ware_houses, receiver_state__in=('pending', 'accepted'),
                    trash=False).order_by(
                    'id')
                total_allocated_quantity = \
                    steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[
                        'total'] or 0
                total_allocated_weight = \
                    steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                        'total'] or 0
                total_accepted_allocated_quantity = \
                    steward_allocations.aggregate(total=Sum('receiver_real_number_of_carcasses'))[
                        'total'] or 0
                total_accepted_allocated_weight = \
                    steward_allocations.aggregate(total=Sum('receiver_real_weight_of_carcasses'))[
                        'total'] or 0

                total_remain_quantity = \
                    kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                        'total'] or 0
                total_remain_weight = \
                    kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                        'total'] or 0
                final_total_number_of_carcasses = \
                    kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
                        'total'] or 0

                final_total_weight_of_carcasses = \
                    kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
                        'total'] or 0
                steward_allocations_for_number_of_steward = steward_allocations.filter(steward__isnull=False,
                                                                                       trash=False)
                number_of_steward = steward_allocations_for_number_of_steward.values(
                    'steward').distinct().count() if steward_allocations_for_number_of_steward else 0

                guild_allocations = steward_allocations.filter(guilds__isnull=False, trash=False)
                number_of_guild = guild_allocations.values('guilds').distinct().count() if guild_allocations else 0

                all_kill_req_quantity_not_assigment = tomorrow_kill_request_not_assigment.aggregate(
                    total_quantity=Sum('accepted_real_quantity')).get(
                    'total_quantity') or 0
                all_kill_req_weight_not_assigment = tomorrow_kill_request_not_assigment.aggregate(
                    total_quantity=Sum('accepted_real_weight')).get(
                    'total_quantity') or 0
                all_quantity_out_true = kill_free_information.aggregate(
                    total_quantity=Sum('number_of_carcasses')).get(
                    'total_quantity') or 0
                all_weight_out_true = kill_free_information.aggregate(
                    total_quantity=Sum('weight_of_carcasses')).get(
                    'total_quantity') or 0
                twenty_five_percent = (int(all_kill_req_weight_reciver) * 75) / 100
                reciver_percent = int(
                    int(all_kill_req_quantity_reciver) * 100) / all_kill_req_quantity if all_kill_req_quantity_reciver > 0 else 0
                lashe_25_percent = int(
                    final_total_number_of_carcasses * 100 / all_kill_req_quantity_reciver) if final_total_number_of_carcasses > 0 else 0
                weight_lashe_25_percent = int(
                    final_total_weight_of_carcasses * 100 / all_kill_req_weight_reciver) if final_total_weight_of_carcasses > 0 else 0
                remain_percent = int((
                                             total_remain_quantity * 100) / all_ware_house_accepted_real_quantity) if total_remain_quantity and all_ware_house_accepted_real_quantity > 0 else 0
                all_num = number_of_steward + number_of_guild
                hasnt_code = len(
                    tomorrow_kill_request.filter(assignment_state_archive='True', clearance_code__isnull=True))
                percent_hasnt_code = round(hasnt_code * 100 / len(tomorrow_kill_request)) if len(
                    tomorrow_kill_request) > 0 else 0
                has_code = len(
                    tomorrow_kill_request.filter(assignment_state_archive='pending', clearance_code__isnull=False))
                percent_has_code = round(has_code * 100 / len(tomorrow_kill_request)) if len(
                    tomorrow_kill_request) > 0 else 0

                has_assignment = len(
                    tomorrow_kill_request.filter(assignment_state_archive='True'))
                percent_has_assignment = round(has_assignment * 100 / len(tomorrow_kill_request)) if len(
                    tomorrow_kill_request) > 0 else 0
                hasnt_assignment = len(
                    tomorrow_kill_request.filter(assignment_state_archive='pending'))
                percent_hasnt_assignment = round(hasnt_assignment * 100 / len(tomorrow_kill_request)) if len(
                    tomorrow_kill_request) > 0 else 0
                accepeted_bar = len(
                    tomorrow_kill_request.filter(bar_document_status__title='بدون مشکل'))
                percent_accepeted_bar = round(accepeted_bar * 100 / has_assignment) if has_assignment > 0 else 0
                diffrent_bar = len(
                    tomorrow_kill_request.filter(bar_document_status__title='مغایرت دارد'))
                percent_diffrent_bar = round(diffrent_bar * 100 / has_assignment) if has_assignment > 0 else 0
                no_quality = len(
                    tomorrow_kill_request.filter(bar_document_status__title='فاقد کیفیت'))
                percent_no_quality = round(no_quality * 100 / has_assignment) if has_assignment > 0 else 0
                low_quality = len(
                    tomorrow_kill_request.filter(bar_document_status__title='کیفیت پایین'))
                percent_low_quality = round(low_quality * 100 / has_assignment) if has_assignment > 0 else 0
                dict_1 = {
                    "name": kill_house.name,
                    "city": kill_house.kill_house_operator.user.city.name,
                    "kill_req_quantity": all_kill_req_quantity,
                    "kill_req_weight": int(weight),
                    "quantity_receiver": all_kill_req_quantity_reciver,
                    "weight_receiver": int(all_kill_req_weight_reciver),
                    "twenty_five_percent_weight": int(twenty_five_percent),
                    "receiver_percent": reciver_percent,
                    "quantity_of_carcasses": final_total_number_of_carcasses,
                    "weight_of_carcasses": int(final_total_weight_of_carcasses),
                    "quantity_of_lashe_percent": lashe_25_percent,
                    "weight_of_lashe_percent": int(weight_lashe_25_percent),
                    "quantity_out_province": all_quantity_out_true,
                    "weight_out_province": int(all_weight_out_true),
                    "total_number_of_carcasses": final_total_number_of_carcasses,
                    "total_weight_of_carcasses": int(final_total_weight_of_carcasses),
                    "allocated_quantity": total_allocated_quantity,
                    "allocated_weight": int(total_allocated_weight),
                    "accepted_allocated_quantity": total_accepted_allocated_quantity,
                    "accepted_allocated_weight": int(total_accepted_allocated_weight),
                    "remain_quantity": total_remain_quantity,
                    "remain_weight": int(total_remain_weight),
                    "remain_percent": remain_percent,
                    "steward_and_guild": all_num,
                    "len_kill_req_not_complete": len(tomorrow_kill_request_not_assigment),
                    "quantity_kill_req_not_complete": all_kill_req_quantity_not_assigment,
                    "weight_kill_req_not_complete": int(all_kill_req_weight_not_assigment),
                    "len_hasnt_code": hasnt_code,
                    "percent_hasnt_code": percent_hasnt_code,
                    "len_has_code": has_code,
                    "percent_has_code": percent_has_code,
                    "has_assignment": has_assignment,
                    "percent_has_assignment": percent_has_assignment,
                    "accepeted_bar": accepeted_bar,
                    "percent_accepeted_bar": percent_accepeted_bar,
                    "diffrent_bar": diffrent_bar,
                    "percent_diffrent_bar": percent_diffrent_bar,
                    "no_quality": no_quality,
                    "percent_no_quality": percent_no_quality,
                    "low_quality": low_quality,
                    "percent_low_quality": percent_low_quality,
                    "hasnt_assignment": hasnt_assignment,
                    "percent_hasnt_assignment": percent_hasnt_assignment,

                }
                list1.append(dict_1)
        return list1

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

        tomorrow_date1 = date1 + timedelta(days=1)
        tomorrow_date2 = date2 + timedelta(days=1)

        filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False,
                                                             kill_request__recive_date__date__gte=date1,
                                                             kill_request__recive_date__date__lte=date2,
                                                             ).order_by(
            '-create_date').select_related(
            'killhouse_user', 'province_request__poultry_request',
            'province_request__poultry_request__poultry').only(
            'killhouse_user',
            'kill_request__slaughter_house',
            'kill_request__slaughter_house__name',
            'province_request__poultry_request__poultry',
            'province_request__poultry_request__send_date',
            'province_kill_request__province_request__poultry_request__Index_weight',
            'quantity',
            'accepted_real_weight',
            'accepted_real_quantity',
            'province_request__poultry_request__send_date',
            'province_request__poultry_request__hatching__date',
            'ware_house_accepted_real_weight',
            'ware_house_accepted_real_quantity',
            'killhouse_user__kill_house_operator__user__city__name')

        kill_free_info = KillHouseFreeBarInformation.objects.filter(trash=False, date__date__gte=tomorrow_date1,
                                                                    date__date__lte=tomorrow_date2).only(
            'weight_of_carcasses', 'number_of_carcasses')
        kill_request = self.all_kill_request(date1, date2)
        general_broadcast_informations = self.general_broadcast_information(tomorrow_date1, tomorrow_date2,
                                                                            filtered_kill_reqs, kill_free_info)
        kill_request_and_broadcasts = self.kill_request_and_broadcast(tomorrow_date1, tomorrow_date2,
                                                                      filtered_kill_reqs, kill_free_info)

        return Response({
            "all_kill_request": kill_request,
            "general_broadcast_informations": general_broadcast_informations,
            "kill_request_and_broadcast": kill_request_and_broadcasts
        }
        )


class DetailOfKillingDashboardView(viewsets.ViewSet):
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardEnterLoadInformationFilterSet

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()

        date1 = datetime.strptime(request.GET['date1'],
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(request.GET['date2'],
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        value = request.GET.get('value')
        search = request.GET.get('search')
        if request.GET.get('type') == 'assignment':
            filtered_kill_request = KillHouseRequest.objects.filter(
                trash=False,
                calculate_status=True,
                non_receipt=False,
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2, assignment_state_archive='True').order_by(
                '-create_date').select_related(
                'killhouse_user',
                'province_request__poultry_request',
                'add_car__driver',
            ).only('province_request', 'province_request__poultry_request',

                   'province_request__poultry_request__send_date',
                   'province_kill_request__province_request__poultry_request__Index_weight',
                   'clearance_code',
                   'quantity',
                   'accepted_real_weight',
                   'accepted_real_quantity',
                   'vet_state', 'vet_accepted_real_quantity',
                   'vet_accepted_real_weight', 'quarantine_quantity',
                   'province_request__poultry_request__hatching__date',
                   'province_request__poultry_request__send_date').values(
                'province_request',
                'province_request__poultry_request',

                'province_request__poultry_request__send_date',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )
        else:

            filtered_kill_request = KillHouseRequest.objects.filter(
                trash=False,
                calculate_status=True,
                non_receipt=False,
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2).order_by(
                '-create_date').select_related(
                'killhouse_user',
                'province_request__poultry_request',
                'add_car__driver',
            ).only('province_request', 'province_request__poultry_request',

                   'province_request__poultry_request__send_date',
                   'province_kill_request__province_request__poultry_request__Index_weight',
                   'clearance_code',
                   'quantity',
                   'accepted_real_weight',
                   'accepted_real_quantity',
                   'vet_state', 'vet_accepted_real_quantity',
                   'vet_accepted_real_weight', 'quarantine_quantity',
                   'province_request__poultry_request__hatching__date',
                   'province_request__poultry_request__send_date').values(
                'province_request',
                'province_request__poultry_request',

                'province_request__poultry_request__send_date',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )

        user = SystemUserProfile.objects.get(user=request.user)
        if request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(trash=False, user=user)
            filtered_kill_request = filtered_kill_request.filter(
                province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
        elif request.GET['role'] == 'VetFarm':
            vet = Vet.objects.filter(user=user, trash=False).last()
            if vet:
                poultry_set = set()
                vet_farms = VetFarm.objects.filter(vet=vet, trash=False)
                for vet_farm in vet_farms:
                    poultry_set.add(vet_farm.poultry)
                poultries = list(poultry_set)
                filtered_kill_request = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__in=poultries
                )


        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            filtered_kill_request = filtered_kill_request.filter(
                province_request__poultry_request__poultry__address__city=user.city)
        elif request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()

            filtered_kill_request = filtered_kill_request.filter(
                killhouse_user=kill_house)
        elif request.GET['role'] == 'KillHouseVet':
            kill_house = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house')
            filtered_kill_request = filtered_kill_request.filter(
                (Q(killhouse_user__id__in=kill_house) | Q(kill_request__slaughter_house__id__in=kill_house)))
        else:
            if request.GET.get('without_quarantine_code_state') == 'true':
                filtered_kill_request = filtered_kill_request.filter(
                    clearance_code__isnull=False,
                    quarantine_quantity__isnull=True,
                    quarantine_code_state__isnull=True,
                )
            elif request.GET.get('without_bar_document') == "true":
                filtered_kill_request = filtered_kill_request.filter(
                    assignment_state_archive='True',
                    bar_document_status__isnull=True,
                )
            else:
                filtered_kill_request = filtered_kill_request

        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                filtered_kill_request = filtered_kill_request.filter(
                    build_query(self.filterset_class, value)
                )

        ware_house_bars = filtered_kill_request.filter(ware_house_confirmation=True)
        ware_house_bars_quantity = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_quantity'))[
                                       'total'] or 0
        ware_house_bars_weight = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_weight'))[
                                     'total'] or 0

        ware_house_bars_weight_lose = ware_house_bars.aggregate(total=Sum('weight_loss'))[
                                          'total'] or 0
        bar_complete_with_kill_house = filtered_kill_request.filter(
            assignment_state_archive='True')

        accepted_real_wight_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        accepted_real_quantity_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity', 0) or 0
        detail_of_killing = DetailOfKillingViewSet()
        bars = dict(list(detail_of_killing.get_kill_house_for_detail(filtered_kill_request).items())[3:])
        dict1 = {**bars,
                 'len_complete_with_vet': 0,
                 'quantity_complete_with_vet': 0,
                 'weight_complete_with_vet': 0,
                 'ware_house_bars': len(ware_house_bars),
                 'ware_house_bars_quantity': ware_house_bars_quantity,
                 'ware_house_bars_weight': ware_house_bars_weight,
                 'ware_house_bars_weight_lose': ware_house_bars_weight_lose / len(
                     ware_house_bars) if ware_house_bars else 0,
                 'len_complete_with_kill_house': len(bar_complete_with_kill_house),
                 'quantity_final_kill_house': accepted_real_quantity_final,
                 'weight_final_kill_house': int(accepted_real_wight_final),

                 }
        return Response(dict1)


class ParentCompanyDetailOfKillingDashboardView(viewsets.ViewSet):
    permission_classes = [AllowAny]
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardEnterLoadInformationFilterSet

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()

        date1 = datetime.strptime(request.GET['date1'],
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(request.GET['date2'],
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        value = request.GET.get('value')
        search = request.GET.get('search')
        if request.GET.get('type') == 'assignment':
            filtered_kill_request = KillHouseRequest.objects.filter(
                trash=False,
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2, assignment_state_archive='True').order_by(
                '-create_date').select_related(
                'killhouse_user',
                'province_request__poultry_request',
                'add_car__driver',
            ).only('province_request', 'province_request__poultry_request',

                   'province_request__poultry_request__send_date',
                   'province_kill_request__province_request__poultry_request__Index_weight',
                   'clearance_code',
                   'quantity',
                   'accepted_real_weight',
                   'accepted_real_quantity',
                   'vet_state', 'vet_accepted_real_quantity',
                   'vet_accepted_real_weight', 'quarantine_quantity',
                   'province_request__poultry_request__hatching__date',
                   'province_request__poultry_request__send_date').values(
                'province_request',
                'province_request__poultry_request',

                'province_request__poultry_request__send_date',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )
        else:

            filtered_kill_request = KillHouseRequest.objects.filter(
                trash=False,
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2).order_by(
                '-create_date').select_related(
                'killhouse_user',
                'province_request__poultry_request',
                'add_car__driver',
            ).only('province_request', 'province_request__poultry_request',

                   'province_request__poultry_request__send_date',
                   'province_kill_request__province_request__poultry_request__Index_weight',
                   'clearance_code',
                   'quantity',
                   'accepted_real_weight',
                   'accepted_real_quantity',
                   'vet_state', 'vet_accepted_real_quantity',
                   'vet_accepted_real_weight', 'quarantine_quantity',
                   'province_request__poultry_request__hatching__date',
                   'province_request__poultry_request__send_date').values(
                'province_request',
                'province_request__poultry_request',

                'province_request__poultry_request__send_date',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )

        if request.GET.get('without_quarantine_code_state') == 'true':
            filtered_kill_request = filtered_kill_request.filter(
                clearance_code__isnull=False,
                quarantine_quantity__isnull=True,
                quarantine_code_state__isnull=True,
            )
        elif request.GET.get('without_bar_document') == "true":
            filtered_kill_request = filtered_kill_request.filter(
                assignment_state_archive='True',
                bar_document_status__isnull=True,
            )
        else:
            filtered_kill_request = filtered_kill_request

        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                filtered_kill_request = filtered_kill_request.filter(
                    build_query(self.filterset_class, value)
                )

        ware_house_bars = filtered_kill_request.filter(ware_house_confirmation=True)
        ware_house_bars_quantity = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_quantity'))[
                                       'total'] or 0
        ware_house_bars_weight = ware_house_bars.aggregate(total=Sum('ware_house_accepted_real_weight'))[
                                     'total'] or 0

        ware_house_bars_weight_lose = ware_house_bars.aggregate(total=Sum('weight_loss'))[
                                          'total'] or 0
        bar_complete_with_kill_house = filtered_kill_request.filter(
            assignment_state_archive='True')

        accepted_real_wight_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        accepted_real_quantity_final = bar_complete_with_kill_house.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity', 0) or 0

        detail_of_killing = DetailOfKillingViewSet()
        bars = dict(list(detail_of_killing.get_kill_house_for_detail(filtered_kill_request).items())[3:])
        dict1 = {**bars,
                 'len_complete_with_vet': 0,
                 'quantity_complete_with_vet': 0,
                 'weight_complete_with_vet': 0,
                 'ware_house_bars': len(ware_house_bars),
                 'ware_house_bars_quantity': ware_house_bars_quantity,
                 'ware_house_bars_weight': ware_house_bars_weight,
                 'ware_house_bars_weight_lose': ware_house_bars_weight_lose / len(
                     ware_house_bars) if ware_house_bars else 0,
                 'len_complete_with_kill_house': len(bar_complete_with_kill_house),
                 'quantity_final_kill_house': accepted_real_quantity_final,
                 'weight_final_kill_house': int(accepted_real_wight_final),

                 }
        return Response(dict1)


class SlaughterHouseTransactionViewSet(viewsets.ModelViewSet):
    queryset = SlaughterHouseTransaction.objects.all()
    serializer_class = SlaughterHouseTransactionSerializer
    permission_classes = [TokenHasReadWriteScope]


class KillHouseWageDashbordInWeightViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseWageSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if request.GET['role'] == 'KillHouse':
            kill_house_operator = KillHouseOperator.objects.get(user=user)
            kill_houses = KillHouse.objects.filter(kill_house_operator=kill_house_operator, out_province=False,
                                                   trash=False)
            # kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator,out_province=False,trash=False).first()
            # serializer = self.serializer_class(kill_house)

        else:
            kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
        serializer = self.serializer_class(kill_houses, many=True)

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


class TotalWageInformationExclusiveKillerViewset(viewsets.ModelViewSet):
    queryset = KillRequest.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = TotalWageInformationKillHouseExclusiveKillerSerializer

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user)
        kill_house_key = request.GET.get('kill_house_key')
        if kill_house_key:
            kill_house = KillHouse.objects.filter(key=kill_house_key, trash=False).first()
        else:

            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        serializer = self.serializer_class(kill_house).data
        return Response(serializer, status=status.HTTP_200_OK)


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

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

        if 'order_code' in request.GET:
            poultry_request = PoultryRequest.objects.get(order_code=int(request.GET['order_code']), trash=False)
            serializer = PoultryRequestLetterForProvinceVetSerializer(poultry_request)
        else:
            date = 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 = PoultryRequestLetterForProvinceVetSerializer(poultry_requests, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ProvinceRequestLetterForProvinceViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseLetterForProvinceSerializer
    permission_classes = [AllowAny]

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

        province_kill_requests = ProvinceKillRequest.objects.filter(kill_request__recive_date__date=date, trash=False,
                                                                    state__in=('pending', 'accepted'),
                                                                    return_to_province=False)
        kill_houses = KillHouse.objects.filter(pk__in=province_kill_requests.values_list('killhouse_user', flat=True))
        serializer = self.serializer_class(kill_houses, many=True, context={'date': date})
        if WageType.objects.filter(en_name='poultry-sell-out-province', status=True).exists():
            poultry_requests = PoultryRequest.objects.filter(send_date__date=date, out=True,
                                                             out_province_request_cancel=False,
                                                             trash=False, state_process='accepted',
                                                             province_state='accepted', wage_pay=True) \
                .select_related('hatching', 'poultry', 'poultry__address__city', 'poultry__address__province',
                                'poultry__user') \
                .order_by('-send_date')
        else:
            poultry_requests = PoultryRequest.objects.filter(send_date__date=date, out=True,
                                                             out_province_request_cancel=False,
                                                             trash=False, state_process='accepted',
                                                             province_state='accepted') \
                .select_related('hatching', 'poultry', 'poultry__address__city', 'poultry__address__province',
                                'poultry__user') \
                .order_by('-send_date')

        poultry_out = PoultryRequestoutProvinceSerializer(poultry_requests, many=True)
        dict1 = {
            'allocation': serializer.data,
            'out_province': poultry_out.data,
        }
        return Response(dict1, status=status.HTTP_200_OK)


class KillHousetestSerializer:
    pass


class KillHouseFortestViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHousetestSerializer
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
        serializer = self.get_serializer(kill_houses, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class DeleteKillHouseRequest(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.filter(trash=False)
    serializer_class = KillHouseRequestSerializer
    permission_classes = [TokenHasReadWriteScope]

    def destroy(self, request, *args, **kwargs):
        kill_house_request = KillHouseRequest.objects.get(trash=False, bar_code=request.GET['bar_code'])
        if kill_house_request.assignment_state_archive == 'True':
            kill_house_assignment = KillHouseAssignmentInformation.objects.get(kill_house_request=kill_house_request)
            kill_house_assignment.trash = True
            kill_house_assignment.save()

        kill_house_request.trash = True
        kill_house_request.save()
        update_kill_house_requests(kill_house_request.province_kill_request,
                                   kill_house_request.province_request.poultry_request)
        update_province_kill_requests(kill_house_request.province_request.poultry_request.hatching)
        poultry_prediction(kill_house_request.province_request.poultry_request.hatching)

        if kill_house_request.ware_house_confirmation == True:
            product = RolesProducts.objects.filter(trash=False, kill_house=kill_house_request.killhouse_user).first()
            kill_house_requests_product_warehousing(product)

        return Response({'result': 'Success'}, status=status.HTTP_200_OK)


class DashboardEnterLoadInformationView(viewsets.ViewSet):
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardEnterLoadInformationFilterSet

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        date1 = datetime.strptime(request.GET['date1'],
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(request.GET['date2'],
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        value = request.GET.get('value')
        search = request.GET.get('search')
        user = SystemUserProfile.objects.get(user=request.user)
        kill_house = []
        if request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)

        elif request.GET['role'] == 'KillHouseVet':
            kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
            for kill_house_vet in kill_house_vets:
                kill_house.append(kill_house_vet.kill_house)

        else:
            kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False)

        if request.GET['role'] in ['CityOperator', 'CityJahad', 'CityPoultry']:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                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,
                    assignment_state_archive='pending',
                    non_receipt=False,
                    trash=False, province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

                ).order_by('-kill_request__recive_date')
            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,
                    assignment_state_archive='pending',
                    non_receipt=False,
                    trash=False, province_request__poultry_request__poultry__address__city=user.city

                ).order_by('-kill_request__recive_date')

        else:

            kill_house_requests = KillHouseRequest.objects.filter(
                (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                    killer__in=kill_house)),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                assignment_state_archive='pending',
                non_receipt=False,
                trash=False,

            ).order_by('-kill_request__recive_date')

        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                kill_house_requests = kill_house_requests.filter(
                    build_query(self.filterset_class, value)
                )

        first_quantity = kill_house_requests.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0

        first_weight = kill_house_requests.aggregate(
            total_quantity=Sum(F('province_request__poultry_request__Index_weight') * F('quantity'))).get(
            'total_quantity') or 0
        vet_accepted_real_quantity = kill_house_requests.aggregate(
            total_quantity=Sum('vet_accepted_real_quantity')).get(
            'total_quantity') or 0
        vet_accepted_real_weight = kill_house_requests.aggregate(
            total_quantity=Sum('vet_accepted_real_weight')).get(
            'total_quantity') or 0

        dict1 = {
            "lenKillHouseRequest": len(kill_house_requests),
            'firstQuantity': first_quantity,
            'firstWeight': int(first_weight),
            'vetAcceptedRealQuantity': vet_accepted_real_quantity,
            'vetAcceptedRealWeight': vet_accepted_real_weight,
        }
        return Response(dict1)


class DashboardDeleteBarView(viewsets.ViewSet):
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardEnterLoadInformationFilterSet

    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        date1 = datetime.strptime(request.GET['date1'],
                                  '%Y-%m-%d').date() if 'date1' in request.GET else now
        date2 = datetime.strptime(request.GET['date2'],
                                  '%Y-%m-%d').date() if 'date2' in request.GET else now
        value = request.GET.get('value')
        search = request.GET.get('search')
        user = SystemUserProfile.objects.get(user=request.user)
        kill_house_requests_list = KillHouseRequest.objects.filter(
            kill_request__recive_date__date__gte=date1,
            kill_request__recive_date__date__lte=date2, trash=True, temporary_trash=False,
            temporary_deleted=False).select_related('kill_request')
        if request.GET['role'] == 'VetSupervisor':
            kill_house_requests_list = kill_house_requests_list.filter(
                province_request__poultry_request__poultry__address__province=user.province,

            )

        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)

                kill_house_requests_list = kill_house_requests_list.filter(
                    province_request__poultry_request__poultry__in=poultries,
                ).select_related('kill_request')

        elif request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user)
            kill_house_requests_list = kill_house_requests_list.filter(
                province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

            ).select_related('kill_request')

        elif request.GET['role'] in ['CityCommerce', 'CityVet', 'CityJahad', 'CityPoultry']:
            kill_house_requests_list = kill_house_requests_list.filter(

                province_request__poultry_request__poultry__address__city=user.city,

            ).select_related('kill_request')

        elif request.GET['role'] == 'LiveStockSupport':
            kill_house_requests_list = kill_house_requests_list.filter(

                province_request__poultry_request__freezing=True,

            ).select_related('kill_request')

        elif request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)

            kill_house_requests_list = kill_house_requests_list.filter(
                (Q(killhouse_user__in=kill_house) | Q(
                    kill_request__slaughter_house__in=kill_house) | Q(killer__in=kill_house)),

                province_request__poultry_request__poultry__address__province=user.province,
            ).select_related('kill_request')

        else:
            kill_house_requests_list = kill_house_requests_list.filter(

                province_request__poultry_request__poultry__address__province=user.province,
            ).select_related('kill_request')

        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                kill_house_requests_list = kill_house_requests_list.filter(
                    build_query(self.filterset_class, value)
                )

        first_quantity = kill_house_requests_list.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0

        first_weight = kill_house_requests_list.aggregate(
            total_quantity=Sum(F('province_request__poultry_request__Index_weight') * F('quantity'))).get(
            'total_quantity') or 0
        len_has_code = len(kill_house_requests_list.filter(clearance_code__isnull=False))
        len_hasnt_code = len(kill_house_requests_list.filter(clearance_code__isnull=True))
        kill_house = kill_house_requests_list.values_list('kill_request__kill_house', flat=True).distinct()

        dict1 = {
            "lenKillHouseRequest": len(kill_house_requests_list),
            'firstQuantity': first_quantity,
            'firstWeight': int(first_weight),
            'lenHasCode': len_has_code,
            'lenHasntCode': len_hasnt_code,
            'lenKillHouse': len(kill_house),
        }
        return Response(dict1)


class DahsnoardProvinceKillRequestViewSet(viewsets.ModelViewSet):
    queryset = ProvinceKillRequest.objects.all()
    serializer_class = ProvinceKillRequestSerializer
    permission_classes = [TokenHasReadWriteScope]
    filterset_class = ProvinceKillRequestNewFilterSet

    # تابع مربوط به نمایش  تخصیصات به کشتارگاها توسط استان
    def list(self, request, *args, **kwargs):
        now = datetime.now().date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)

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

            kill_house = KillHouse.objects.filter(kill_house_operator__user=user,
                                                  trash=False)

            trash = True if 'deleted_object' in request.GET else False
            province_kill_requests = ProvinceKillRequest.objects.filter(Q(killhouse_user__in=kill_house) | Q(
                kill_request__slaughter_house__in=kill_house),
                                                                        trash=trash,
                                                                        delete_message__isnull=False if trash else True,
                                                                        kill_request__recive_date__date__gte=date1,
                                                                        kill_request__recive_date__date__lte=date2,
                                                                        temporary_trash=False, temporary_deleted=False,
                                                                        ).select_related(
                'province_request__poultry_request').order_by(
                'province_request__city_request_Poultry__poultry_request__send_date')
        else:
            trash = True if 'deleted_object' in request.GET else False
            province_kill_requests = ProvinceKillRequest.objects.filter(
                province_request__city_request_Poultry__poultry_request__poultry__user__province=user.province,
                trash=trash,
                delete_message__isnull=False if trash else True,
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2, temporary_trash=False, temporary_deleted=False,
            ).select_related(
                'province_request__poultry_request__poultry',
                'province_request__city_request_Poultry__poultry_request__poultry__user',
                'province_request__city_request_Poultry__poultry_request__poultry__user__city',
                'kill_request__kill_house',
                'kill_request__kill_house__kill_house_operator__user',
                'kill_request__kill_house__system_address__city'
            ).order_by('province_request__poultry_request__send_date')
        if 'allocated_car_state' in request.GET:
            province_kill_requests = province_kill_requests.filter(first_car_allocated_quantity=0)
        value = request.GET.get('value')
        search = request.GET.get('filter')
        if value and search == 'search':
            if value != 'undefined' and value.strip():
                province_kill_requests = province_kill_requests.filter(
                    build_query(self.filterset_class, value)
                )
        kill_requests = KillHouseRequest.objects.filter(province_kill_request__in=province_kill_requests, trash=False)
        accepted_province_kill_requests = province_kill_requests.filter(state='accepted')
        pending_province_kill_requests = province_kill_requests.filter(state='pending')
        rejected_province_kill_requests = province_kill_requests.filter(state='rejected')

        quantity = province_kill_requests.aggregate(
            total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity') or 0
        weight = province_kill_requests.aggregate(
            total_quantity=Sum('total_killed_weight')).get(
            'total_quantity') or 0

        accepted_quantity = accepted_province_kill_requests.aggregate(
            total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity') or 0
        pending_quantity = pending_province_kill_requests.aggregate(
            total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity') or 0
        rejected_quantity = rejected_province_kill_requests.aggregate(
            total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity') or 0
        has_car = province_kill_requests.filter(first_car_allocated_quantity__gt=0)
        has_car_quantity = has_car.aggregate(
            total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity') or 0
        has_car_weight = has_car.aggregate(
            total_quantity=Sum('total_killed_weight')).get(
            'total_quantity') or 0
        hasnt_car = province_kill_requests.filter(first_car_allocated_quantity=0)
        hasnt_car_quantity = hasnt_car.aggregate(
            total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity') or 0
        hasnt_car_weight = hasnt_car.aggregate(
            total_quantity=Sum('total_killed_weight')).get(
            'total_quantity') or 0
        real_quantity = kill_requests.aggregate(
            total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        real_weight = kill_requests.aggregate(
            total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        internal_dict_infos = {
            "lenProvinceRequest": len(province_kill_requests),
            "quantity": quantity,
            "weight": int(weight),
            "acceptedProvinceKillRequests": len(accepted_province_kill_requests),
            "acceptedProvinceKillRequestsQuantity": accepted_quantity,
            "pendingProvinceKillRequests": len(pending_province_kill_requests),
            "pendingProvinceKillRequestsQuantity": pending_quantity,
            "rejectedProvinceKillRequests": len(rejected_province_kill_requests),
            "rejectedProvinceKillRequestsQuantity": rejected_quantity,
            "lenHasCar": len(has_car),
            "hasCarQuantity": has_car_quantity,
            "hasCarWeight": has_car_weight,
            "lenKillRequests": len(kill_requests),
            "realQuantity": real_quantity,
            "realWeight": real_weight,
            "lenHasntCar": len(hasnt_car),
            "hasntCarQuantity": hasnt_car_quantity,
            "hasntCarWeight": hasnt_car_weight,
        }

        return Response(internal_dict_infos, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.data['role']
        request.data.pop('role')
        if 'type' in request.data.keys():
            if request.data['type'] == 'archive':
                user_fullname = user.fullname
                date = str(datetime.now())
                archive_province_kill_request_wage_threading = threading.Thread(
                    target=provincearchiveprovincekillrequestforwage,
                    args=(
                        request.data['province_kill_request_list'], request.data['message'], role, user_fullname, date
                    ))
                archive_province_kill_request_wage_threading.start()
                return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)


            elif request.data['type'] == 'return_archive':
                user_fullname = user.fullname
                date = str(datetime.now().date())
                province_kill_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'])
                province_kill_request.archive_by_province = False
                if 'return_archive_message' in request.data.keys():
                    province_kill_request.return_archive_message = request.data['return_archive_message']
                province_kill_request.returner = {
                    "fullname": user_fullname,
                    "date": date,
                    "role": role
                }
                province_kill_request.save()
                return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)


        else:

            province_kill_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'])
            if province_kill_request.prev_total_amount == None:
                province_kill_request.prev_total_amount = province_kill_request.total_amount
            province_kill_request.total_amount_editor = {
                "role": role,
                "fullname": user.fullname,
                "mobile": user.mobile,
                "date": str(datetime.now())
            }
            province_kill_request.save()
            serializer = self.serializer_class(province_kill_request)
            serializer.update(instance=province_kill_request, validated_data=request.data)
            return Response(serializer.data, status=status.HTTP_200_OK)

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

        if 'delete_allocation' in request.GET:
            province_kill_request = ProvinceKillRequest.objects.get(key=request.GET['province_kill_request_key'],
                                                                    trash=False)
            if province_kill_request.quantity != province_kill_request.main_quantity:
                return Response({"result": "برای تخصیص ماشین ثبت شده امکان حذف وجود ندارد!"},
                                status=status.HTTP_403_FORBIDDEN)

            poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key,
                                                         trash=False)
            province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)

            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
            if poultry_request.export == True:
                hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
                hatching.export_killed_quantity -= int(request.data['quantity'])
            elif poultry_request.free_sale_in_province == True:
                hatching.free_killed_quantity -= province_kill_request.total_killed_weight
                # hatching.free_killed_quantity -= int(province_kill_request.main_quantity * poultry_request.Index_weight)
                hatching.free_quantity -= province_kill_request.total_killed_quantity
                # hatching.free_quantity -= province_kill_request.main_quantity
            else:
                hatching.governmental_killed_quantity -= province_kill_request.total_killed_weight
                # hatching.governmental_killed_quantity -= int(
                #     province_kill_request.main_quantity * poultry_request.Index_weight)

                hatching.governmental_quantity -= province_kill_request.total_killed_quantity
                # hatching.governmental_quantity -= province_kill_request.main_quantity
            # hatching.killed_quantity -= province_kill_request.main_quantity
            hatching.save()

            if poultry_request.remain_quantity > 0:
                # province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity
                poultry_request.save()
            else:

                # province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity
                poultry_request.save()
                # poultry_request.quantity -= province_kill_request.quantity
                # poultry_request.first_quantity -= province_kill_request.quantity
                # poultry_request.previous_quantity -= province_kill_request.quantity
                # poultry_request.save()
                # if poultry_request.quantity == 0:
                # poultry_request.trash = True
                # poultry_request.save()
                # hatching.left_over += province_kill_request.quantity
                # hatching.state = 'pending'
                # hatching.allow_hatching = 'pending'
                # hatching.save()
            kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
            kill_request.remain_quantity += province_kill_request.main_quantity
            kill_request.save()
            province_kill_request.delete_message = request.GET['message']
            province_kill_request.trash = True
            province_kill_request.save()
            return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
        elif 'return_allocation_quantity' in request.GET:

            province_kill_request = ProvinceKillRequest.objects.get(key=request.GET['province_kill_request_key'],
                                                                    trash=False)
            if province_kill_request.quantity == 0:
                return Response({"result": "باقی مانده تخصیص صفر است امکان بازگشت تعداد وجود ندارد"},
                                status=status.HTTP_403_FORBIDDEN)
            amount = province_kill_request.quantity

            poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key,
                                                         trash=False)
            hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)

            if province_kill_request.main_quantity - province_kill_request.quantity == 0:
                province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity
                poultry_request.save()
                # kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
                # kill_request.remain_quantity += province_kill_request.main_quantity
                # kill_request.save()
                if poultry_request.export == True:
                    hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
                    hatching.export_killed_quantity -= int(request.data['quantity'])
                elif poultry_request.free_sale_in_province == True:
                    hatching.free_killed_quantity -= province_kill_request.total_killed_weight
                    # hatching.free_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.free_quantity -= province_kill_request.total_killed_quantity
                    # hatching.free_quantity -= amount
                else:
                    hatching.governmental_killed_quantity -= province_kill_request.total_killed_weight
                    # hatching.governmental_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.governmental_quantity -= province_kill_request.total_killed_quantity
                    # hatching.governmental_quantity -= amount
                # hatching.killed_quantity -= amount
                hatching.save()
                # province_kill_request.trash = True
                province_kill_request.quantity = 0
                province_kill_request.total_killed_quantity = 0
                province_kill_request.total_killed_weight = 0
                province_kill_request.return_to_province = True
                province_kill_request.save()
            else:

                province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
                province_check.quantity += province_kill_request.main_quantity - province_kill_request.quantity
                province_check.save()
                poultry_request.remain_quantity += province_kill_request.main_quantity - province_kill_request.quantity
                poultry_request.save()
                # kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
                # kill_request.remain_quantity += province_kill_request.main_quantity - province_kill_request.quantity
                # kill_request.save()
                if poultry_request.export == True:
                    hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
                    hatching.export_killed_quantity -= int(request.data['quantity'])
                elif poultry_request.free_sale_in_province == True:
                    hatching.free_killed_quantity -= int((
                                                                 province_kill_request.main_quantity - province_kill_request.quantity) * poultry_request.Index_weight)
                    # hatching.free_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.free_quantity -= province_kill_request.total_killed_quantity
                    # hatching.free_quantity -= amount
                else:
                    hatching.governmental_killed_quantity -= int((
                                                                         province_kill_request.main_quantity - province_kill_request.quantity) * poultry_request.Index_weight)
                    # hatching.governmental_killed_quantity -= int(amount * poultry_request.Index_weight)
                    hatching.governmental_quantity -= province_kill_request.main_quantity - province_kill_request.quantity
                    # hatching.governmental_quantity -= amount
                # hatching.killed_quantity -= amount
                hatching.save()
                province_kill_request.main_quantity = province_kill_request.main_quantity - province_kill_request.quantity
                province_kill_request.quantity = 0
                province_kill_request.save()
            return Response({"result": "با موفقیت انجام شد"}, status=status.HTTP_200_OK)
        queryset = ProvinceKillRequest.objects.get(key=request.GET['key'])
        poultry_request = PoultryRequest.objects.get(key=queryset.province_request.poultry_request.key)
        hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
        check = KillHouseCheckRequest.objects.filter(province_kill_request=queryset, state='accepted')
        if check.count() > 0:
            return Response({"result": "can not delete"}, status=status.HTTP_403_FORBIDDEN)
        province = ProvinceCheckOperatorRequest.objects.get(key=queryset.province_request.key)
        province.quantity += queryset.quantity
        province.save()
        kill_request = KillRequest.objects.get(key=queryset.kill_request.key)
        kill_request.remain_quantity += queryset.quantity
        kill_request.save()
        # queryset.delete()
        poultry_request.remain_quantity += queryset.quantity
        poultry_request.save()
        if poultry_request.export == True:
            hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
            hatching.export_killed_quantity -= int(request.data['quantity'])
        elif poultry_request.free_sale_in_province == True:
            hatching.free_killed_quantity -= queryset.total_killed_weight
            # hatching.free_killed_quantity -= int(queryset.quantity * poultry_request.Index_weight)
            hatching.free_quantity -= queryset.total_killed_quantity
        else:
            hatching.governmental_killed_quantity -= queryset.total_killed_weight
            # hatching.governmental_killed_quantity -= int(
            #     queryset.quantity * poultry_request.Index_weight)
            hatching.governmental_quantity -= queryset.total_killed_quantity
        # hatching.killed_quantity -= queryset.total_killed_quantity
        hatching.save()
        queryset.delete()

        return Response(status=status.HTTP_200_OK)


class DashboardKillHouseFreeBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeBarInformation.objects.all()
    serializer_class = KillHouseFreeBarInformationSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardKillHouseFreeBarInformationFilterSet

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        if date1:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        type = request.GET['type']
        if request.GET['role'] in ['KillHouse', 'KillHouseVet']:
            if request.GET['role'] == 'KillHouse':
                kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
            else:
                kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                      flat=True)
                kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)

            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                Q(kill_house__in=kill_houses) | Q(exclusive_killer__in=kill_houses) | Q(public_killer__in=kill_houses),
                buy_type=type,
                calculate_status=True,
                temporary_trash=False,
                temporary_deleted=False,
                trash=False).order_by('-date')
        else:
            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                buy_type=type,
                calculate_status=True,
                temporary_trash=False,
                temporary_deleted=False,
                trash=False).order_by('-date')

        if date1:
            kill_house_free_bar_info = kill_house_free_bar_info.filter(register_date__date__gte=date1,
                                                                       register_date__date__lte=date2)

        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                kill_house_free_bar_info = kill_house_free_bar_info.filter(
                    build_query(self.filterset_class, value)
                )
        quantity = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0
        live_weight = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('live_weight')).get(
            'total_quantity') or 0
        number_of_carcasses = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('number_of_carcasses')).get(
            'total_quantity') or 0
        weight_of_carcasses = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('weight_of_carcasses')).get(
            'total_quantity') or 0
        if type == 'live':
            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

            entered_quantity = entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            entered_live_weight = entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            entered_number_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            entered_weight_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

            not_entered_quantity = not_entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            not_entered_live_weight = not_entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            not_entered_number_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            not_entered_weight_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            result = {
                'total_bars': len(kill_house_free_bar_info),
                'total_bars_quantity': quantity,
                'total_bars_live_Weight': live_weight,
                'total_bars_numberOfCarcasses': number_of_carcasses,
                'total_bars_weightOfCarcasses': weight_of_carcasses,

                'entered_total_bars': len(entered_bars),
                'entered_total_bars_quantity': entered_quantity,
                'entered_total_bars_live_Weight': entered_live_weight,
                'entered_total_bars_numberOfCarcasses': entered_number_of_carcasses,
                'entered_total_bars_weightOfCarcasses': entered_weight_of_carcasses,

                'not_entered_total_bars': len(not_entered_bars),
                'not_entered_total_bars_quantity': not_entered_quantity,
                'not_entered_total_bars_live_Weight': not_entered_live_weight,
                'not_entered_total_bars_numberOfCarcasses': not_entered_number_of_carcasses,
                'not_entered_total_bars_weightOfCarcasses': not_entered_weight_of_carcasses,

            }
        else:
            result = {
                'total_bars': len(kill_house_free_bar_info),
                'total_bars_quantity': quantity,
                'total_bars_live_Weight': live_weight,
                'total_bars_numberOfCarcasses': number_of_carcasses,
                'total_bars_weightOfCarcasses': weight_of_carcasses,
            }
        return Response(result, status=status.HTTP_200_OK)


class ParentCopmanyDashboardKillHouseFreeBarInformationViewSet(viewsets.ModelViewSet):
    queryset = KillHouseFreeBarInformation.objects.all()
    serializer_class = KillHouseFreeBarInformationSerializer
    permission_classes = [AllowAny]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardKillHouseFreeBarInformationFilterSet

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

        type = request.GET['type']

        kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
            buy_type=type,
            trash=False).order_by('-date')
        quantity = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('quantity')).get(
            'total_quantity') or 0
        live_weight = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('live_weight')).get(
            'total_quantity') or 0
        number_of_carcasses = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('number_of_carcasses')).get(
            'total_quantity') or 0
        weight_of_carcasses = kill_house_free_bar_info.aggregate(
            total_quantity=Sum('weight_of_carcasses')).get(
            'total_quantity') or 0
        if type == 'live':
            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

            entered_quantity = entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            entered_live_weight = entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            entered_number_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            entered_weight_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

            not_entered_quantity = not_entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            not_entered_live_weight = not_entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            not_entered_number_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            not_entered_weight_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            result = {
                'total_bars': len(kill_house_free_bar_info),
                'total_bars_quantity': quantity,
                'total_bars_live_Weight': live_weight,
                'total_bars_numberOfCarcasses': number_of_carcasses,
                'total_bars_weightOfCarcasses': weight_of_carcasses,

                'entered_total_bars': len(entered_bars),
                'entered_total_bars_quantity': entered_quantity,
                'entered_total_bars_live_Weight': entered_live_weight,
                'entered_total_bars_numberOfCarcasses': entered_number_of_carcasses,
                'entered_total_bars_weightOfCarcasses': entered_weight_of_carcasses,

                'not_entered_total_bars': len(not_entered_bars),
                'not_entered_total_bars_quantity': not_entered_quantity,
                'not_entered_total_bars_live_Weight': not_entered_live_weight,
                'not_entered_total_bars_numberOfCarcasses': not_entered_number_of_carcasses,
                'not_entered_total_bars_weightOfCarcasses': not_entered_weight_of_carcasses,

            }
        else:
            result = {
                'total_bars': len(kill_house_free_bar_info),
                'total_bars_quantity': quantity,
                'total_bars_live_Weight': live_weight,
                'total_bars_numberOfCarcasses': number_of_carcasses,
                'total_bars_weightOfCarcasses': weight_of_carcasses,
            }
        return Response(result, status=status.HTTP_200_OK)


class DashboardKillRequestViewSet(viewsets.ModelViewSet):
    queryset = KillRequest.objects.all()
    serializer_class = KillHouseFreeBarInformationSerializer
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = DashboardKillRequestFilterSet

    def list(self, request, *args, **kwargs):
        value = request.GET.get('value')
        search = request.GET.get('search')
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        querysets = KillRequest.objects.filter(
            recive_date__date__gte=date1,
            recive_date__date__lte=date2, poultry__isnull=False,
            trash=False).order_by(
            'recive_date')
        if request.GET['role'] == 'KillHouse':
            kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)
            querysets = querysets.filter(kill_house__in=kill_house).order_by('recive_date')
        elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX']:
            if 'direct_buying' in request.GET:
                querysets = querysets.filter(market=False,
                                             final_accept=True,
                                             direct_buying_state__in=(
                                                 'accepted', 'rejected', 'deleted', 'pending'),
                                             export_status=False, trash=False
                                             )
            if 'export' in request.GET:
                if request.GET['type'] == 'pending':
                    querysets = querysets.filter(export_status=True,
                                                 export_state='pending'
                                                 )
                else:
                    querysets = querysets.filter(export_status=True,
                                                 export_state__in=(
                                                     'accepted', 'rejected', 'deleted'),
                                                 )

        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                querysets = querysets.filter(
                    build_query(self.filterset_class, value)
                )
        quantity = querysets.aggregate(
            total_quantity=Sum('kill_capacity')).get(
            'total_quantity') or 0
        free_direct_buying_true_quantity = querysets.aggregate(
            total_quantity=Sum('kill_capacity', filter=Q(free_direct_buying=True))).get(
            'total_quantity') or 0
        free_direct_buying_false_quantity = querysets.aggregate(
            total_quantity=Sum('kill_capacity', filter=Q(free_direct_buying=False))).get(
            'total_quantity') or 0
        left_over = querysets.aggregate(
            total_quantity=Sum('remain_quantity')).get(
            'total_quantity') or 0
        amount = querysets.aggregate(
            total_quantity=Avg('amount')).get(
            'total_quantity') or 0
        index_wight = querysets.aggregate(
            total_quantity=Avg('Index_weight')).get(
            'total_quantity') or 0
        dict1 = {
            'lenKillRequest': querysets.count(),
            'lenKillRequestHasFreeDirectBuying': querysets.filter(free_direct_buying=True).count(),
            'lenKillRequestHasntFreeDirectBuying': querysets.filter(free_direct_buying=False).count(),
            'quantity': quantity,
            'leftOver': left_over,
            'remainQuantity': quantity - left_over,
            'amount': amount,
            'indexWight': index_wight,
            'freeDirectBuyingTrueQuantity': free_direct_buying_true_quantity,
            'freeDirectBuyingFalseQuantity': free_direct_buying_false_quantity,

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


class InputBarsForKillHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForInputBarsSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

    def list(self, request, *args, **kwargs):
        quota = request.GET.get('quota')
        if quota == 'governmental':
            quota_filter = {'province_request__poultry_request__free_sale_in_province': False}
        elif quota == 'free':
            quota_filter = {'province_request__poultry_request__free_sale_in_province': True}
        else:
            quota_filter = None
        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 'date1' in request.GET and request.GET['date1']:

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

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

            if request.GET['type'] == 'entered':

                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date')
            else:

                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    ware_house_confirmation=False, non_receipt=False, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date')
        else:

            if request.GET['type'] == 'entered':
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date')
            else:

                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    ware_house_confirmation=False, non_receipt=False, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date')

        if quota_filter:
            kill_house_requests = kill_house_requests.filter(**quota_filter)

        if 'search' in request.GET:
            kill_house_requests_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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_requests_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_requests_list) == 0 else kill_house_requests_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(kill_house_requests)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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


class InputBarsForKillHouseDashboardViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForInputBarsSerializer
    permission_classes = [TokenHasReadWriteScope]

    def list(self, request, *args, **kwargs):
        role = request.GET.get('role')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        if role in ('Steward', 'Guild'):
            guild = Guilds.objects.get(user=user, active=True, trash=False)
            if 'date1' in request.GET:
                date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                allocations = StewardAllocation.objects.filter(
                    Q(to_steward=guild) | Q(to_guilds=guild), date__date__gte=date1, date__date__lte=date2,
                    trash=False, calculate_status=True, system_registration_code=True)
            else:
                allocations = StewardAllocation.objects.filter(
                    Q(to_steward=guild) | Q(to_guilds=guild),
                    trash=False, calculate_status=True, system_registration_code=True)
            entered_allocations = allocations.filter(receiver_state='accepted')
            not_entered_allocations = allocations.filter(receiver_state='pending')
            rejected_allocations = allocations.filter(receiver_state='rejected')
            total_allocations_quantity = allocations.filter(receiver_state__in=('pending', 'accepted')).aggregate(
                total=Sum('real_number_of_carcasses'))[
                                             'total'] or 0
            total_allocations_weight = allocations.filter(receiver_state__in=('pending', 'accepted')).aggregate(
                total=Sum('real_weight_of_carcasses'))[
                                           'total'] or 0
            total_entered_allocations_quantity = \
                entered_allocations.aggregate(total=Sum('real_number_of_carcasses'))['total'] or 0
            total_entered_allocations_weight = \
                entered_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0
            total_not_entered_allocations_quantity = \
                not_entered_allocations.aggregate(total=Sum('real_number_of_carcasses'))['total'] or 0
            total_not_entered_allocations_weight = \
                not_entered_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0

            total_rejected_allocations_quantity = \
                rejected_allocations.aggregate(total=Sum('real_number_of_carcasses'))['total'] or 0
            total_rejected_allocations_weight = \
                rejected_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0

            result = {
                "total_bars": len(allocations),
                "total_bars_quantity": total_allocations_quantity,
                "total_bars_weight": total_allocations_weight,
                "total_entered_bars": len(entered_allocations),
                "total_entered_bars_quantity": total_entered_allocations_quantity,
                "total_entered_bars_weight": total_entered_allocations_weight,
                "total_not_entered_bars": len(not_entered_allocations),
                "total_not_entered_bars_quantity": total_not_entered_allocations_quantity,
                "total_not_entered_kill_house_requests_weight": total_not_entered_allocations_weight,
                "total_rejected_bars": len(rejected_allocations),
                "total_rejected_bars_quantity": total_rejected_allocations_quantity,
                "total_rejected_bars_weight": total_rejected_allocations_weight,
            }

        else:
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
                'system_address__province').first()

            kill_house_requests = KillHouseRequest.objects.filter(
                Q(killhouse_user=kill_house) | Q(killer=kill_house),
                trash=False, calculate_status=True).order_by('-kill_request__recive_date')
            entered_kill_house_requests = kill_house_requests.filter(ware_house_confirmation=True)
            not_entered_kill_house_requests = kill_house_requests.filter(ware_house_confirmation=False)
            total_kill_house_requests_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[
                                                     'total'] or 0
            total_kill_house_requests_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                                                   'total'] or 0
            total_entered_kill_house_requests_quantity = \
                entered_kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
            total_entered_kill_house_requests_weight = \
                entered_kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0
            total_entered_kill_house_requests_carcasses = \
                entered_kill_house_requests.aggregate(total=Sum('ware_house_accepted_real_quantity'))['total'] or 0
            total_entered_kill_house_requests_carcasses_weight = \
                entered_kill_house_requests.aggregate(total=Sum('ware_house_accepted_real_weight'))['total'] or 0
            total_not_entered_kill_house_requests_quantity = \
                not_entered_kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))['total'] or 0
            total_not_entered_kill_house_requests_weight = \
                not_entered_kill_house_requests.aggregate(total=Sum('accepted_real_weight'))['total'] or 0

            result = {
                "total_bars": len(kill_house_requests),
                "total_bars_quantity": total_kill_house_requests_quantity,
                "total_bars_weight": total_kill_house_requests_weight,
                "total_entered_bars": len(entered_kill_house_requests),
                "total_entered_bars_quantity": total_entered_kill_house_requests_quantity,
                "total_entered_bars_weight": total_entered_kill_house_requests_weight,
                "total_entered_bars_carcasses": total_entered_kill_house_requests_carcasses,
                "total_entered_bars_carcasses_weight": total_entered_kill_house_requests_carcasses_weight,
                "total_not_entered_bars": len(not_entered_kill_house_requests),
                "total_not_entered_bars_quantity": total_not_entered_kill_house_requests_quantity,
                "total_not_entered_kill_house_requests_weight": total_not_entered_kill_house_requests_weight,
            }

        return Response(result, status=status.HTTP_200_OK)


class BarDifferenceRequestViewSet(viewsets.ModelViewSet):
    queryset = BarDifferenceRequest.objects.all()
    serializer_class = BarDifferenceRequestSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = BarDifferenceRequestFilterSet
    filterset_fields = [
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__mobile',
        'hatching__poultry__user__fullname',
        'hatching__poultry__user__mobile'
    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        role = request.GET.get('role')
        state = request.GET.get('state')
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        filters = {
            'trash': False,
        }
        if role == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
                'system_address__province').first()
            filters['kill_house'] = kill_house
        if state == 'pending':
            filters['state'] = 'pending'
        else:
            filters['state__in'] = ('accepted', 'rejected')

        if date1:
            filters['create_date__date__gte'] = date1
            filters['create_date__date__lte'] = date2

        bar_requests = BarDifferenceRequest.objects.filter(**filters).order_by('-id')

        if 'search' in request.GET:
            bar_requests_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=bar_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=bar_requests)
                            bar_requests_list = ps.filter()
                    bar_requests = [] if len(bar_requests_list) == 0 else bar_requests_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(bar_requests)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        hatching = PoultryHatching.objects.get(key=request.data['hatching_key'], trash=False)
        kill_house = KillHouse.objects.get(key=request.data['kill_house_key'], trash=False)
        images = None
        acceptor_images = None
        request.data.pop('hatching_key')
        request.data.pop('kill_house_key')
        if 'images' in request.data.keys():
            images = request.data['images']
            request.data.pop('images')

        if 'acceptor_images' in request.data.keys():
            acceptor_images = request.data['acceptor_images']
            request.data.pop('acceptor_images')
        image_list = []
        acceptor_image_list = []
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            bar_request = serializer.create(validated_data=request.data)
            bar_request.hatching = hatching
            bar_request.kill_house = kill_house
            bar_request.register_fullname = user.fullname
            bar_request.register_mobile = user.mobile
            bar_request.weight = int(bar_request.quantity) * bar_request.hatching.poultry.real_killing_ave_weight

            if images != None:
                for image in images:
                    image_list.append(send_image_to_server(image))

                bar_request.violation_image = image_list

            if acceptor_images != None:
                for acceptor_image in acceptor_images:
                    acceptor_image_list.append(send_image_to_server(acceptor_image))

                bar_request.acceptor_image = acceptor_image_list

            bar_request.save()
            send_sms_for_bar_difference_request(kill_house.kill_house_operator.user.mobile, request.data['quantity'],
                                                hatching.poultry.unit_name)
            send_ticket_for_bar_difference_request(user, kill_house.kill_house_operator.user, request.data['quantity'],
                                                   hatching.poultry.unit_name)
            serializer_request = self.serializer_class(bar_request)
            return Response(serializer_request.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    def update(self, request, pk=None, *args, **kwargs):
        bar_request = BarDifferenceRequest.objects.get(key=request.data['bar_key'])
        request.data.pop('bar_key')
        if 'kill_house_check' in request.data.keys():
            request.data.pop('kill_house_check')
            if request.data['state'] == 'accepted':
                user = SystemUserProfile.objects.get(user=request.user, trash=False)
                bar_request.acceptor_fullname = user.fullname
                bar_request.acceptor_mobile = user.mobile
                bar_request.acceptor_date = datetime.now()
                # bar_request.weight = bar_request.quantity * bar_request.hatching.poultry.real_killing_ave_weight
                bar_request.hatching.bar_difference_request_quantity += bar_request.quantity
                bar_request.hatching.bar_difference_request_weight += bar_request.weight
                bar_request.hatching.save()
                bar_request.save()

        if 'images' in request.data.keys():
            images = request.data['images']
            request.data.pop('images')
            image_list = []
            if images != None:
                for image in images:
                    image_list.append(send_image_to_server(image))

                bar_request.violation_image = image_list
        if 'acceptor_images' in request.data.keys():
            acceptor_images = request.data['acceptor_images']
            request.data.pop('acceptor_images')
            acceptor_images_list = []
            if acceptor_images != None:
                for acceptor_image in acceptor_images:
                    acceptor_images_list.append(send_image_to_server(acceptor_image))

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

    def destroy(self, request, pk=None, *args, **kwargs):
        bar_request = BarDifferenceRequest.objects.get(key=request.GET['bar_key'], trash=False)
        if bar_request.state == 'accepted':
            bar_request.hatching.bar_difference_request_quantity -= bar_request.quantity
            bar_request.hatching.bar_difference_request_weight -= bar_request.weight
            bar_request.hatching.save()
        bar_request.trash = True
        bar_request.save()
        return Response({"result": "با موفقیت حذف شد."},
                        status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def get_hatching_kill_ingo(request):
    hatching = PoultryHatching.objects.get(key=request.GET['hatching_key'])
    kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'])

    total_quantity = 0
    total_weight = 0
    Province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house, trash=False,
                                                                state__in=('pending', 'accepted'),
                                                                return_to_province=False,
                                                                province_request__poultry_request__hatching=hatching)
    first_total_quantity = \
        Province_kill_requests.aggregate(total=Sum('main_quantity'))[
            'total'] or 0

    total_quantity = \
        Province_kill_requests.aggregate(total=Sum('total_killed_quantity'))[
            'total'] or 0
    total_weight = \
        Province_kill_requests.aggregate(total=Sum('total_killed_weight'))[
            'total'] or 0

    difference_quantity = first_total_quantity - total_quantity
    # kill_house_requests = KillHouseRequest.objects.filter(Q(killhouse_user=obj.kill_house) | Q(killer=obj.kill_house),trash=False,
    #                                                       province_request__poultry_request__hatching=obj.hatching)
    #
    #
    # total_quantity +=\
    # kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[
    #     'total'] or 0
    # total_weight +=\
    # kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
    #     'total'] or 0

    result = {
        "first_total_quantity": first_total_quantity,
        "total_quantity": total_quantity,
        "difference_quantity": difference_quantity,
        "total_weight": total_weight,
    }

    return Response(result,
                    status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def dashboard_monitoring_bar_and_killing(request):
    now = datetime.now().date()
    date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else now
    date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date1' in request.GET else now
    kill_house_free_bar = KillHouseFreeBarInformation.objects.filter(Q(date__date__gte=date1,
                                                                       date__date__lte=date2,
                                                                       buy_type='carcass') | Q(
        create_date__date__gte=date1, create_date__date__lte=date2, buy_type='live'),
                                                                     trash=False,
                                                                     archive_wage=False,
                                                                     ).only(
        'quantity',
        'live_weight',
        'number_of_carcasses',
        'weight_of_carcasses',
        'send_date',
        'type',
        'out'
    )

    kill_house_free_bar_aggregates = kill_house_free_bar.aggregate(
        total_quantity_live=Sum('quantity', filter=Q(buy_type='live')),
        total_weight_live=Sum('live_weight', filter=Q(buy_type='live')),
        total_count=Count('id', filter=Q(buy_type='live')),
        total_weight=Sum('weight_of_carcasses', filter=Q(buy_type='live')),
        total_count_carcass=Count('id', filter=Q(buy_type='carcass')),
        total_weight_carcass=Sum('weight_of_carcasses', filter=Q(buy_type='carcass')),
        total_quantity_carcass=Sum('number_of_carcasses', filter=Q(buy_type='carcass')),

    )

    if kill_house_free_bar_aggregates['total_quantity_live'] != 0:
        ratio = round(
            ((kill_house_free_bar_aggregates['total_weight_live'] or 0) / (
                    kill_house_free_bar_aggregates['total_quantity_live']
                    or 0))
            , 1) if (kill_house_free_bar_aggregates['total_quantity_live'] or 0) > 0 else 0
    else:
        ratio = 0

    province_kill_request = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                               wage_pay=False,
                                                               archive_wage=False,
                                                               return_to_province=False,
                                                               trash=False,
                                                               kill_request__recive_date__date__gte=date1,
                                                               kill_request__recive_date__date__lte=date2). \
        select_related('province_request__poultry_request').only(
        'total_killed_quantity',
        'province_request__poultry_request__Index_weight',
    )

    province_kill_request_aggregates = province_kill_request.aggregate(
        total_count=Count('id', filter=Q(first_car_allocated_quantity=0)),
        total_quantity=Sum('total_killed_quantity', filter=Q(first_car_allocated_quantity=0)),
        total_index_weight=Avg('province_request__poultry_request__Index_weight',
                               filter=Q(first_car_allocated_quantity=0)),
        total_count_new=Count('id'),
        total_quantity_new=Sum('total_killed_quantity'),
        total_weight_new=Sum('total_killed_weight'),
        total_index_weight_new=Avg('province_request__poultry_request__Index_weight'),

    )

    poultry_request = PoultryRequest.objects.filter(
        trash=False,
        state_process__in=('pending', 'accepted'),
        province_state__in=('pending', 'accepted'),
        out_province_request_cancel=False,
        temporary_trash=False,
        temporary_deleted=False, send_date__date__gte=date1,
        send_date__date__lte=date2
    ).only(
        'quantity',
        'Index_weight',
    ).annotate(
        item_weight=F('Index_weight') * F('quantity')
    )

    poultry_request_aggregates = poultry_request.aggregate(
        total_count=Count('id', filter=Q(out=True)),
        total_quantity=Sum('quantity', filter=Q(out=True)),
        total_ave_weight=Avg('Index_weight', filter=Q(out=True)),
        total_weight=Sum('item_weight', filter=Q(out=True)),
        total_count_killing=Count('id'),
        total_quantity_killing=Sum('quantity'),
        total_ave_weight_killing=Avg('Index_weight'),
        total_weight_killing=Sum('item_weight')
    )

    kill_house_request = KillHouseRequest.objects.filter(
        trash=False,
        temporary_trash=False,
        temporary_deleted=False, kill_request__recive_date__date__gte=date1,
        kill_request__recive_date__date__lte=date2
    ).select_related('province_kill_request__province_request__poultry_request__Index_weight').only(
        'quantity',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'accepted_real_weight',
        'accepted_real_quantity',
    )

    kill_house_request_aggregates = kill_house_request.aggregate(
        total_count=Count('id'),
        total_quantity=Sum('accepted_real_quantity'),
        total_quantity_has_quarantine=Sum('accepted_real_quantity', filter=Q(quarantine_quantity__gt=0)),
        total_count_has_quarantine=Count('id', filter=Q(quarantine_quantity__gt=0)),
        total_weight=Sum('accepted_real_weight'),
        total_ave_weight=Avg('province_kill_request__province_request__poultry_request__Index_weight'),
        total_ave_age=Avg('province_kill_request__province_request__poultry_request__hatching__chicken_age'),
        total_quarantine=Count('id', filter=Q(quarantine_quantity__gt=0)),
        total_quarantine_quantity=Sum('quarantine_quantity', filter=Q(quarantine_quantity__gt=0)),
        total_quarantine_discharge_confirmation=Count('id', filter=Q(quarantine_quantity__gt=0,
                                                                     assignment_state_archive='True')),
        total_quarantine_discharge_confirmation_quantity=Sum('accepted_real_quantity',
                                                             filter=Q(quarantine_quantity__gt=0,
                                                                      assignment_state_archive='True')),

    )

    province_request_count = province_kill_request_aggregates['total_count_new'] or 0
    province_request_quantity = province_kill_request_aggregates['total_quantity_new'] or 0
    province_request_weight = province_kill_request_aggregates['total_weight_new'] or 0
    total_free_sell_count = kill_house_free_bar_aggregates['total_count'] or 0
    total_free_sell_quantity = kill_house_free_bar_aggregates['total_quantity_live'] or 0
    total_free_sell_weight = kill_house_free_bar_aggregates['total_weight_live'] or 0
    avgWeight = round(
        (province_request_weight + total_free_sell_weight) / (province_request_quantity + total_free_sell_quantity),
        1) if (province_request_quantity + total_free_sell_quantity) > 0 else 0

    result_dict = {
        'freeLiveBar': {
            'count': kill_house_free_bar_aggregates['total_count'] or 0,
            'quantity': kill_house_free_bar_aggregates['total_quantity_live'] or 0,
            'weight': kill_house_free_bar_aggregates['total_weight_live'] or 0,
            'weightCarcass': kill_house_free_bar_aggregates['total_weight_carcass'] or 0,
            'avgWeight': ratio,
        },
        'provinceKillRequestWithoutBar': {
            'count': province_kill_request_aggregates['total_count'] or 0,
            'quantity': province_kill_request_aggregates['total_quantity'] or 0,
            'indexWeight': round((province_kill_request_aggregates['total_index_weight'] or 0), 1),
        },
        'outLiveBar': {
            'count': poultry_request_aggregates['total_count'] or 0,
            'quantity': poultry_request_aggregates['total_quantity'] or 0,
            'weight': poultry_request_aggregates['total_weight'] or 0,
            'avgWeight': round((poultry_request_aggregates['total_ave_weight'] or 0), 1),

        },
        'bar': {
            'count': kill_house_request_aggregates['total_count'] or 0,
            'count_has_quarantine': kill_house_request_aggregates['total_count_has_quarantine'] or 0,
            'quantity': kill_house_request_aggregates['total_quantity'] or 0,
            'quantity_has_quarantine': kill_house_request_aggregates['total_quantity_has_quarantine'] or 0,
            'weight': kill_house_request_aggregates['total_weight'] or 0,
            'avgWeight': round((kill_house_request_aggregates['total_ave_weight'] or 0), 1),
            'avgAge': int(kill_house_request_aggregates['total_ave_age'] or 0),

            'total_quarantine': kill_house_request_aggregates['total_quarantine'] or 0,
            'total_quarantine_quantity': kill_house_request_aggregates['total_quarantine_quantity'] or 0,
            'total_quarantine_discharge_confirmation': kill_house_request_aggregates[
                                                           'total_quarantine_discharge_confirmation'] or 0,
            'total_quarantine_discharge_confirmation_quantity': kill_house_request_aggregates[
                                                                    'total_quarantine_discharge_confirmation_quantity'] or 0,

        },
        'killingInfo': {
            'count': province_request_count + total_free_sell_count,
            'quantity': province_request_quantity + total_free_sell_quantity,
            'weight': province_request_weight + total_free_sell_weight,
            'avgWeight': avgWeight,
        },
        'buyFreeCarcasses': {
            'count': kill_house_free_bar_aggregates['total_count_carcass'] or 0,
            'quantity': kill_house_free_bar_aggregates['total_quantity_carcass'] or 0,
            'weight': kill_house_free_bar_aggregates['total_weight_carcass'] or 0,
        }

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


@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def dashboarad_bar_for_kill_house(request):
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]
    user = SystemUserProfile.objects.get(user=request.user)
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    kill_house_requests = KillHouseRequest.objects.filter(
        (Q(killhouse_user=kill_house) | Q(
            kill_request__slaughter_house=kill_house) | Q(killer=kill_house)),
        (Q(trash=False) | Q(trash=True, clearance_code__isnull=False, temporary_trash=False,
                            temporary_deleted=False)),

        province_request__poultry_request__poultry__address__province=user.province,
    ).select_related('kill_request')
    if 'date1' in request.GET and 'date2' in request.GET:
        date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        kill_house_requests = kill_house_requests.filter(
            kill_request__recive_date__date__gte=date1,
            kill_request__recive_date__date__lte=date2)

    if 'search' in request.GET:
        kill_house_request_list = []
        if request.GET['search'] == 'filter':
            if request.GET['value'] != "" and request.GET['value'] != 'undefined':
                for item in filterset_fields:
                    query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                    if (filterset_class(
                            data=query,
                            queryset=kill_house_requests
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=kill_house_requests)
                        kill_house_request_list = ps.filter()
                kill_house_requests = [] if len(kill_house_request_list) == 0 else kill_house_request_list
    kill_house_requests_aggregate = kill_house_requests.aggregate(
        first_quantity=Sum('quantity'),
        first_weight=Sum('quantity') * Avg('province_request__poultry_request__Index_weight'),
        first_index_weight=Avg('province_request__poultry_request__Index_weight'),
        accepted_real_quantity=Sum('accepted_real_quantity'),
        accepted_real_weight=Sum('accepted_real_weight'),
        assignment_state_archive_pending=Count('id', filter=Q(assignment_state_archive='pending')),
        assignment_state_archive_accepted=Count('id', filter=Q(assignment_state_archive='accepted')),
        clearance_code_count=Count('id', filter=Q(clearance_code__isnull=False)),

    )

    result_dict = {
        'count': kill_house_requests.count(),
        'firstQuantity': kill_house_requests_aggregate['first_quantity'] or 0,
        'firstWeight': int(kill_house_requests_aggregate['first_weight'] or 0),
        'firstIndexWeight': round((kill_house_requests_aggregate['first_index_weight'] or 0), 1),
        'acceptedRealQuantity': kill_house_requests_aggregate['accepted_real_quantity'] or 0,
        'acceptedRealWeight': int(kill_house_requests_aggregate['accepted_real_weight'] or 0),
        'finalIndexWeight': round((kill_house_requests_aggregate['accepted_real_weight'] or 0) /
                                  (kill_house_requests_aggregate['accepted_real_quantity'] or 0), 1)
        if (kill_house_requests_aggregate['accepted_real_quantity'] or 0) > 0 else 0,
        'assignmentStateArchivePending': kill_house_requests_aggregate['assignment_state_archive_pending'] or 0,
        'assignmentStateArchiveAccepted': kill_house_requests_aggregate['assignment_state_archive_accepted'] or 0,
        'clearanceCodeCount': kill_house_requests_aggregate['clearance_code_count'] or 0,

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


@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def dashboard_bar_difference_request(request):
    filterset_class = BarDifferenceRequestFilterSet
    filterset_fields = [
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__mobile',
        'hatching__poultry__user__fullname',
        'hatching__poultry__user__mobile'
    ]
    user = SystemUserProfile.objects.get(user=request.user, trash=False)
    # if request.GET['role'] == 'KillHouse':
    #     kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
    #         'system_address__province').first()
    #     if request.GET['state'] == 'pending':
    #         bar_requests = BarDifferenceRequest.objects.filter(kill_house=kill_house, trash=False,
    #                                                            state='pending').order_by('id')
    #     else:
    #         bar_requests = BarDifferenceRequest.objects.filter(kill_house=kill_house, trash=False,
    #                                                            state__in=('accepted', 'rejected')).order_by('id')
    # else:
    #     if request.GET['state'] == 'pending':
    #         bar_requests = BarDifferenceRequest.objects.filter(trash=False, state='pending').order_by('id')
    #     else:
    #         bar_requests = BarDifferenceRequest.objects.filter(trash=False,
    #                                                            state__in=('accepted', 'rejected')).order_by('id')

    role = request.GET.get('role')
    state = request.GET.get('state')
    date1 = request.GET.get('date1')
    date2 = request.GET.get('date2')
    filters = {
        'trash': False,
    }
    if role == 'KillHouse':
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
            'system_address__province').first()
        filters['kill_house'] = kill_house
    if state == 'pending':
        filters['state'] = 'pending'
    else:
        filters['state__in'] = ('accepted', 'rejected')

    if date1:
        filters['create_date__date__gte'] = date1
        filters['create_date__date__lte'] = date2

    bar_requests = BarDifferenceRequest.objects.filter(**filters).order_by('-id')

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

    serializer = BarDifferenceRequestSerializer(bar_requests, many=True)

    bar_info_list = [item['bar_info'] for item in serializer.data]

    difference_quantity = sum(item["first_total_quantity"] for item in bar_info_list) - \
                          sum(item["total_quantity"] for item in bar_info_list)

    bar_requests_aggregate = bar_requests.aggregate(
        count=Count('id'),
        weight=Sum('weight'),
        quantity=Sum('quantity'),
    )

    result_dict = {
        'count': bar_requests_aggregate['count'] or 0,
        'weight': bar_requests_aggregate['weight'] or 0,
        'quantity': bar_requests_aggregate['quantity'] or 0,
        "firstTotalQuantity": sum(item["first_total_quantity"] for item in bar_info_list),
        "totalQuantity": sum(item["total_quantity"] for item in bar_info_list),
        "differenceQuantity": difference_quantity,
        "totalWeight": sum(item["total_weight"] for item in bar_info_list),
    }

    return Response(result_dict, status=status.HTTP_200_OK)


class KillHousePerformanceDashboardViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list(
            'kill_house', flat=True)
        kill_houses = KillHouse.objects.filter(out_province=False, trash=False).exclude(id__in=kill_house_ids).order_by(
            'id')

        serializer = KillHouseForPerformanceDashboardSerializer(kill_houses, many=True,
                                                                context={'date1': date1, 'date2': date2, })
        return Response(serializer.data, status=status.HTTP_200_OK)


class NonReceiptKillHouseRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestForBarManagementSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

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

        elif request.GET['role'] == 'KillHouseVet':
            kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
            for kill_house_vet in kill_house_vets:
                kill_house.append(kill_house_vet.kill_house)

        else:
            kill_house = KillHouse.objects.filter(system_address__province=user.province, trash=False)

        if request.GET['role'] in ['CityOperator', 'CityJahad', 'CityPoultry']:
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(user=user, trash=False)
                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,
                    main_non_receipt=True,
                    non_receipt=True,
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

                ).order_by('-kill_request__recive_date')
            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,
                    main_non_receipt=True,
                    non_receipt=True,
                    province_request__poultry_request__poultry__address__city=user.city

                ).order_by('-kill_request__recive_date')

        else:

            kill_house_requests = KillHouseRequest.objects.filter(
                (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                    killer__in=kill_house)),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                main_non_receipt=True,
                non_receipt=True

            ).order_by('-kill_request__recive_date')

        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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_requests_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_requests_list) == 0 else kill_house_requests_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(kill_house_requests)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def update(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        now = datetime.now()
        role = request.data.get('role')
        message = request.data.get('message')
        state = request.data.get('state')
        key = request.data.get('key')
        kill_house_request = KillHouseRequest.objects.get(key=key)
        if kill_house_request.assignment_state_archive == 'True':
            return Response({"result": "به دلیل وارد کردن اطلاعات بار امکان ثبت عدم وصول وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

        kill_house_request.non_receipt_state = state
        kill_house_request.message = message
        kill_house_request.bar_remover = {
            "full_name": user.fullname,
            "role": role,
            "mobile": user.mobile,
            "date": str(now)
        }
        kill_house_request.trash = True if state == 'accepted' else False
        kill_house_request.save()
        if state == 'accepted':
            update_kill_house_requests(kill_house_request.province_kill_request,
                                       kill_house_request.province_request.poultry_request)
            update_province_kill_requests(kill_house_request.province_request.poultry_request.hatching)

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


class ReturnNonReceiptKillHouseRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseRequestForBarManagementSerializer

    def update(self, request, *args, **kwargs):
        key = request.data.get('key')
        kill_house_request = KillHouseRequest.objects.get(key=key)
        trash = kill_house_request.trash
        if kill_house_request.non_receipt_return:
            return Response({"result": "عدم وصول برای این بار قبلا ثبت و لغو گردیده!"})
        kill_house_request.trash = False
        kill_house_request.non_receipt = request.data['non_receipt']
        kill_house_request.non_receipt_return = request.data['non_receipt_return']
        kill_house_request.non_receipt_return_message = request.data['non_receipt_return_message']
        kill_house_request.save()
        if trash:
            update_kill_house_requests(kill_house_request.province_kill_request,
                                       kill_house_request.province_request.poultry_request)
            update_province_kill_requests(kill_house_request.province_request.poultry_request.hatching)

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


class DirectBuyingPaymentViewSet(viewsets.ModelViewSet):
    queryset = DirectBuyingPayment.objects.all()
    serializer_class = DirectBuyingPaymentSerializer
    permission_classes = [TokenHasReadWriteScope]
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = DirectBuyingPaymentFilterSet
    filterset_fields = [

        'province_kill_request__kill_request__kill_house__name',
        'province_kill_request__kill_request__kill_house__kill_house_operator__user__fullname',
        'province_kill_request__kill_request__kill_house__kill_house_operator__user__first_name',
        'province_kill_request__kill_request__kill_house__kill_house_operator__user__last_name',
        'province_kill_request__kill_request__kill_house__kill_house_operator__user__mobile',

    ]

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        province_kill_request = ProvinceKillRequest.objects.get(key=request.data['province_kill_request_key'])
        now = datetime.now()
        image = request.data.pop('image', None)
        request.data.pop('province_kill_request_key')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            payment = serializer.create(validated_data=request.data)
            payment.province_kill_request = province_kill_request
            payment.date = now
            payment.payment_registrar = user.fullname
            payment.payment_registrar_mobile = user.mobile
            payment.image = send_image_to_server(image)
            payment.save()

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

    def list(self, request, *args, **kwargs):
        province_kill_request = ProvinceKillRequest.objects.get(key=request.GET['province_kill_request_key'])
        filter = {'trash': False, 'province_kill_request': province_kill_request}
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        if date1:
            filter['date1'] = datetime.strptime(str(date1), '%Y-%m-%d').date()
            filter['date2'] = datetime.strptime(str(date2), '%Y-%m-%d').date()
        payments = DirectBuyingPayment.objects.filter(**filter)

        if 'search' in request.GET:
            payments_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=payments
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=payments)
                            payments_list = ps.filter()
                    payments = [] if len(
                        payments_list) == 0 else payments_list

        if request.GET.get('page'):

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

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

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

    def update(self, request, pk=None, *args, **kwargs):
        payment = DirectBuyingPayment.objects.get(key=request.data['key'])
        image = request.data.pop('image', None)
        if image:
            payment.image = send_image_to_server(image)
            payment.save()
        serializer = self.serializer_class(payment)
        serializer.update(instance=payment, validated_data=request.data)

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

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


class ProvinceKillRequestDirectBuyingViewSet(viewsets.ModelViewSet):
    queryset = ProvinceKillRequest.objects.all()
    serializer_class = ProvinceKillRequestForDirectBuyingSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = ProvinceKillRequestFilterSet
    filterset_fields = [
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__poultry__address__city__name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',

    ]

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        role = request.GET.get('role')
        state = request.GET.get('status')
        filter = {
            'trash': False,
            'payment_deadline': True,
            'return_to_province': False,
            'payment_deadline_archive': False if state == 'active' else True,
        }
        if date1:
            filter['kill_request__recive_date__date__gte'] = datetime.strptime(date1, '%Y-%m-%d').date()
            filter['kill_request__recive_date__date__lte'] = datetime.strptime(date2, '%Y-%m-%d').date()
        if role == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
            filter['killhouse_user'] = kill_house

        elif role in ('CityJahad', 'CityOperator', 'CityCommerce', 'CityVet', 'CitySupervisor', 'CityPoultry'):
            filter['kill_request__poultry__address__city'] = user.city

        province_kill_requests = ProvinceKillRequest.objects.filter(**filter).select_related('kill_request',
                                                                                             'kill_request__poultry_hatching',
                                                                                             'kill_request__poultry').only(
            'kill_request', 'kill_request__poultry_hatching', 'kill_request__poultry').order_by('payment_deadline_date')

        if 'search' in request.GET:
            province_kill_requests_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=province_kill_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=province_kill_requests)
                            province_kill_requests_list = ps.filter()
                    province_kill_requests = [] if len(
                        province_kill_requests_list) == 0 else province_kill_requests_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(province_kill_requests)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def update(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        province_kill_request = ProvinceKillRequest.objects.get(key=request.data['key'])
        check = request.data.pop('check', None)
        archive = request.data.pop('archive', None)
        if 'final_accept' in request.data.keys():
            role = request.data.pop('role', None)
            if request.data['final_accept'] == True:
                province_kill_request.payment_deadline_state = 'checking' if role == 'KillHouse' else 'accepted'
                province_kill_request.final_accept_registrar = user.fullname
                province_kill_request.final_accept_registrar_mobile = user.mobile
                province_kill_request.final_accept_date = datetime.now()
                if role != 'KillHouse':
                    province_kill_request.payment_deadline_checker_fullname = user.fullname
                    province_kill_request.payment_deadline_checker_mobile = user.mobile
                    province_kill_request.payment_deadline_check_date = datetime.now()
                    province_kill_request.payment_deadline_archive_message = 'تایید و تسویه کامل'
                    province_kill_request.payment_deadline_archive = True
                province_kill_request.save()
        if check:
            state = request.data.pop('state', None)
            province_kill_request.payment_deadline_checker_fullname = user.fullname
            province_kill_request.payment_deadline_checker_mobile = user.mobile
            province_kill_request.payment_deadline_check_date = datetime.now()
            province_kill_request.payment_deadline_archive = True if state == 'accepted' else False
            province_kill_request.payment_deadline_state = state

            if province_kill_request.payment_deadline_state == 'rejected':
                province_kill_request.final_accept = False
        if archive:
            province_kill_request.payment_deadline_checker_fullname = user.fullname
            province_kill_request.payment_deadline_checker_mobile = user.mobile
            province_kill_request.payment_deadline_check_date = datetime.now()
            province_kill_request.payment_deadline_archive = True
            province_kill_request.payment_deadline_state = 'archive'

        if 'extension_payment_deadline_days' in request.data.keys():
            province_kill_request.extension_payment_deadline_date = province_kill_request.payment_deadline_date + timedelta(
                days=request.data['extension_payment_deadline_days'])
            province_kill_request.kill_request.extension_payment_deadline_days = request.data[
                'extension_payment_deadline_days']
            province_kill_request.kill_request.extension_payment_deadline_date = province_kill_request.extension_payment_deadline_date
            province_kill_request.kill_request.save()

        province_kill_request.save()
        serializer = self.serializer_class(province_kill_request)
        serializer.update(instance=province_kill_request, validated_data=request.data)

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


class MarketKillRequestViewSet(viewsets.ModelViewSet):
    queryset = KillRequest.objects.all()
    serializer_class = KillRequestForDirectBuyingSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillRequestFilterSet
    filterset_fields = [
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'poultry_request__chicken_breed',
        'poultry_request__order_code',
        'poultry_request__poultry__address__city__name',
        'poultry_request__poultry__user__mobile',
        'poultry_request__poultry__user__fullname',

    ]

    def calculate_province_kill_request_wage(self, kill_request):
        province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=kill_request.poultry_request)

        wage_type = WageType.objects.filter(en_name='province-kill-request', trash=False).first()
        wage = wage_type.amount if wage_type.status == True else 0
        percentages_wage_type = PercentageOfWageType.objects.filter(wage_type=wage_type, percent__gt=0,
                                                                    trash=False)
        province_killrequest = ProvinceKillRequest(
            killhouse_user=kill_request.kill_house,
            kill_request=kill_request,
            province_request=province_check,
            quantity=kill_request.kill_capacity,
            total_killed_quantity=kill_request.kill_capacity,
            total_killed_weight=int(kill_request.kill_capacity * kill_request.poultry_request.Index_weight),
            main_quantity=kill_request.kill_capacity,
            wage=wage,
            market=True,
            payment_deadline=True,
            payment_deadline_days=kill_request.payment_deadline_days,
            payment_deadline_date=kill_request.payment_deadline_date,
            state='accepted',
            kill_house_price=kill_request.amount,
            total_wage_amount=wage * int(kill_request.kill_capacity * kill_request.poultry_request.Index_weight),
        )
        province_killrequest.save()
        kill_house_check = KillHouseCheckRequest(
            province_kill_request=province_killrequest,
            state='accepted'
        )

        kill_house_check.save()
        vet_farm = VetFarm.objects.filter(trash=False,
                                          poultry=province_killrequest.province_request.poultry_request.poultry).first()
        bot_eitaa_for_each_province_kill_request(province_killrequest, vet_farm)
        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':
                    province_killrequest.union_share = int(
                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                    province_killrequest.union_share_percent = percentage_wage_type.percent

                elif percentage_wage_type.share_type.en_name == 'company':
                    province_killrequest.company_share = int(
                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                    province_killrequest.company_share_percent = percentage_wage_type.percent

                elif percentage_wage_type.share_type.en_name == 'guilds':
                    province_killrequest.guilds_share = int(
                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                    province_killrequest.guilds_share_percent = percentage_wage_type.percent

                elif percentage_wage_type.share_type.en_name == 'city':
                    province_killrequest.city_share = int(
                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                    province_killrequest.city_share_percent = percentage_wage_type.percent

                elif percentage_wage_type.share_type.en_name == 'other':
                    province_killrequest.other_share = int(
                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                    province_killrequest.other_share_percent = percentage_wage_type.percent

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

                else:
                    province_killrequest.other_share = int(
                        (percentage_wage_type.percent / 100) * province_killrequest.total_wage_amount)
                    province_killrequest.other_share_percent = percentage_wage_type.percent
                province_killrequest.save()

    def create(self, request, *args, **kwargs):
        total_unpaid_wage = 0
        total_paid_wage = 0
        user = SystemUserProfile.objects.get(trash=False, user=request.user)
        now = datetime.now()
        kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list(
            'kill_house', flat=True)
        kill_houses = KillHouse.objects.filter(out_province=False, market_buying=True, trash=False).exclude(
            id__in=kill_house_ids).order_by('id', 'killer')
        kill_house_for_killer = None
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()

        if kill_house.ware_house_remaining_weight_limitation_status:
            if kill_house.total_remain_warehouse_governmental_weight > kill_house.ware_house_remaining_weight_limitation:
                return Response({
                    "result": "باقی مانده انبار شما از حداکثر محدودیت وزن باقی مانده انبار بیشتر است !"},
                    status=status.HTTP_403_FORBIDDEN)

        if kill_house.ware_house_remaining_percent_limitation_status:
            if not check_kill_house_remain_limitation_weight(kill_house):
                return Response({
                    "result": "باقی مانده انبار شما از حداکثر محدودیت وزن باقی مانده روزانه انبار بیشتر است !"},
                    status=status.HTTP_403_FORBIDDEN)
        with transaction.atomic():
            poultry_request = PoultryRequest.objects.select_for_update().get(key=request.data['poultry_request_key'])
            if poultry_request.free_sale_in_province == True:

                if kill_house.quota:
                    kill_house_info = calculate_governmental_quota(kill_house)
                    if kill_house_info == 'not_allowed':
                        return Response({"result": " امکان خرید آزاد تا تکمیل تعهد دولتی وجود ندارد!"},
                                        status=status.HTTP_403_FORBIDDEN)

            index_weight_category = IndexWeightCategory.objects.filter(trash=False, name='سبک').first()
            light_max_value = index_weight_category.max_value if index_weight_category else 0
            if kill_house.market_buying_limitation:
                kill_house_info = market_kill_request_share_quantity(kill_house, total_kill_houses=kill_houses)
                kill_house_share = kill_house_info['kill_house_today_share']
                kill_house_buying = kill_house_info['kill_house_market_kill_requests_quantity'] + request.data[
                    'kill_capacity']
                if kill_house.market_light_capacity:
                    total_remain_light_weight = kill_house_info['total_remain_poultry_requests_quantity_light_weight']
                    kill_house_market_kill_requests_quantity_light_weight = kill_house_info[
                        'kill_house_market_kill_requests_quantity_light_weight']
                    real_kill_house_market_kill_requests_quantity_light_weight = kill_house_info['light_real_quantity']
                    if poultry_request.Index_weight >= light_max_value:
                        if real_kill_house_market_kill_requests_quantity_light_weight > 0:
                            if total_remain_light_weight > real_kill_house_market_kill_requests_quantity_light_weight:
                                if real_kill_house_market_kill_requests_quantity_light_weight > kill_house_market_kill_requests_quantity_light_weight:
                                    return Response({"result": "الویت با خرید و تکمیل نهایی  سهمیه سبک  می باشد!"},
                                                    status=status.HTTP_403_FORBIDDEN)
                            else:
                                if total_remain_light_weight > kill_house_market_kill_requests_quantity_light_weight:
                                    return Response({"result": "الویت با خرید و تکمیل نهایی  سهمیه سبک  می باشد!"},
                                                    status=status.HTTP_403_FORBIDDEN)

                if kill_house_share - kill_house_buying < 0:
                    return Response({"result": "حجم خریداری شده از سهمیه  شما بیشتر است !"},
                                    status=status.HTTP_403_FORBIDDEN)
            kill_request = KillRequest.objects.filter(trash=False, poultry_request=poultry_request,
                                                      kill_house=kill_house,
                                                      market_final_accept=False).first()
            # if poultry_request.remain_quantity < request.data['kill_capacity']:
            #     return Response({"result": "حجم وارد شده از باقی مانده قابل فروش بیشتر است !"},
            #                     status=status.HTTP_403_FORBIDDEN)
            market_requests_quantity = KillRequest.objects.filter(poultry_request=poultry_request, trash=False,
                                                                  market_state__in=('pending', 'accepted'),
                                                                  market=True).aggregate(
                total=Sum('kill_capacity'))['total'] or 0
            if market_requests_quantity + request.data['kill_capacity'] > poultry_request.quantity:
                return Response({"result": "باقی مانده اعلام نیاز مرغدار کمتر از درخواست شماست!"},
                                status=status.HTTP_403_FORBIDDEN)

            kill_house_purchase = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()
            total_unpaid_wage = get_finance_info(kill_house)['total_price']
            slaughter_transactions = InternalTransaction.objects.filter(
                kill_house=kill_house, status='completed',
                trash=False)

            total_paid_wage += slaughter_transactions.aggregate(total=Sum('amount'))[
                                   'total'] or 0
            if kill_house_purchase.limitation == True:

                if kill_house_purchase.limitation_number <= total_unpaid_wage - total_paid_wage:
                    if not ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
                                                              kill_request__recive_date__date=now.date(),
                                                              trash=False,
                                                              state__in=('pending', 'accepted')).exists():
                        return Response({
                            "result": "به علت بدهی امکان ثبت درخواست وحود ندارد لطفا بدهی خود را در پنل کارمزد ها تسویه کنید"},
                            status=status.HTTP_403_FORBIDDEN)

            if kill_request:
                kill_request.kill_capacity += request.data['kill_capacity']
                kill_request.remain_quantity += request.data['kill_capacity']
                kill_request.save()
                market_poultry_request_remain_quantity(kill_request.poultry_request)
                return Response({"result": "با موفقیت ثبت شد."}, status=status.HTTP_200_OK)
            request.data.pop('poultry_request_key')
            if kill_house.killer and kill_house.type == 'public':
                percentage = KillHousePercentage.objects.filter(trash=False, kill_house=kill_house,
                                                                kill_house_for_killer__isnull=False).first()
                kill_house_for_killer = percentage.kill_house_for_killer
            serializer = self.serializer_class(data=request.data)
            if serializer.is_valid():
                market_kill_request = serializer.create(validated_data=request.data)
                market_kill_request.kill_house = kill_house
                market_kill_request.poultry_request = poultry_request
                market_kill_request.poultry_hatching = poultry_request.hatching
                market_kill_request.poultry = poultry_request.poultry
                market_kill_request.recive_date = now
                market_kill_request.chicken_breed = poultry_request.chicken_breed
                market_kill_request.remain_quantity = market_kill_request.kill_capacity
                market_kill_request.amount = poultry_request.amount
                market_kill_request.Index_weight = poultry_request.Index_weight
                market_kill_request.market = True
                market_kill_request.payment_deadline = True
                if kill_house_for_killer:
                    market_kill_request.slaughter_house = kill_house_for_killer
                market_kill_request.market_expire_date_time = now + timedelta(
                    minutes=30) if market_code_state else now + timedelta(minutes=5)
                if market_code_state:
                    market_kill_request.market_code_status = True
                market_kill_request.payment_deadline_date = datetime.now() + timedelta(
                    days=request.data['payment_deadline_days'])
                market_kill_request.save()
                market_poultry_request_remain_quantity(market_kill_request.poultry_request)
                return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        from django.db.models import Value

        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        now = datetime.now().date()
        role = request.GET.get('role')
        poultry_request_key = request.GET.get('poultry_request_key')
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        # filter = {
        #     'trash': False,
        #     'market': True,
        # }
        filter = {
            'market': True
        }
        if date1:
            filter['recive_date__date__gte'] = date1
            filter['recive_date__date__lte'] = date2

        else:
            filter['recive_date__date'] = now

        if role == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
            filter['kill_house'] = kill_house

        elif role in ('CityJahad', 'CityOperator', 'CityCommerce', 'CityVet', 'CitySupervisor', 'CityPoultry'):
            filter['poultry__address__city'] = user.city
        state_type = request.GET.get('type')

        if state_type and state_type != 'all':
            filter['market_state'] = state_type

        if state_type in ('pending', 'accepted', 'rejected'):
            filter['trash'] = False
        elif state_type == 'deleted':
            filter['trash'] = True

        if poultry_request_key:
            filter['poultry_request__key'] = poultry_request_key

        kill_requests = KillRequest.objects.filter(**filter).select_related('poultry_hatching', 'poultry').only(
            'poultry_hatching', 'poultry').order_by(
            Case(
                When(market_state='pending', then=Value(0)),
                default=Value(1)
            ),
            '-create_date'
        )

        if 'search' in request.GET:
            kill_requests_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=kill_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_requests)
                            kill_requests_list = ps.filter()
                    kill_requests = [] if len(
                        kill_requests_list) == 0 else kill_requests_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(kill_requests)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def update(self, request, pk=None, *args, **kwargs):
        kill_request = KillRequest.objects.get(key=request.data['key'])
        if kill_request.trash:
            return Response({"result": "درخواست شما توسط کاربر حذف گردید!"}, status=status.HTTP_403_FORBIDDEN)

        if 'check' in request.data.keys():
            state = request.data['market_state']
            if state == 'accepted':
                self.calculate_province_kill_request_wage(kill_request)
            request.data.pop('check')

        if 'market_final_accept' in request.data.keys():
            # market_poultry_request_remain_quantity(kill_request.poultry_request)
            poultry_request = kill_request.poultry_request
            # market_requests_quantity = KillRequest.objects.filter(poultry_request=poultry_request, trash=False,
            #                                                       market_state__in=('pending', 'accepted'), market=True,
            #                                                       market_final_accept=True).aggregate(
            #     total=Sum('kill_capacity'))['total'] or 0
            # if market_requests_quantity + kill_request.kill_capacity > poultry_request.quantity:
            #     return Response({"result": "باقی مانده اعلام نیاز مرغدار کمتر از درخواست شماست!"},
            #                     status=status.HTTP_403_FORBIDDEN)
            if market_code_state:
                code = str(random.randint(10000, 99000))
                kill_request.market_code = code
                kill_request.save()
                market_sms = threading.Thread(
                    target=send_sms_fro_kill_request_market,
                    args=(
                        kill_request,))

                market_sms.start()
            kill_request.remain_quantity -= kill_request.kill_capacity
            kill_request.save()
        if 'kill_capacity' in request.data.keys():
            kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list(
                'kill_house', flat=True)
            kill_houses = KillHouse.objects.filter(out_province=False, market_buying=True, trash=False).exclude(
                id__in=kill_house_ids).order_by('id', 'killer')
            if kill_request.kill_house.market_buying_limitation:
                kill_house_info = market_kill_request_share_quantity(kill_request.kill_house,
                                                                     total_kill_houses=kill_houses)
                kill_house_share = kill_house_info['kill_house_today_share']
                kill_house_today_left_share = kill_house_info['kill_house_today_left_share']
                kill_house_buying = kill_house_info['kill_house_market_kill_requests_quantity'] + request.data[
                    'kill_capacity']
                if (kill_house_today_left_share + kill_request.kill_capacity) < request.data['kill_capacity']:
                    return Response({"result": "حجم خریداری شده از سهمیه  شما بیشتر است !"},
                                    status=status.HTTP_403_FORBIDDEN)
            if kill_request.poultry_request.remain_quantity + kill_request.kill_capacity < request.data[
                'kill_capacity']:
                return Response({"result": "حجم وارد شده از باقی مانده قابل فروش بیشتر است !"},
                                status=status.HTTP_403_FORBIDDEN)
            kill_request.remain_quantity = request.data['kill_capacity']
        if 'payment_deadline_days' in request.data.keys():
            kill_request.payment_deadline_date = datetime.now() + timedelta(
                days=request.data['payment_deadline_days'])
        if 'input_market_code' in request.data.keys():
            if request.data['input_market_code'] != kill_request.market_code:
                return Response({"result": "کد وارد شده صحیح نمی باشد!"}, status=status.HTTP_403_FORBIDDEN)
            kill_request.input_market_code = request.data['input_market_code']
            self.calculate_province_kill_request_wage(kill_request)
            kill_request.market_state = 'accepted'
        kill_request.save()
        serializer = self.serializer_class(kill_request)
        serializer.update(instance=kill_request, validated_data=request.data)
        market_poultry_request_remain_quantity(kill_request.poultry_request)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        user = SystemUserProfile.objects.get(trash=False, user=request.user)
        kill_request = KillRequest.objects.get(key=request.GET["key"])
        kill_request.trash = True
        kill_request.market_state_message = {
            "fullname": user.fullname,
            "mobile": user.mobile,
            "date": str(datetime.now())
        }
        kill_request.market_state = 'deleted'
        kill_request.save()
        market_poultry_request_remain_quantity(kill_request.poultry_request)
        return Response(' با موفقیت حذف شد', status=status.HTTP_200_OK)


class MarketKillHouseViewSet(viewsets.ModelViewSet):
    queryset = KillHouse.objects.all()
    serializer_class = KillHouseForCommonlyUsedSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

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

        kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by(
            'id', 'killer')

        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_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(kill_houses)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def update(self, request, pk=None, *args, **kwargs):
        kill_house = KillHouse.objects.get(key=request.data['key'])
        serializer = self.serializer_class(kill_house)
        serializer.update(instance=kill_house, validated_data=request.data)

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


class KillHouseMarketInfoViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseMarketInfoSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        role = request.GET.get('role')
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list(
            'kill_house', flat=True)
        kill_houses = KillHouse.objects.filter(out_province=False, market_buying=True, trash=False).exclude(
            id__in=kill_house_ids).order_by('id', 'killer')
        if role == 'KillHouse':
            user = SystemUserProfile.objects.get(trash=False, user=request.user)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            serializer = self.serializer_class(kill_house,
                                               context={'date1': date1, 'date2': date2, 'kill_houses': kill_houses})

        else:
            if 'search' in request.GET:
                kill_house_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=kill_houses
                            )
                            ).filter():
                                ps = self.filterset_class(data=query, queryset=kill_houses)
                                kill_house_list = ps.filter()
                        kill_houses = [] if len(
                            kill_house_list) == 0 else kill_house_list

            serializer = self.serializer_class(kill_houses, many=True,
                                               context={'date1': date1, 'date2': date2, 'kill_houses': kill_houses})

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


class KillHouseMarketInfoDashboardViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        today = datetime.now().date()
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        if date1:
            total_poultry_requests_quantity = (
                    PoultryRequest.objects.filter(
                        send_date__date__gte=date1,
                        send_date__date__lte=date2,
                        state_process='accepted',
                        province_state='accepted',
                        final_state__in=('pending', 'accepted'),
                        temporary_trash=False,
                        trash=False,
                        out=False,
                        market=True,
                    ).aggregate(total=Sum('quantity'))['total'] or 0
            )

        else:
            total_poultry_requests_quantity = (
                    PoultryRequest.objects.filter(
                        send_date__date=today,
                        state_process='accepted',
                        province_state='accepted',
                        final_state__in=('pending', 'accepted'),
                        temporary_trash=False,
                        trash=False,
                        out=False,
                        market=True,
                    ).aggregate(total=Sum('quantity'))['total'] or 0
            )

        exclusive_kill_house_ids = KillHousePercentage.objects.filter(
            kill_house__type='exclusive',
            trash=False
        ).values_list('kill_house', flat=True)

        kill_houses = KillHouse.objects.filter(
            out_province=False,
            market_buying=True,
            trash=False
        ).exclude(id__in=exclusive_kill_house_ids).order_by('id', 'killer')

        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_list

        dashboard_data = {
            "kill_house_today_share": 0,
            "market_light_share": 0,
            "kill_house_market_kill_requests_quantity": 0,
            "kill_house_market_kill_requests_quantity_first": 0,
            "kill_house_market_kill_requests_quantity_final": 0,
            "kill_house_today_left_share": 0,
            "kill_house_market_kill_requests_quantity_weight": 0,
            "kill_house_market_kill_requests_quantity_first_weight": 0,
            "kill_house_market_kill_requests_quantity_final_weight": 0,
            "total_kill_house_market_kill_requests_quantity_agreement_light_weight": 0,
            "total_kill_house_market_kill_requests_quantity_light_weight": 0,
            "total_kill_house_market_kill_requests_quantity_heavy_weight": 0,
        }

        for kill_house in kill_houses:
            if date1:
                info = market_kill_request_share_quantity(kill_house, date1, date2, total_kill_houses=kill_houses)
            else:
                info = market_kill_request_share_quantity(kill_house, total_kill_houses=kill_houses)
            for key in dashboard_data:
                dashboard_data[key] += info.get(key, 0) or 0

        result = {"total_poultry_requests_quantity": total_poultry_requests_quantity, **dashboard_data}

        return Response(result, status=200)


def make_fine_for_requests_cron():
    now = datetime.now().date()
    fine = FinePermission.objects.filter(trash=False).first()

    province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, temporary_trash=False,
                                                                return_to_province=False,
                                                                kill_request__recive_date__date__lt=now,
                                                                first_car_allocated_quantity=0,
                                                                state__in=('pending', 'accepted')).select_related(
        'province_request__poultry_request__hatching')
    if province_kill_requests:
        for province_kill_request in province_kill_requests:
            hatching = province_kill_request.province_request.poultry_request.hatching
            province_kill_request.fine = True
            province_kill_request.fine_amount = fine.in_province_allocations_fine_coefficient * province_kill_request.total_wage_amount
            province_kill_request.fine_coefficient = fine.in_province_allocations_fine_coefficient
            if province_kill_request.market:
                province_kill_request.kill_request.market_state = 'deleted'
                province_kill_request.kill_request.save()
            province_kill_request.delete_message = "حذف  تخصیص و اعمال جریمه به دلیل عدم ثبت خودرو در بازه مشخص"
            province_kill_request.trash = True
            province_kill_request.save()
            update_province_kill_requests(hatching)

    kill_house_requests = KillHouseRequest.objects.filter(
        Q(assignment_state_archive='pending') | Q(ware_house_confirmation=False), fine=False, trash=False,
        kill_request__recive_date__date__lt=now,
        temporary_trash=False).select_related('province_kill_request', 'province_request__poultry_request',
                                              'province_request__poultry_request__hatching')
    empty_info_bars = kill_house_requests.filter(assignment_state_archive='pending', ware_house_confirmation=False)
    not_completed_bars = kill_house_requests.filter(assignment_state_archive='pending', ware_house_confirmation=True)
    not_entered_bars = kill_house_requests.filter(assignment_state_archive='True', ware_house_confirmation=False)

    if empty_info_bars:
        for empty_info_bar in empty_info_bars:
            poultry_request = empty_info_bar.province_request.poultry_request
            hatching = empty_info_bar.province_request.poultry_request.hatching
            province_kill_request = empty_info_bar.province_kill_request
            empty_info_bar.fine = True
            empty_info_bar.fine_amount = (
                                                 fine.in_province_bars_fine_coefficient * empty_info_bar.accepted_real_weight) * province_kill_request.wage
            empty_info_bar.fine_coefficient = fine.in_province_bars_fine_coefficient
            empty_info_bar.message = 'لغو بار و اعمال جریمه به علت عدم تکمبل اطلاعات و ورود به انبار'
            empty_info_bar.bar_remover = {
                "date": str(datetime.now()),
                "role": "system",
                "mobile": "-",
                "full_name": "system"
            }
            empty_info_bar.trash = True
            empty_info_bar.save()
            update_kill_house_requests(province_kill_request, poultry_request)
            update_province_kill_requests(hatching)

    if not_completed_bars:
        for not_completed_bar in not_completed_bars:
            province_kill_request = not_completed_bar.province_kill_request

            not_completed_bar.fine = True
            not_completed_bar.fine_amount = (
                                                    fine.in_province_bars_fine_coefficient * not_completed_bar.accepted_real_weight) * province_kill_request.wage
            not_completed_bar.fine_coefficient = fine.in_province_bars_fine_coefficient
            not_completed_bar.message = 'اعمال جریمه به علت عدم تکمبل اطلاعات'
            not_completed_bar.save()

    if not_entered_bars:
        for not_entered_bar in not_entered_bars:
            province_kill_request = not_entered_bar.province_kill_request

            not_entered_bar.ware_house_accepted_real_quantity = not_entered_bar.accepted_real_quantity
            not_entered_bar.ware_house_accepted_real_weight = int(not_entered_bar.accepted_real_weight - (
                    (not_entered_bar.accepted_real_weight * 25) / 100))
            not_entered_bar.weight_loss = 25
            poultry_prediction(not_entered_bar.province_request.poultry_request.poultry)

            not_entered_bar.ware_house_input_type = "loss_weight"
            not_entered_bar.ware_house_confirmation = True
            not_entered_bar.date_of_ware_house = str(datetime.now())
            not_entered_bar.fine = True
            not_entered_bar.fine_amount = (
                                                  fine.in_province_bars_fine_coefficient * not_entered_bar.accepted_real_weight) * province_kill_request.wage
            not_entered_bar.fine_coefficient = fine.in_province_bars_fine_coefficient
            not_entered_bar.message = 'اعمال جریمه به علت عدم ورود به انبار'
            not_entered_bar.save()
            product = RolesProducts.objects.filter(parent_product__product_id=2,
                                                   kill_house=not_entered_bar.killhouse_user).first()
            kill_house_requests_product_warehousing(product)


# class KillHouseSalesInformationViewSet(APIView):
#     permission_classes = [TokenHasReadWriteScope]
#
#     def get(self, request):
#         date1 = request.GET.get('date1')
#         date2 = request.GET.get('date2')
#         key = request.GET.get('key')
#         kill_house = KillHouse.objects.get(key=key, trash=False)
#         kill_house_request_filter = {
#             'killhouse_user': kill_house,
#             'ware_house_confirmation': True,
#             'trash': False,
#             'calculate_status': True,
#         }
#         kill_house_free_buying_bar_filter = {
#             'kill_house': kill_house,
#             'trash': False,
#             'calculate_status': True,
#         }
#         kill_house_allocation_filter = {
#             'trash': False,
#             'calculate_status': True,
#         }
#
#         kill_house_free_sale_bars_filter = {
#             'trash': False,
#             'calculate_status': True,
#         }
#         if date1:
#             kill_house_request_filter['kill_request__recive_date__date__gte'] = datetime.strptime(date1,
#                                                                                                   '%Y-%m-%d').date() - timedelta(
#                 days=1)
#             kill_house_request_filter['kill_request__recive_date__date__lte'] = datetime.strptime(date2,
#                                                                                                   '%Y-%m-%d').date() - timedelta(
#                 days=1)
#             kill_house_free_buying_bar_filter['date__date__gte'] = date1
#             kill_house_free_buying_bar_filter['date__date__lte'] = date2
#             kill_house_allocation_filter['date__date__gte'] = date1
#             kill_house_allocation_filter['date__date__lte'] = date2
#             kill_house_free_sale_bars_filter['date__date__gte'] = date1
#             kill_house_free_sale_bars_filter['date__date__lte'] = date2
#
#         kill_house_requests = KillHouseRequest.objects.filter(**kill_house_request_filter)
#         kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter(
#             **kill_house_free_buying_bar_filter).exclude(entered_message='ورود به انبار مجازی')
#         kill_house_allocations = StewardAllocation.objects.filter(
#             Q(kill_house=kill_house) | Q(to_kill_house=kill_house), **kill_house_allocation_filter)
#         kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(**kill_house_free_sale_bars_filter)
#
#         kill_house_requests_aggregates = kill_house_requests.aggregate(
#             total_count=Count('id'),
#             total_governmental_weight=Sum('ware_house_accepted_real_weight',
#                                           filter=Q(province_request__poultry_request__free_sale_in_province=False)),
#             total_free_weight=Sum('ware_house_accepted_real_weight',
#                                   filter=Q(province_request__poultry_request__free_sale_in_province=True)),
#         )
#
#         kill_house_free_buying_bars_aggregates = kill_house_free_buying_bars.aggregate(
#             total_count=Count('id'),
#             total_weight=Sum('weight_of_carcasses'),
#         )
#
#         kill_house_allocations_aggregates = kill_house_allocations.aggregate(
#             total_count=Count('id'),
#             total_receive_governmental_weight=Sum('receiver_real_weight_of_carcasses',
#                                                   filter=Q(approved_price_status=True, receiver_state='accepted',
#                                                            kill_house__isnull=True, to_cold_house__isnull=True)),
#             total_receive_free_weight=Sum('receiver_real_weight_of_carcasses',
#                                           filter=Q(approved_price_status=False, receiver_state='accepted',
#                                                    kill_house__isnull=True, to_cold_house__isnull=True)),
#             total_allocated_governmental_weight=Sum('receiver_real_weight_of_carcasses',
#                                                     filter=Q(approved_price_status=False, receiver_state='accepted',
#                                                              kill_house__isnull=False, to_cold_house__isnull=True)),
#             total_allocated_free_weight=Sum('receiver_real_weight_of_carcasses',
#                                             filter=Q(approved_price_status=False, receiver_state='accepted',
#                                                      kill_house__isnull=False, to_cold_house__isnull=True)),
#
#         )
#         kill_house_free_sale_bars_aggregates = kill_house_free_sale_bars.aggregate(
#             total_count=Count('id'),
#             total_governmental_weight=Sum('real_weight_of_carcasses',
#                                           filter=Q(sale_type='governmental')),
#             total_free_weight=Sum('real_weight_of_carcasses',
#                                   filter=Q(sale_type='free')),
#         )
#
#         result = {
#             "kill_house_request_governmental_weight": kill_house_requests_aggregates['total_governmental_weight'] or 0,
#             "kill_house_request_free_weight": kill_house_requests_aggregates['total_free_weight'] or 0,
#             "kill_house_free_buying_bars_weight": kill_house_free_buying_bars_aggregates['total_weight'] or 0,
#             "total_receive_governmental_weight": kill_house_allocations_aggregates[
#                                                      'total_receive_governmental_weight'] or 0,
#             "total_receive_free_weight": kill_house_allocations_aggregates['total_receive_free_weight'] or 0,
#             "total_in_allocated_governmental_weight": kill_house_allocations_aggregates[
#                                                           'total_allocated_governmental_weight'] or 0,
#             "total_in_allocated_free_weight": kill_house_allocations_aggregates['total_allocated_free_weight'] or 0,
#             "total_out_allocated_free_weight": kill_house_free_sale_bars_aggregates['total_governmental_weight'] or 0,
#             "total_out_free_weight": kill_house_free_sale_bars_aggregates['total_free_weight'] or 0,
#         }
#
#         return Response(result, status=200)
class KillHouseSalesInformationViewSet(APIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        product = RolesProducts.objects.filter(kill_house=kill_house, trash=False, name='مرغ گرم').first()

        kill_house_requests = KillHouseRequest.objects.filter(
            input_warehouse=kill_house,
            temporary_trash=False,
            temporary_deleted=False,
            trash=False, calculate_status=True, warehouse=True)

        kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter(input_warehouse=kill_house,
                                                                                      trash=False,
                                                                                      temporary_trash=False,
                                                                                      temporary_deleted=False,
                                                                                      calculate_status=True,
                                                                                      warehouse=True).exclude(
            entered_message='ورود به انبار مجازی')
        kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter(
            kill_house=kill_house,
            trash=False,
            temporary_trash=False,
            temporary_deleted=False,
            calculate_status=True, warehouse=True)
        kill_house_allocations = StewardAllocation.objects.filter(kill_house=kill_house, trash=False,
                                                                  receiver_state__in=('pending', 'accepted'),
                                                                  temporary_trash=False,
                                                                  temporary_deleted=False,
                                                                  to_cold_house__isnull=True,
                                                                  calculate_status=True, warehouse=True)

        segmentations = PosSegmentation.objects.filter(kill_house=kill_house, trash=False, warehouse=True)
        cold_house_allocations = StewardAllocation.objects.filter(
            kill_house=kill_house,
            to_cold_house__isnull=False,
            receiver_state__in=('accepted', 'pending'),
            trash=False, warehouse=True)
        transactions = ProductsTransactions.objects.filter(product=product, transaction__paid=True, trash=False,
                                                           warehouse=True)
        total_entered_kill_house_requests_carcasses_governmental_weight = \
            kill_house_requests.filter(ware_house_confirmation=True,
                                       province_request__poultry_request__free_sale_in_province=False).aggregate(
                total=Sum('ware_house_accepted_real_weight'))[
                'total'] or 0
        total_entered_kill_house_requests_carcasses_free_weight = \
            kill_house_requests.filter(ware_house_confirmation=True,
                                       province_request__poultry_request__free_sale_in_province=True).aggregate(
                total=Sum('ware_house_accepted_real_weight'))[
                'total'] or 0

        total_entered_kill_house_free_bar_carcasses_weight = \
            kill_house_free_bar_informations.aggregate(total=Sum('weight_of_carcasses'))[
                'total'] or 0
        total_kill_house_free_sale__bar_carcasses_weight = \
            kill_house_free_Sale_bar_informations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        total_kill_house_free_sale__bar_carcasses_governmental_weight = \
            kill_house_free_Sale_bar_informations.filter(quota='governmental').aggregate(
                total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_kill_house_free_sale__bar_carcasses_free_weight = \
            kill_house_free_Sale_bar_informations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_kill_house_allocations_weight = \
            kill_house_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        total_kill_house_allocations_governmental_weight = \
            kill_house_allocations.filter(quota='governmental').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        total_kill_house_allocations_free_weight = \
            kill_house_allocations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        segmentations_weight = \
            segmentations.aggregate(total=Sum('weight'))[
                'total'] or 0
        segmentations_governmental_weight = \
            segmentations.filter(quota='governmental').aggregate(total=Sum('weight'))[
                'total'] or 0
        segmentations_free_weight = \
            segmentations.filter(quota='free').aggregate(total=Sum('weight'))[
                'total'] or 0

        cold_house_allocations_weight = \
            cold_house_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        cold_house_allocations_governmental_weight = \
            cold_house_allocations.filter(quota='governmental').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        cold_house_allocations_free_weight = \
            cold_house_allocations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        pos_allocated_weight_info = transactions.aggregate(
            pos_allocated_weight=Sum('cur_weight'),
            pos_governmental_allocated_weight=Sum('cur_weight',
                                                  filter=Q(price_approved=True)),
            pos_free_allocated_weight=Sum('cur_weight', filter=Q(price_approved=False)),

        )
        pos_allocated_weight = pos_allocated_weight_info['pos_allocated_weight'] or 0
        pos_governmental_allocated_weight = pos_allocated_weight_info['pos_governmental_allocated_weight'] or 0
        pos_free_allocated_weight = pos_allocated_weight_info['pos_free_allocated_weight'] or 0

        total_governmental_input_weight = total_entered_kill_house_requests_carcasses_governmental_weight
        total_free_input_weight = total_entered_kill_house_requests_carcasses_free_weight + total_entered_kill_house_free_bar_carcasses_weight
        total_governmental_output_weight = total_kill_house_free_sale__bar_carcasses_governmental_weight + segmentations_governmental_weight + total_kill_house_allocations_governmental_weight + cold_house_allocations_governmental_weight + int(pos_governmental_allocated_weight / 1000)
        total_free_output_weight = total_kill_house_free_sale__bar_carcasses_free_weight + total_kill_house_allocations_free_weight + segmentations_free_weight + cold_house_allocations_free_weight + int(pos_free_allocated_weight / 1000)
        total_governmental_remain_weight = (
                                                   total_governmental_input_weight - total_governmental_output_weight) - kill_house.ware_house_archive_governmental_weight
        total_free_remain_weight = (
                                           total_free_input_weight - total_free_output_weight) - kill_house.ware_house_archive_free_weight

        result = {

            "total_governmental_input_weight": int(total_governmental_input_weight),
            "total_free_input_weight": int(total_free_input_weight),
            "total_governmental_output_weight": int(total_governmental_output_weight),
            "total_free_output_weight": int(total_free_output_weight),
            "total_governmental_remain_weight": int(total_governmental_remain_weight),
            "total_free_remain_weight": int(total_free_remain_weight),
            "total_kill_house_free_sale__bar_carcasses_weight": int(total_kill_house_free_sale__bar_carcasses_weight),
            "total_kill_house_allocations_weight": int(total_kill_house_allocations_weight),
            "segmentations_weight": int(segmentations_weight),
            "cold_house_allocations_weight": int(cold_house_allocations_weight),
            "total_selling_in_province_governmental_weight": kill_house.total_selling_in_province_governmental_weight,
            "total_selling_in_province_free_weight": kill_house.total_selling_in_province_free_weight,
            "total_commitment_selling_in_province_governmental_weight": kill_house.total_commitment_selling_in_province_governmental_weight,
            "total_commitment_selling_in_province_governmental_remain_weight": kill_house.total_commitment_selling_in_province_governmental_remain_weight,
            "total_commitment_selling_in_province_free_weight": kill_house.total_commitment_selling_in_province_free_weight,
            "total_commitment_selling_in_province_free_remain_weight": kill_house.total_commitment_selling_in_province_free_remain_weight,
            "pos_allocated_weight": int(pos_allocated_weight / 1000),
            "pos_governmental_allocated_weight": int(pos_governmental_allocated_weight / 1000),
            "pos_free_allocated_weight": int(pos_free_allocated_weight / 1000),
            "ware_house_archive_governmental_weight": kill_house.ware_house_archive_governmental_weight,
            "ware_house_archive_free_weight": kill_house.ware_house_archive_free_weight,

        }

        return Response(result, status=200)


class KillHouseForColdHouseAllocationViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseForColdHouseAllocationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        role = request.GET.get('role')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_filters = {'out_province': False, 'trash': False}
        if role in ['CityJahad']:
            kill_house_filters['kill_house_operator__user__city'] = user.city
        kill_houses = KillHouse.objects.filter(**kill_house_filters).order_by('id', 'killer')
        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_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(kill_houses)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'date1': date1, 'date2': date2})
            return self.get_paginated_response(serializer.data)

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


class KillHouseForSegmentationViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseForSegmentationSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        role = request.GET.get('role')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house_filters = {'out_province': False, 'trash': False}
        if role in ['CityJahad']:
            kill_house_filters['kill_house_operator__user__city'] = user.city

        kill_houses = KillHouse.objects.filter(**kill_house_filters).order_by('id', 'killer')

        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_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(kill_houses)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'date1': date1, 'date2': date2})
            return self.get_paginated_response(serializer.data)

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


class KillHouseComparativeInformationViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = KillHouseComparativeInformationSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        # kill_house_ids = KillHousePercentage.objects.filter(kill_house__type='exclusive', trash=False).values_list(
        #     'kill_house', flat=True)
        # kill_houses = KillHouse.objects.filter(out_province=False,killer=False,trash=False).exclude(
        #     id__in=kill_house_ids).order_by('id')
        kill_houses = KillHouse.objects.filter(out_province=False, killer=False, trash=False).order_by('id')
        codes = kill_houses.values_list('unique_identifier', flat=True)
        code = ",".join(codes)
        if date1:
            url = f"https://rsibackend.rasadyar.com/app/send_transport_carcass_detail_for_rasadyaar/?code={code}&date1={date1}&date2={date2}"
        else:
            url = f"https://rsibackend.rasadyar.com/app/send_transport_carcass_detail_for_rasadyaar/?code={code}"

        response = requests.get(url)
        rsi_data = response.json()
        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_list
        serializer = self.serializer_class(kill_houses, many=True,
                                           context={'date1': date1, 'date2': date2, 'rsi_data': rsi_data})
        return Response(serializer.data, status=status.HTTP_200_OK)


def cancel_bar_and_province_request(request):
    date_str = '2025-10-11'
    date = datetime.now().date() - timedelta(days=1)

    kill_house_requests = KillHouseRequest.objects.filter(trash=False, ware_house_confirmation=False,
                                                          kill_request__recive_date__date__lte=date,
                                                          kill_request__recive_date__date__gte=date_str)
    all_province_requests = kill_house_requests.values_list('province_kill_request', flat=True).distinct()
    for kill_house_request in kill_house_requests:
        kill_house_request.trash = True
        kill_house_request.return_trash = True
        kill_house_request.save()
        update_kill_house_requests(kill_house_request.province_kill_request,
                                   kill_house_request.province_request.poultry_request)
        update_province_kill_requests(
            kill_house_request.province_kill_request.province_request.poultry_request.hatching)

    for all_province_request in all_province_requests:
        if not KillHouseRequest.objects.filter(trash=False, province_kill_request=all_province_request).exists():
            all_province_request.return_to_province = True
            all_province_request.returner = {"date": str(datetime.today()),
                                             "mobile": "09000000000", "fullname": "برگشت به دلیل حذف سیستمی بار"}
            all_province_request.save()

    province_requests = ProvinceKillRequest.objects.filter(trash=False, first_car_allocated_quantity=0,
                                                           return_to_province=False,
                                                           kill_request__recive_date__date=datetime.now().date(),
                                                           )
    for province_request in province_requests:
        province_request.trash = True
        province_request.return_trash = True
        province_request.save()
        update_province_kill_requests(province_request.province_request.poultry_request.hatching)

    return HttpResponse('ok')


def cancel_bar_and_province_request_cron():
    date_str = '2025-10-11'
    date = datetime.now().date() - timedelta(days=1)

    kill_house_requests = KillHouseRequest.objects.filter(trash=False, ware_house_confirmation=False,
                                                          kill_request__recive_date__date__lte=date,
                                                          kill_request__recive_date__date__gte=date_str)
    all_province_requests = kill_house_requests.values_list('province_kill_request', flat=True).distinct()
    for kill_house_request in kill_house_requests:
        kill_house_request.trash = True
        kill_house_request.return_trash = True
        kill_house_request.save()
        update_kill_house_requests(kill_house_request.province_kill_request,
                                   kill_house_request.province_request.poultry_request)
        update_province_kill_requests(
            kill_house_request.province_kill_request.province_request.poultry_request.hatching)

    for all_province_request in all_province_requests:
        if not KillHouseRequest.objects.filter(trash=False, province_kill_request=all_province_request).exists():
            all_province_request.return_to_province = True
            all_province_request.returner = {"date": str(datetime.today()),
                                             "mobile": "09000000000", "fullname": "برگشت به دلیل حذف سیستمی بار"}
            all_province_request.save()

    province_requests = ProvinceKillRequest.objects.filter(trash=False, first_car_allocated_quantity=0,
                                                           return_to_province=False,
                                                           kill_request__recive_date__date=datetime.now().date(),
                                                           )
    for province_request in province_requests:
        province_request.trash = True
        province_request.return_trash = True
        province_request.save()
        update_province_kill_requests(province_request.province_request.poultry_request.hatching)


class ReturnProvinceKillRequestViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = ReturnProvinceKillRequestSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = ReturnProvinceKillRequestFilterSet
    filterset_fields = [
        'province_request__poultry_request__order_code',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__kill_house_operator__address__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__poultry__address__city__name',
    ]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        role = request.GET.get('role')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        filters = {
            'archive_wage': False,
            'state__in': ('pending', 'accepted'),
            'first_car_allocated_quantity': 0
        }
        if role == 'KillHouse':
            filters['killhouse_user__kill_house_operator__user'] = user
        if date1:
            filters['kill_request__recive_date__date__gte'] = date1
            filters['kill_request__recive_date__date__lte'] = date2

        return_province_kill_requests = ProvinceKillRequest.objects.filter(
            Q(trash=False, return_to_province=True) | Q(trash=True, return_trash=True), **filters).order_by('id')

        if 'search' in request.GET:
            return_province_kill_requests_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=return_province_kill_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=return_province_kill_requests)
                            return_province_kill_requests_list = ps.filter()
                    return_province_kill_requests = [] if len(
                        return_province_kill_requests_list) == 0 else return_province_kill_requests_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(return_province_kill_requests)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

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

    def put(self, request):
        return_province_kill_requests = ProvinceKillRequest.objects.get(
            key=request.data['key'])
        request.data.pop('key')
        serializer = self.serializer_class(return_province_kill_requests)
        serializer.update(instance=return_province_kill_requests, validated_data=request.data)
        update_province_kill_requests(return_province_kill_requests.province_request.poultry_request.hatching)
        poultry_prediction(return_province_kill_requests.province_request.poultry_request.hatching.poultry)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ReturnKillHouseRequestViewSet(viewsets.ModelViewSet):
    queryset = KillHouseRequest.objects.all()
    serializer_class = KillHouseRequestForBarManagementSerializer
    pagination_class = CustomPagination
    permission_classes = [TokenHasReadWriteScope]
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

    def list(self, request, *args, **kwargs):
        if request.GET['role'] == 'KillHouse':
            user = SystemUserProfile.objects.get(user=request.user)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            if 'date1' in request.GET and 'date2' in request.GET:
                date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2)

            else:
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True))

        else:
            if 'date1' in request.GET and 'date2' in request.GET:
                date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2)

            else:
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True))

        if 'search' in request.GET:
            kill_house_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=kill_house_requests
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_house_requests)
                            kill_house_request_list = ps.filter()
                    kill_house_requests = [] if len(kill_house_request_list) == 0 else kill_house_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(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)

    def update(self, request, *args, **kwargs):
        kill_house_requests = KillHouseRequest.objects.get(key=request.data['key'])
        kill_house_requests.province_kill_request.trash = False
        kill_house_requests.province_kill_request.return_trash = False
        kill_house_requests.province_kill_request.return_to_province = False
        kill_house_requests.province_kill_request.returner = None
        kill_house_requests.province_kill_request.save()
        request.data.pop('key')
        serializer = self.serializer_class(kill_house_requests)
        serializer.update(instance=kill_house_requests, validated_data=request.data)
        update_kill_house_requests(kill_house_requests.province_kill_request,
                                   kill_house_requests.province_request.poultry_request)
        update_province_kill_requests(kill_house_requests.province_request.poultry_request.hatching)
        return Response(serializer.data, status=status.HTTP_200_OK)


class ReturnRequestDashboardViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        role = request.GET.get('role')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        total_wage_type = WageType.objects.filter(trash=False)
        province_live_wage_type = total_wage_type.filter(en_name='province-kill-request', trash=False).first()
        province_live_wage_type_amount = province_live_wage_type.amount if province_live_wage_type.status == True else 0

        province_kill_request_filters = {
            'archive_wage': False,
            'state__in': ('pending', 'accepted'),
            'first_car_allocated_quantity': 0
        }

        kill_house_request_filters = {}
        if date1:
            province_kill_request_filters['kill_request__recive_date__date__gte'] = date1
            province_kill_request_filters['kill_request__recive_date__date__lte'] = date2
            kill_house_request_filters['kill_request__recive_date__date__gte'] = date1
            kill_house_request_filters['kill_request__recive_date__date__lte'] = date2
        if role == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            province_kill_request_filters['killhouse_user'] = kill_house
            return_kill_house_requests = KillHouseRequest.objects.filter(
                Q(killhouse_user=kill_house) | Q(killer=kill_house),
                Q(non_receipt=True, main_non_receipt=True, non_receipt_state__in=('pending', 'accepted')) | Q(
                    trash=True, return_trash=True),
                **kill_house_request_filters)
        else:
            return_kill_house_requests = KillHouseRequest.objects.filter(
                Q(non_receipt=True, main_non_receipt=True, non_receipt_state__in=('pending', 'accepted')) | Q(
                    trash=True, return_trash=True),
                **kill_house_request_filters)

        return_province_kill_requests = ProvinceKillRequest.objects.filter(
            Q(trash=False, return_to_province=True) | Q(trash=True, return_trash=True),
            **province_kill_request_filters).order_by('id')

        return_province_kill_requests_aggregates = return_province_kill_requests.aggregate(
            total_count=Count('id'),
            total_operator_return_count=Count('id', filter=Q(trash=False, return_to_province=True)),
            total_system_return_count=Count('id', filter=Q(trash=True, return_trash=True)),
            total_quantity=Sum('total_killed_quantity'),
            total_operator_return_quantity=Sum('main_quantity', filter=Q(trash=False, return_to_province=True)),
            total_system_return_quantity=Sum('total_killed_quantity', filter=Q(trash=True, return_trash=True)),
            total_weight=Sum('total_killed_weight'),
            total_operator_return_weight=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight'),
                                             filter=Q(trash=False, return_to_province=True)),
            total_system_return_weight=Sum('total_killed_weight', filter=Q(trash=True, return_trash=True)),

        )
        return_kill_house_requests_aggregates = return_kill_house_requests.aggregate(
            total_count=Count('id'),
            total_non_receipt_count=Count('id', filter=Q(non_receipt=True, main_non_receipt=True)),
            total_system_return_count=Count('id', filter=Q(trash=True, return_trash=True)),
            total_quantity=Sum('accepted_real_quantity'),
            total_non_receipt_quantity=Sum('accepted_real_quantity', filter=Q(non_receipt=True, main_non_receipt=True)),
            total_system_return_quantity=Sum('accepted_real_quantity', filter=Q(trash=True, return_trash=True)),
            total_weight=Sum('accepted_real_weight'),
            total_non_receipt_weight=Sum('accepted_real_weight', filter=Q(non_receipt=True, main_non_receipt=True)),
            total_system_return_weight=Sum('accepted_real_weight', filter=Q(trash=True, return_trash=True)),
        )
        province_kill_request_total_operator_return_quantity = return_province_kill_requests_aggregates[
                                                                   'total_operator_return_quantity'] or 0
        province_kill_request_total_system_return_quantity = return_province_kill_requests_aggregates[
                                                                 'total_system_return_quantity'] or 0
        province_kill_request_total_quantity = province_kill_request_total_operator_return_quantity + province_kill_request_total_system_return_quantity
        province_kill_request_total_operator_return_weight = return_province_kill_requests_aggregates[
                                                                 'total_operator_return_weight'] or 0
        province_kill_request_total_system_return_weight = return_province_kill_requests_aggregates[
                                                               'total_system_return_weight'] or 0
        province_kill_request_total_weight = province_kill_request_total_operator_return_weight + province_kill_request_total_system_return_weight
        kill_house_request_total_system_return_weight = return_kill_house_requests_aggregates[
                                                            'total_system_return_weight'] or 0
        total_return_weight_with_wage = province_kill_request_total_system_return_weight + kill_house_request_total_system_return_weight
        result = {
            "province_kill_request_total_count": return_province_kill_requests_aggregates['total_count'] or 0,
            "province_kill_request_total_operator_return_count": return_province_kill_requests_aggregates[
                                                                     'total_operator_return_count'] or 0,
            "province_kill_request_total_system_return_count": return_province_kill_requests_aggregates[
                                                                   'total_system_return_count'] or 0,
            "province_kill_request_total_quantity": province_kill_request_total_quantity,
            "province_kill_request_total_operator_return_quantity": province_kill_request_total_operator_return_quantity,
            "province_kill_request_total_system_return_quantity": province_kill_request_total_system_return_quantity,
            "province_kill_request_total_weight": province_kill_request_total_weight,
            "province_kill_request_total_operator_return_weight": province_kill_request_total_operator_return_weight,
            "province_kill_request_total_system_return_weight": province_kill_request_total_system_return_weight,
            "kill_house_request_total_count": return_kill_house_requests_aggregates['total_count'] or 0,
            "kill_house_request_total_non_receipt_count": return_kill_house_requests_aggregates[
                                                              'total_non_receipt_count'] or 0,
            "kill_house_request_total_system_return_count": return_kill_house_requests_aggregates[
                                                                'total_system_return_count'] or 0,
            "kill_house_request_total_quantity": return_kill_house_requests_aggregates['total_quantity'] or 0,
            "kill_house_request_total_non_receipt_quantity": return_kill_house_requests_aggregates[
                                                                 'total_non_receipt_quantity'] or 0,
            "kill_house_request_total_system_return_quantity": return_kill_house_requests_aggregates[
                                                                   'total_system_return_quantity'] or 0,
            "kill_house_request_total_weight": return_kill_house_requests_aggregates['total_weight'] or 0,
            "kill_house_request_total_non_receipt_weight": return_kill_house_requests_aggregates[
                                                               'total_non_receipt_weight'] or 0,
            "kill_house_request_total_system_return_weight": kill_house_request_total_system_return_weight,
            "total_return_weight_with_wage": total_return_weight_with_wage,
            "total_return_wage": total_return_weight_with_wage * province_live_wage_type_amount,
        }

        return Response(result, status=status.HTTP_200_OK)


# class KillHouseRemainWeightViewSet(GenericAPIView):
#     permission_classes = [TokenHasReadWriteScope]
#
#     def get(self, request):
#         # چک کردن آیا کاربر بازه تاریخی دلخواه فرستاده یا نه
#         start_date_param = request.query_params.get('date1', None)
#         end_date_param = request.query_params.get('date2', None)
#
#         if start_date_param and end_date_param:
#             # بازه تاریخی دلخواه از ورودی کاربر
#             user = SystemUserProfile.objects.get(user=request.user, trash=False)
#             kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
#             product = RolesProducts.objects.filter(kill_house=kill_house, trash=False, name='مرغ گرم').first()
#
#             # تبدیل string به date
#             from datetime import datetime as dt
#             start_date = dt.strptime(start_date_param, '%Y-%m-%d').date()
#             end_date = dt.strptime(end_date_param, '%Y-%m-%d').date()
#
#             # ساخت لیست تمام روزهای بین start_date و end_date
#             days = []
#             current_day = start_date
#             while current_day <= end_date:
#                 days.append(current_day)
#                 current_day += timedelta(days=1)
#
#             kill_house_requests = KillHouseRequest.objects.filter(
#                 input_warehouse=kill_house,
#                 kill_request__recive_date__date__gte=start_date,
#                 kill_request__recive_date__date__lte=end_date,
#                 ware_house_confirmation=True,
#                 trash=False,
#                 calculate_status=True,
#                 warehouse=True
#             )
#
#             kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter(
#                 trash=False,
#                 calculate_status=True,
#                 warehouse=True,
#                 date__date__gte=start_date,
#                 date__date__lte=end_date,
#                 input_warehouse=kill_house
#             ).exclude(entered_message='ورود به انبار مجازی')
#
#             kill_house_allocations = StewardAllocation.objects.filter(
#                 kill_house=kill_house,
#                 trash=False,
#                 calculate_status=True,
#                 warehouse=True,
#                 receiver_state__in=('pending', 'accepted'),
#                 production_date__date__gte=start_date,
#                 production_date__date__lte=end_date
#             )
#
#             kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(
#                 kill_house=kill_house,
#                 production_date__date__gte=start_date,
#                 production_date__date__lte=end_date,
#                 trash=False,
#                 calculate_status=True,
#                 warehouse=True
#             )
#
#             segmentations = PosSegmentation.objects.filter(
#                 kill_house=kill_house,
#                 production_date__date__gte=start_date,
#                 production_date__date__lte=end_date,
#                 trash=False,
#                 warehouse=True
#             )
#
#             transactions = ProductsTransactions.objects.filter(
#                 product=product,
#                 transaction__paid=True,
#                 transaction__date__date__gte=start_date,
#                 transaction__date__date__lte=end_date,
#                 trash=False,
#                 warehouse=True
#             )
#
#             governmental_list = []
#             free_list = []
#             final_dict = {}
#
#             for day in days:
#                 kill_house_requests_info = kill_house_requests.aggregate(
#                     total_kill_house_request_governmental_weight=Sum(
#                         'ware_house_accepted_real_weight',
#                         filter=Q(province_request__poultry_request__free_sale_in_province=False,
#                                  kill_request__recive_date__date=day)
#                     ),
#                     total_kill_house_request_free_weight=Sum(
#                         'ware_house_accepted_real_weight',
#                         filter=Q(province_request__poultry_request__free_sale_in_province=True,
#                                  kill_request__recive_date__date=day)
#                     ),
#                 )
#
#                 kill_house_free_buying_bars_info = kill_house_free_buying_bars.aggregate(
#                     total_kill_house_free_buying_bars_weight=Sum(
#                         'weight_of_carcasses', filter=Q(date__date=day)
#                     )
#                 )
#
#                 kill_house_allocations_info = kill_house_allocations.aggregate(
#                     total_kill_house_allocations_governmental_weight=Sum(
#                         'real_weight_of_carcasses',
#                         filter=Q(quota='governmental', production_date__date=day)
#                     ),
#                     total_kill_house_allocations_free_weight=Sum(
#                         'real_weight_of_carcasses',
#                         filter=Q(quota='free', production_date__date=day)
#                     ),
#                 )
#
#                 kill_house_free_sale_bars_info = kill_house_free_sale_bars.aggregate(
#                     total_kill_house_free_sale_bars_governmental_weight=Sum(
#                         'real_weight_of_carcasses',
#                         filter=Q(quota='governmental', production_date__date=day)
#                     ),
#                     total_kill_house_free_sale_bars_free_weight=Sum(
#                         'real_weight_of_carcasses',
#                         filter=Q(quota='free', production_date__date=day)
#                     ),
#                 )
#
#                 segmentations_info = segmentations.aggregate(
#                     segmentations_governmental_weight=Sum(
#                         'weight', filter=Q(quota='governmental', production_date__date=day)
#                     ),
#                     segmentations_free_weight=Sum(
#                         'weight', filter=Q(quota='free', production_date__date=day)
#                     ),
#                 )
#
#                 pos_allocated_weight_info = transactions.aggregate(
#                     pos_governmental_allocated_weight=Sum(
#                         'cur_weight', filter=Q(price_approved=True, transaction__date__date=day)
#                     ),
#                     pos_free_allocated_weight=Sum(
#                         'cur_weight', filter=Q(price_approved=False, transaction__date__date=day)
#                     ),
#                 )
#
#                 total_kill_house_request_governmental_weight = kill_house_requests_info[
#                                                                    'total_kill_house_request_governmental_weight'] or 0
#                 total_kill_house_request_free_weight = kill_house_requests_info[
#                                                            'total_kill_house_request_free_weight'] or 0
#                 total_kill_house_free_buying_bars_weight = kill_house_free_buying_bars_info[
#                                                                'total_kill_house_free_buying_bars_weight'] or 0
#                 total_kill_house_allocations_governmental_weight = kill_house_allocations_info[
#                                                                        'total_kill_house_allocations_governmental_weight'] or 0
#                 total_kill_house_allocations_free_weight = kill_house_allocations_info[
#                                                                'total_kill_house_allocations_free_weight'] or 0
#                 total_kill_house_free_sale_bars_governmental_weight = kill_house_free_sale_bars_info[
#                                                                           'total_kill_house_free_sale_bars_governmental_weight'] or 0
#                 total_kill_house_free_sale_bars_free_weight = kill_house_free_sale_bars_info[
#                                                                   'total_kill_house_free_sale_bars_free_weight'] or 0
#                 segmentations_governmental_weight = segmentations_info['segmentations_governmental_weight'] or 0
#                 segmentations_free_weight = segmentations_info['segmentations_free_weight'] or 0
#                 pos_governmental_allocated_weight = pos_allocated_weight_info['pos_governmental_allocated_weight'] or 0
#                 pos_free_allocated_weight = pos_allocated_weight_info['pos_free_allocated_weight'] or 0
#
#                 total_governmental_input = total_kill_house_request_governmental_weight
#                 total_free_input = total_kill_house_request_free_weight + total_kill_house_free_buying_bars_weight
#
#                 total_governmental_output = (
#                         total_kill_house_allocations_governmental_weight +
#                         total_kill_house_free_sale_bars_governmental_weight +
#                         segmentations_governmental_weight +
#                         int(pos_governmental_allocated_weight / 1000)
#                 )
#
#                 total_free_output = (
#                         total_kill_house_allocations_free_weight +
#                         total_kill_house_free_sale_bars_free_weight +
#                         segmentations_free_weight +
#                         int(pos_free_allocated_weight / 1000)
#                 )
#
#                 governmental_data = {
#                     'day': day,
#                     'amount': total_governmental_input - total_governmental_output,
#                 }
#                 free_data = {
#                     'day': day,
#                     'amount': total_free_input - total_free_output,
#                 }
#
#                 governmental_list.append(governmental_data)
#                 free_list.append(free_data)
#
#             final_dict['governmental'] = governmental_list
#             final_dict['free'] = free_list
#             return Response(final_dict, status=status.HTTP_200_OK)
#
#         # حالت پیش‌فرض: 3 روز اخیر (کد قبلی دست نخورده)
#         user = SystemUserProfile.objects.get(user=request.user, trash=False)
#         kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
#         product = RolesProducts.objects.filter(kill_house=kill_house, trash=False, name='مرغ گرم').first()
#         today = datetime.now().date()
#         yesterday = today - timedelta(days=1)
#         two_days_ago = yesterday - timedelta(days=1)
#         days = (two_days_ago, yesterday, today)
#
#         archives = WarehouseArchive.objects.filter(kill_house=kill_house, trash=False,date__date__gte=two_days_ago,date__date__lte=today)
#
#
#         kill_house_requests = KillHouseRequest.objects.filter(input_warehouse=kill_house,
#                                                               kill_request__recive_date__date__gte=two_days_ago,
#                                                               kill_request__recive_date__date__lte=today,
#                                                               ware_house_confirmation=True, trash=False,
#                                                               calculate_status=True, warehouse=True)
#         kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter(trash=False,
#                                                                                  calculate_status=True, warehouse=True,
#                                                                                  date__date__gte=two_days_ago,
#                                                                                  date__date__lte=today,
#                                                                                  input_warehouse=kill_house) \
#             .exclude(entered_message='ورود به انبار مجازی')
#         kill_house_allocations = StewardAllocation.objects.filter(
#             kill_house=kill_house, trash=False, calculate_status=True, warehouse=True,
#             receiver_state__in=('pending', 'accepted'), production_date__date__gte=two_days_ago,
#             production_date__date__lte=today)
#
#         kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house,
#                                                                                    production_date__date__gte=two_days_ago,
#                                                                                    production_date__date__lte=today,
#                                                                                    trash=False,
#                                                                                    calculate_status=True,
#                                                                                    warehouse=True)
#         segmentations = PosSegmentation.objects.filter(kill_house=kill_house, production_date__date__gte=two_days_ago,
#                                                        production_date__date__lte=today, trash=False,
#                                                        warehouse=True)
#         transactions = ProductsTransactions.objects.filter(product=product, transaction__paid=True,
#                                                            transaction__date__date__gte=two_days_ago,
#                                                            transaction__date__date__lte=today, trash=False,
#                                                            warehouse=True)
#
#         governmental_list = []
#         free_list = []
#         final_dict = {}
#
#         for day in days:
#             kill_house_requests_info = kill_house_requests.aggregate(
#                 total_kill_house_request_governmental_weight=Sum('ware_house_accepted_real_weight', filter=Q(
#                     province_request__poultry_request__free_sale_in_province=False,
#                     kill_request__recive_date__date=day)),
#                 total_kill_house_request_free_weight=Sum('ware_house_accepted_real_weight', filter=Q(
#                     province_request__poultry_request__free_sale_in_province=True,
#                     kill_request__recive_date__date=day)),
#
#             )
#
#             kill_house_free_buying_bars_info = kill_house_free_buying_bars.aggregate(
#                 total_kill_house_free_buying_bars_weight=Sum('weight_of_carcasses', filter=Q(date__date=day)))
#
#             kill_house_allocations_info = kill_house_allocations.aggregate(
#                 total_kill_house_allocations_governmental_weight=Sum('real_weight_of_carcasses',
#                                                                      filter=Q(quota='governmental',
#                                                                               production_date__date=day)),
#                 total_kill_house_allocations_free_weight=Sum('real_weight_of_carcasses',
#                                                              filter=Q(quota='free', production_date__date=day)),
#
#             )
#
#             kill_house_free_sale_bars_info = kill_house_free_sale_bars.aggregate(
#                 total_kill_house_free_sale_bars_governmental_weight=Sum('real_weight_of_carcasses',
#                                                                         filter=Q(quota='governmental',
#                                                                                  production_date__date=day)),
#                 total_kill_house_free_sale_bars_free_weight=Sum('real_weight_of_carcasses',
#                                                                 filter=Q(quota='free', production_date__date=day)),
#
#             )
#
#             segmentations_info = segmentations.aggregate(
#                 segmentations_governmental_weight=Sum('weight',
#                                                       filter=Q(quota='governmental', production_date__date=day)),
#                 segmentations_free_weight=Sum('weight', filter=Q(quota='free', production_date__date=day)),
#
#             )
#             pos_allocated_weight_info = transactions.aggregate(
#                 pos_governmental_allocated_weight=Sum('cur_weight',
#                                                       filter=Q(price_approved=True, transaction__date__date=day)),
#                 pos_free_allocated_weight=Sum('cur_weight',
#                                               filter=Q(price_approved=False, transaction__date__date=day)),
#
#             )
#
#             archives_info = archives.aggregate(
#                 archives_governmental_weight=Sum('weight',
#                                                       filter=Q(quota='governmental', date__date=day)),
#                 archives_free_weight=Sum('weight',
#                                               filter=Q(quota='free', date__date=day)),
#
#             )
#
#             total_kill_house_request_governmental_weight = kill_house_requests_info[
#                                                                'total_kill_house_request_governmental_weight'] or 0
#             total_kill_house_request_free_weight = kill_house_requests_info['total_kill_house_request_free_weight'] or 0
#             total_kill_house_free_buying_bars_weight = kill_house_free_buying_bars_info[
#                                                            'total_kill_house_free_buying_bars_weight'] or 0
#             total_kill_house_allocations_governmental_weight = kill_house_allocations_info[
#                                                                    'total_kill_house_allocations_governmental_weight'] or 0
#             total_kill_house_allocations_free_weight = kill_house_allocations_info[
#                                                            'total_kill_house_allocations_free_weight'] or 0
#             total_kill_house_free_sale_bars_governmental_weight = kill_house_free_sale_bars_info[
#                                                                       'total_kill_house_free_sale_bars_governmental_weight'] or 0
#             total_kill_house_free_sale_bars_free_weight = kill_house_free_sale_bars_info[
#                                                               'total_kill_house_free_sale_bars_free_weight'] or 0
#             segmentations_governmental_weight = segmentations_info['segmentations_governmental_weight'] or 0
#             segmentations_free_weight = segmentations_info['segmentations_free_weight'] or 0
#             pos_governmental_allocated_weight = pos_allocated_weight_info['pos_governmental_allocated_weight'] or 0
#             pos_free_allocated_weight = pos_allocated_weight_info['pos_free_allocated_weight'] or 0
#
#             archives_governmental_weight = archives_info['archives_governmental_weight'] or 0
#             archives_free_weight = archives_info['archives_free_weight'] or 0
#
#             total_governmental_input = total_kill_house_request_governmental_weight
#             total_free_input = total_kill_house_request_free_weight + total_kill_house_free_buying_bars_weight
#             total_governmental_output = total_kill_house_allocations_governmental_weight + total_kill_house_free_sale_bars_governmental_weight + segmentations_governmental_weight + int(
#                 pos_governmental_allocated_weight / 1000)
#             total_free_output = total_kill_house_allocations_free_weight + total_kill_house_free_sale_bars_free_weight + segmentations_free_weight + int(
#                 pos_free_allocated_weight / 1000)
#             governmental_data = {
#                 'day': day,
#                 'amount': (total_governmental_input - total_governmental_output) - archives_governmental_weight,
#             }
#             free_data = {
#                 'day': day,
#                 'amount': (total_free_input - total_free_output) - archives_free_weight,
#             }
#
#             governmental_list.append(governmental_data)
#             free_list.append(free_data)
#         final_dict['governmental'] = governmental_list
#         final_dict['free'] = free_list
#         return Response(final_dict, status=status.HTTP_200_OK)
#
#     # def get(self, request):
#     #     target_date = request.GET.get('date')
#     #     user = SystemUserProfile.objects.get(user=request.user, trash=False)
#     #
#     #     kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
#     #
#     #     product = RolesProducts.objects.filter(kill_house=kill_house, trash=False, name='مرغ گرم').first()
#     #
#     #     today = datetime.now().date() if not target_date else datetime.strptime(target_date, "%Y-%m-%d").date()
#     #     month_ago = today - timedelta(days=30)
#     #     yesterday = today - timedelta(days=1)
#     #     two_days_ago = yesterday - timedelta(days=1)
#     #
#     #     days = [month_ago + timedelta(days=i) for i in range(31)]
#     #     target_days = [two_days_ago ,yesterday , today]
#     #
#     #     kill_house_requests = KillHouseRequest.objects.filter(
#     #         input_warehouse=kill_house,
#     #         kill_request__recive_date__date__gte=month_ago,
#     #         kill_request__recive_date__date__lte=today,
#     #         ware_house_confirmation=True,
#     #         trash=False,
#     #         calculate_status=True,
#     #         warehouse=True
#     #     )
#     #
#     #     kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter(
#     #         trash=False,
#     #         calculate_status=True,
#     #         warehouse=True,
#     #         date__date__gte=month_ago,
#     #         date__date__lte=today,
#     #         input_warehouse=kill_house
#     #     ).exclude(entered_message='ورود به انبار مجازی')
#     #
#     #     kill_house_allocations = StewardAllocation.objects.filter(
#     #         kill_house=kill_house,
#     #         trash=False,
#     #         calculate_status=True,
#     #         warehouse=True,
#     #         receiver_state__in=('pending', 'accepted'),
#     #         production_date__date__gte=month_ago,
#     #         production_date__date__lte=today
#     #     )
#     #
#     #     kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(
#     #         kill_house=kill_house,
#     #         production_date__date__gte=month_ago,
#     #         production_date__date__lte=today,
#     #         trash=False,
#     #         calculate_status=True,
#     #         warehouse=True
#     #     )
#     #
#     #     segmentations = PosSegmentation.objects.filter(
#     #         kill_house=kill_house,
#     #         production_date__date__gte=month_ago,
#     #         production_date__date__lte=today,
#     #         trash=False,
#     #         warehouse=True
#     #     )
#     #
#     #     transactions = ProductsTransactions.objects.filter(
#     #         product=product,
#     #         transaction__paid=True,
#     #         transaction__date__date__gte=month_ago,
#     #         transaction__date__date__lte=today,
#     #         trash=False,
#     #         warehouse=True
#     #     )
#     #     archives = WarehouseArchive.objects.filter(kill_house=kill_house, trash=False)
#     #
#     #
#     #     governmental_list = []
#     #     free_list = []
#     #     final_dict = {}
#     #
#     #     for day in days:
#     #         kill_house_requests_info = kill_house_requests.aggregate(
#     #             total_kill_house_request_governmental_weight=Sum(
#     #                 'ware_house_accepted_real_weight',
#     #                 filter=Q(province_request__poultry_request__free_sale_in_province=False,
#     #                          kill_request__recive_date__date=day)
#     #             ),
#     #             total_kill_house_request_free_weight=Sum(
#     #                 'ware_house_accepted_real_weight',
#     #                 filter=Q(province_request__poultry_request__free_sale_in_province=True,
#     #                          kill_request__recive_date__date=day)
#     #             ),
#     #         )
#     #
#     #         kill_house_free_buying_bars_info = kill_house_free_buying_bars.aggregate(
#     #             total_kill_house_free_buying_bars_weight=Sum(
#     #                 'weight_of_carcasses', filter=Q(date__date=day)
#     #             )
#     #         )
#     #
#     #         kill_house_allocations_info = kill_house_allocations.aggregate(
#     #             total_kill_house_allocations_governmental_weight=Sum(
#     #                 'real_weight_of_carcasses',
#     #                 filter=Q(quota='governmental', production_date__date=day)
#     #             ),
#     #             total_kill_house_allocations_free_weight=Sum(
#     #                 'real_weight_of_carcasses',
#     #                 filter=Q(quota='free', production_date__date=day)
#     #             ),
#     #         )
#     #
#     #         kill_house_free_sale_bars_info = kill_house_free_sale_bars.aggregate(
#     #             total_kill_house_free_sale_bars_governmental_weight=Sum(
#     #                 'real_weight_of_carcasses',
#     #                 filter=Q(quota='governmental', production_date__date=day)
#     #             ),
#     #             total_kill_house_free_sale_bars_free_weight=Sum(
#     #                 'real_weight_of_carcasses',
#     #                 filter=Q(quota='free', production_date__date=day)
#     #             ),
#     #         )
#     #
#     #         segmentations_info = segmentations.aggregate(
#     #             segmentations_governmental_weight=Sum(
#     #                 'weight', filter=Q(quota='governmental', production_date__date=day)
#     #             ),
#     #             segmentations_free_weight=Sum(
#     #                 'weight', filter=Q(quota='free', production_date__date=day)
#     #             ),
#     #         )
#     #
#     #         pos_allocated_weight_info = transactions.aggregate(
#     #             pos_governmental_allocated_weight=Sum(
#     #                 'cur_weight', filter=Q(price_approved=True, transaction__date__date=day)
#     #             ),
#     #             pos_free_allocated_weight=Sum(
#     #                 'cur_weight', filter=Q(price_approved=False, transaction__date__date=day)
#     #             ),
#     #         )
#     #
#     #         archives_info = archives.aggregate(
#     #             total_archive_governmental_weight=Sum('weight', filter=Q(date__date=day, quota='governmental')),
#     #             total_archive_free_weight=Sum('weight', filter=Q(date__date=day, quota='free')),
#     #         )
#     #
#     #         total_kill_house_request_governmental_weight = kill_house_requests_info['total_kill_house_request_governmental_weight'] or 0
#     #         total_kill_house_request_free_weight = kill_house_requests_info['total_kill_house_request_free_weight'] or 0
#     #         total_kill_house_free_buying_bars_weight = kill_house_free_buying_bars_info['total_kill_house_free_buying_bars_weight'] or 0
#     #         total_kill_house_allocations_governmental_weight = kill_house_allocations_info['total_kill_house_allocations_governmental_weight'] or 0
#     #         total_kill_house_allocations_free_weight = kill_house_allocations_info['total_kill_house_allocations_free_weight'] or 0
#     #         total_kill_house_free_sale_bars_governmental_weight = kill_house_free_sale_bars_info['total_kill_house_free_sale_bars_governmental_weight'] or 0
#     #         total_kill_house_free_sale_bars_free_weight = kill_house_free_sale_bars_info['total_kill_house_free_sale_bars_free_weight'] or 0
#     #         segmentations_governmental_weight = segmentations_info['segmentations_governmental_weight'] or 0
#     #         segmentations_free_weight = segmentations_info['segmentations_free_weight'] or 0
#     #         pos_governmental_allocated_weight = pos_allocated_weight_info['pos_governmental_allocated_weight'] or 0
#     #         pos_free_allocated_weight = pos_allocated_weight_info['pos_free_allocated_weight'] or 0
#     #         total_archive_governmental_weight = archives_info['total_archive_governmental_weight'] or 0
#     #         total_archive_free_weight = archives_info['total_archive_free_weight'] or 0
#     #
#     #         total_governmental_input = total_kill_house_request_governmental_weight
#     #         total_free_input = total_kill_house_request_free_weight + total_kill_house_free_buying_bars_weight
#     #
#     #         total_governmental_output = (
#     #             total_kill_house_allocations_governmental_weight +
#     #             total_kill_house_free_sale_bars_governmental_weight +
#     #             segmentations_governmental_weight +
#     #             int(pos_governmental_allocated_weight / 1000)
#     #         )
#     #
#     #         total_free_output = (
#     #             total_kill_house_allocations_free_weight +
#     #             total_kill_house_free_sale_bars_free_weight +
#     #             segmentations_free_weight +
#     #             int(pos_free_allocated_weight / 1000)
#     #         )
#     #
#     #         governmental_amount = (
#     #                                           total_governmental_input - total_governmental_output) - total_archive_governmental_weight
#     #         free_amount = (total_free_input - total_free_output) - total_archive_free_weight
#     #
#     #         governmental_data = {
#     #             'day': day,
#     #             'amount': governmental_amount,
#     #             'active': True if day in target_days else False,
#     #         }
#     #         free_data = {
#     #             'day': day,
#     #             'amount': free_amount,
#     #             'active': True if day in target_days else False,
#     #         }
#     #
#     #         governmental_list.append(governmental_data)
#     #         free_list.append(free_data)
#     #
#     #     final_dict['governmental'] = governmental_list
#     #     final_dict['free'] = free_list
#     #
#     #     return Response(final_dict, status=status.HTTP_200_OK)

class KillHouseRemainWeightViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]

    def get(self, request):
        target_date = request.GET.get('date')
        user = SystemUserProfile.objects.get(user=request.user, trash=False)

        kill_house = KillHouse.objects.filter(kill_house_operator__user=user).first()
        product = RolesProducts.objects.filter(kill_house=kill_house, trash=False, name='مرغ گرم').first()

        today = datetime.now().date() if not target_date else datetime.strptime(target_date, "%Y-%m-%d").date()
        month_ago = today - timedelta(days=30)
        yesterday = today - timedelta(days=1)
        two_days_ago = yesterday - timedelta(days=1)

        days = [month_ago + timedelta(days=i) for i in range(31)]
        target_days = {two_days_ago, yesterday, today}
        req_vals = list(
            KillHouseRequest.objects.filter(
                input_warehouse=kill_house,
                kill_request__recive_date__date__gte=month_ago,
                kill_request__recive_date__date__lte=today,
                ware_house_confirmation=True,
                trash=False,
                calculate_status=True,
                warehouse=True
            ).values(
                "kill_request__recive_date__date",
                "ware_house_accepted_real_weight",
                "province_request__poultry_request__free_sale_in_province"
            )
        )

        free_buy_vals = list(
            KillHouseFreeBarInformation.objects.filter(
                trash=False,
                calculate_status=True,
                warehouse=True,
                date__date__gte=month_ago,
                date__date__lte=today,
                input_warehouse=kill_house
            ).exclude(entered_message='ورود به انبار مجازی')
                .values("date__date", "weight_of_carcasses")
        )

        alloc_vals = list(
            StewardAllocation.objects.filter(
                kill_house=kill_house,
                trash=False,
                calculate_status=True,
                warehouse=True,
                receiver_state__in=('pending', 'accepted'),
                production_date__date__gte=month_ago,
                production_date__date__lte=today
            ).values(
                "production_date__date",
                "quota",
                "real_weight_of_carcasses"
            )
        )

        free_sale_vals = list(
            KillHouseFreeSaleBarInformation.objects.filter(
                kill_house=kill_house,
                production_date__date__gte=month_ago,
                production_date__date__lte=today,
                trash=False,
                calculate_status=True,
                warehouse=True
            ).values("production_date__date", "quota", "real_weight_of_carcasses")
        )

        seg_vals = list(
            PosSegmentation.objects.filter(
                kill_house=kill_house,
                production_date__date__gte=month_ago,
                production_date__date__lte=today,
                trash=False,
                warehouse=True
            ).values("production_date__date", "quota", "weight")
        )

        pos_vals = list(
            ProductsTransactions.objects.filter(
                product=product,
                transaction__paid=True,
                transaction__date__date__gte=month_ago,
                transaction__date__date__lte=today,
                trash=False,
                warehouse=True
            ).values(
                "transaction__date__date",
                "price_approved",
                "cur_weight"
            )
        )

        arch_vals = list(
            WarehouseArchive.objects.filter(
                kill_house=kill_house,
                warehouse=True,
                trash=False
            ).values("date__date", "quota", "weight")
        )

        req_daily = {}
        for r in req_vals:
            d = r["kill_request__recive_date__date"]
            w = r["ware_house_accepted_real_weight"] or 0
            if d not in req_daily:
                req_daily[d] = {"governmental": 0, "free": 0}
            if r["province_request__poultry_request__free_sale_in_province"]:
                req_daily[d]["free"] += w
            else:
                req_daily[d]["governmental"] += w

        free_buy_daily = {}
        for r in free_buy_vals:
            d = r["date__date"]
            w = r["weight_of_carcasses"] or 0
            free_buy_daily[d] = free_buy_daily.get(d, 0) + w

        alloc_daily = {}
        for r in alloc_vals:
            d = r["production_date__date"]
            w = r["real_weight_of_carcasses"] or 0
            q = r["quota"]
            if d not in alloc_daily:
                alloc_daily[d] = {"governmental": 0, "free": 0}
            alloc_daily[d][q] += w

        free_sale_daily = {}
        for r in free_sale_vals:
            d = r["production_date__date"]
            w = r["real_weight_of_carcasses"] or 0
            q = r["quota"]
            if d not in free_sale_daily:
                free_sale_daily[d] = {"governmental": 0, "free": 0}
            free_sale_daily[d][q] += w

        seg_daily = {}
        for r in seg_vals:
            d = r["production_date__date"]
            w = r["weight"] or 0
            q = r["quota"]
            if d not in seg_daily:
                seg_daily[d] = {"governmental": 0, "free": 0}
            seg_daily[d][q] += w

        pos_daily = {}
        for r in pos_vals:
            d = r["transaction__date__date"]
            w = r["cur_weight"] or 0
            if d not in pos_daily:
                pos_daily[d] = {"governmental": 0, "free": 0}
            if r["price_approved"]:
                pos_daily[d]["governmental"] += w
            else:
                pos_daily[d]["free"] += w

        arch_daily = {}
        for r in arch_vals:
            d = r["date__date"]
            w = r["weight"] or 0
            q = r["quota"]
            if d not in arch_daily:
                arch_daily[d] = {"governmental": 0, "free": 0}
            arch_daily[d][q] += w

        governmental_list = []
        free_list = []

        for day in days:
            gov_in = req_daily.get(day, {}).get("governmental", 0)
            free_in = req_daily.get(day, {}).get("free", 0) + free_buy_daily.get(day, 0)

            gov_out = (
                    alloc_daily.get(day, {}).get("governmental", 0) +
                    free_sale_daily.get(day, {}).get("governmental", 0) +
                    seg_daily.get(day, {}).get("governmental", 0) +
                    (pos_daily.get(day, {}).get("governmental", 0) // 1000)
            )

            free_out = (
                    alloc_daily.get(day, {}).get("free", 0) +
                    free_sale_daily.get(day, {}).get("free", 0) +
                    seg_daily.get(day, {}).get("free", 0) +
                    (pos_daily.get(day, {}).get("free", 0) // 1000)
            )

            gov_remain = gov_in - gov_out - arch_daily.get(day, {}).get("governmental", 0)
            free_remain = free_in - free_out - arch_daily.get(day, {}).get("free", 0)

            governmental_list.append({
                "day": day,
                "amount": gov_remain if gov_remain > 0 else 0,
                "active": day in target_days,
            })

            free_list.append({
                "day": day,
                "amount": free_remain if free_remain > 0 else 0,
                "active": day in target_days,
            })

        return Response({
            "governmental": governmental_list,
            "free": free_list
        }, status=status.HTTP_200_OK)


# class TotalKillHouseRemainWeightViewSet(GenericAPIView):
#     permission_classes = [TokenHasReadWriteScope]
#     serializer_class = TotalKillHouseRemainWeightViewSetSerializer
#     pagination_class = CustomPagination
#     filter_backends = [DjangoFilterBackend]
#     filterset_class = KillHouseFilterSet
#     filterset_fields = [
#         'name',
#         'kill_house_operator__user__mobile',
#         'kill_house_operator__user__fullname',
#         'kill_house_operator__user__first_name',
#         'kill_house_operator__user__last_name'
#
#     ]
#
#     def get(self, request):
#
#         kill_house_filters = {'out_province': False, 'trash': False, 'total_remain_warehouse_weight__gt': 0}
#         kill_houses = KillHouse.objects.filter(**kill_house_filters).order_by('id', 'killer')
#
#         if 'search' in request.GET:
#             kill_house_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=kill_houses
#                         )
#                         ).filter():
#                             ps = self.filterset_class(data=query, queryset=kill_houses)
#                             kill_house_list = ps.filter()
#                     kill_houses = [] if len(
#                         kill_house_list) == 0 else kill_house_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(kill_houses)
#         if page is not None:
#             serializer = self.get_serializer(page, many=True)
#             return self.get_paginated_response(serializer.data)
#
#         serializer = self.serializer_class(kill_houses, many=True)
#         return Response(serializer.data, status=status.HTTP_200_OK)
class TotalKillHouseRemainWeightViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = TotalKillHouseRemainWeightViewSetSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        quota = request.GET.get("quota")
        kill_house_filters = {'out_province': False, 'trash': False, 'total_remain_warehouse_weight__gt': 0}
        kill_houses = KillHouse.objects.filter(**kill_house_filters).order_by('id', 'killer')

        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_list

        all_data = TotalKillHouseRemainWeightViewSetSerializer(kill_houses, many=True).data
        if quota in ("governmental", "free"):
            filtered = []
            today = datetime.today().date()
            two_days_ago = today - timedelta(days=2)

            for item in all_data:
                info = item.get("info")
                if not info:
                    continue

                for row in info.get(quota, []):
                    day = row["day"]
                    amount = row["amount"]
                    if amount > 0 and day < two_days_ago:
                        filtered.append(item)
                        break

            all_data = filtered

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

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

        # serializer = self.serializer_class(kill_houses, many=True)
        return Response(all_data, status=status.HTTP_200_OK)


class TotalKillHouseWarehouseArchiveDashboardViewSet(GenericAPIView):
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = TotalKillHouseWarehouseArchiveDashboardSerializer
    pagination_class = CustomPagination
    filter_backends = [DjangoFilterBackend]
    filterset_class = KillHouseFilterSet
    filterset_fields = [
        'name',
        'kill_house_operator__user__mobile',
        'kill_house_operator__user__fullname',
        'kill_house_operator__user__first_name',
        'kill_house_operator__user__last_name'

    ]

    def get(self, request):
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        archives_filters = {"trash": False, "kill_house__isnull": False}
        if date1:
            archives_filters['create_date__date__gte'] = date1
            archives_filters['create_date__date__lte'] = date2

        archives = WarehouseArchive.objects.filter(**archives_filters)
        kill_houses = KillHouse.objects.filter(id__in=archives.values_list('kill_house__id', flat=True), trash=False)
        if 'search' in request.GET:
            kill_house_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=kill_houses
                        )
                        ).filter():
                            ps = self.filterset_class(data=query, queryset=kill_houses)
                            kill_house_list = ps.filter()
                    kill_houses = [] if len(
                        kill_house_list) == 0 else kill_house_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(kill_houses)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'date1': date1, 'date2': date2})
            return self.get_paginated_response(serializer.data)

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


def fix_wage(request):
    kill_house_requests = KillHouseRequest.objects.filter(trash=True, return_trash=True)
    kill_house_requests_values = kill_house_requests.values_list('province_kill_request__id', flat=True).distinct()
    province_requests = ProvinceKillRequest.objects.filter(trash=True, id__in=kill_house_requests_values,
                                                           return_trash=True)
    return HttpResponse(province_requests.count())


class KillHouseLock(APIView):

    def get(self, request):

        wage_lock = False
        ware_house_lock = False
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()
        total_unpaid_wage = get_finance_info(kill_house)['total_price']
        if kill_house.killer and kill_house.type=='public':
            slaughter_transactions = InternalTransaction.objects.filter(kill_house=kill_house,parent_kill_house=kill_house,
                                                                        status='completed',
                                                                        trash=False)
        else:
            slaughter_transactions = InternalTransaction.objects.filter(
                Q(kill_house=kill_house) | Q(parent_kill_house=kill_house),
                status='completed',
                trash=False)

        total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[
                              'total'] or 0
        total_unpaid_wage -= total_paid_wage

        if kill_house_purchase:
            if kill_house_purchase.limitation == True:

                if kill_house_purchase.limitation_number <= total_unpaid_wage:
                    wage_lock = True

        if kill_house.ware_house_remaining_weight_limitation_status:
            if kill_house.total_remain_warehouse_governmental_weight > kill_house.ware_house_remaining_weight_limitation:
                ware_house_lock = True

        if kill_house.ware_house_remaining_percent_limitation_status:
            if not check_kill_house_remain_limitation_weight(kill_house):
                ware_house_lock = True

        result = {
            'wage': total_unpaid_wage,
            'wage_lock': wage_lock,
            'ware_house_lock': ware_house_lock
        }

        return Response (result,status=status.HTTP_200_OK)
