import hashlib
import uuid
import random
import cryptocode
import requests
import jdatetime
import datetime
import openpyxl

from django.http import HttpResponse
from django.utils import timezone
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from django.db.models import Q, Sum
from datetime import timedelta

from oauth2_provider.models import AccessToken

from general_urls import base_url_for_sms_report
from panel.filterset import \
    PoultryRequestFilterSet, KillRequestFilterSet, GuildsFilterSet, ProvinceKillRequestNewFilterSet, \
    KillHouseRequestFilterSet, ChainAllocationFilterSet
from django.db import models

from django.db.models import F, Count

from panel.admin import PROJECT_API_KEY
from rest_framework.decorators import permission_classes, api_view
from .convert_date import convert_to_miladi, convert_to_shamsi
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, QueryDict
from rest_framework.permissions import AllowAny

from .helper import build_query
from .helper_excel import shamsi_date, create_header, excel_description, create_header_freez, create_value, \
    percent_of_losses, start_excel, close_excel, convert_str_to_date
from .models import Poultry, PoultryHatching, PoultryRequest, ProvinceKillRequest, KillHouseRequest, VetFarm, \
    KillRequest, KillHouseVet, KillHouseAssignmentInformation, VetCheckRequest, \
    ProvinceFactorToKillHouse, ProvinceCheckOperatorRequest, KillHouseFactorToProvince, KillHouseWareHouse, \
    KillHouseFreeBarInformation, Guilds, Wallet, Steward, StewardAllocation, KillHouseOperator, KillHousePercentage, \
    CityOperator, KillHouseDriver, \
    ProvinceOperator, POSMachine, StewardWareHouse, Vet, WagePayment, ChainCompany, ReportsUsers, \
    PoultryRequestQuarantineCode, ChainAllocation
from authentication.models import (
    UserProfile,
    User,
    BankCard,
    SystemUserProfile,
    SystemAddress,
    City,
    Province, ExternalTransaction
)

from .models import (
    KillHouse,
    KillHouseADDCAR
)
from django.contrib.auth.models import Group
from rest_framework.response import Response
from authentication.models import Address
from django.shortcuts import get_object_or_404

ARTA_REGISTER = "https://userbackend.rasadyar.com/api/register_all/"


# تابع برای ثبت اطلاعات مرغداران از سامانه سماسط
@api_view(["POST"])
@csrf_exempt
@permission_classes([AllowAny])
def user_excel(request):
    file = request.FILES['file'].read()
    read = openpyxl.load_workbook(BytesIO(file), data_only=True)
    sheet = read.active
    group = Group.objects.get(id=1)
    password = '00100'
    hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 1:
            continue
        if row[3] is not None:
            last_name = row[3]
        else:
            last_name = ''

        first_name = row[2]
        mobile = "0" + str(row[4])
        system_profile = SystemUserProfile.objects.filter(mobile=mobile, trash=False).exists()
        if not system_profile:
            data = {
                "username": mobile,
                "first_name": first_name,
                "last_name": last_name,
                "password": hashed_password,
                "national_code": '0',
                "role": "Poultry",
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                user = User.objects.filter(username=mobile).first()
                if not user:
                    user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
                    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=mobile,
                    first_name=str(first_name),
                    last_name=str(last_name),
                    fullname=str(first_name) + ' ' + str(last_name),
                    user=user,
                    base_order=base_id,
                    password=password,
                    birthday=str(datetime.datetime.now().date()),
                )
                system_profile.save()
                system_profile.role.add(group)
                wallet = Wallet()
                wallet.save()
                poultry = Poultry(
                    unit_name=row[7],
                    system_code=row[10],
                    epidemiological_code=row[9],
                    breeding_unique_id=row[11],
                    unit_status=row[13],
                    samasat_user_code=row[0],
                )
                address = SystemAddress()
                address.save()
                poultry.address = address
                poultry.user = system_profile
                poultry.wallet = wallet
                poultry.save()
        # send_sms(userprofile.mobile, rand)
    return JsonResponse({"Msg": "Done"})


# تابع برای آپدیت اطلاعات ثبت شذه مرغداران از سامانه سماسط
@api_view(["POST"])
@csrf_exempt
@permission_classes([AllowAny])
def user_excel_update(request):
    file = request.FILES['file'].read()
    read = openpyxl.load_workbook(filename=BytesIO(file), data_only=True)
    sheet = read.active
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i == 0:
            continue
        if row[6] is not None:
            if Poultry.objects.filter(breeding_unique_id=row[6]).exists():
                poultry = Poultry.objects.get(breeding_unique_id=row[6])
                poultry.total_capacity = row[9]
                poultry.save()
                poultry.fullname = row[8]
                poultry.unit_name = row[7]
                poultry.operating_licence_capacity = 0
                poultry.system_code = row[3]
                poultry.epidemiological_code = row[5]
                poultry.breeding_unique_id = row[6]
                poultry.licence_number = row[10]
                poultry.health_certificate_number = row[11]
                poultry.number_of_requests = row[12]
                poultry.number_of_incubators = row[15]
                poultry.herd_age_by_day = row[16]
                poultry.herd_age_by_week = row[17]
                poultry.number_of_party = row[18]
                poultry.communication_type = row[19]
                poultry.cooperative = ""
                poultry.save()
                if row[13] != 'تاریخ جوجه ریزی':
                    date_of_incubators = row[13]
                    date_incube = date_of_incubators.split('/')
                    date = convert_to_miladi(
                        year=int(date_incube[0]),
                        month=int(date_incube[1]),
                        day=int(date_incube[2])
                    )
                    poultry.incubation_date = date
                if row[14] != 'تاریخ آخرین پارتی':
                    last_party_date = row[14].split('/')
                    party_date = convert_to_miladi(
                        year=int(last_party_date[0]),
                        month=int(last_party_date[1]),
                        day=int(last_party_date[2])
                    )
                    poultry.last_party_date = party_date
                if row[1] != 'استان' and row[2] != 'شهر':
                    if not Province.objects.filter(name=row[1]).exists():
                        province = Province(name=row[1])
                        province.save()
                    else:
                        province = Province.objects.get(name=row[1])

                    if not City.objects.filter(name=row[2]).exists():
                        city = City(name=row[2])
                        city.save()
                    else:
                        city = City.objects.get(name=row[2])

                    # if poultry.address.city != row[2] and poultry.address.province != row[1]:
                    poultry.address.city = city
                    poultry.address.province = province
                    poultry.address.save()
                    poultry.user.province = province
                    poultry.user.city = city
                    poultry.user.save()
                poultry.save()
    return JsonResponse({"msg": "Done"})


# تابع برای ثبت نام کاربر درون سیستم
# @api_view(["POST"])
# @csrf_exempt
# @permission_classes([AllowAny])
# def test_register(request):
#     # last_user = UserProfile.objects.all().last().base_orde + 1
#     last_user = UserProfile.objects.all()
#     if len(last_user) > 0:
#         last_user = last_user.last().base_order + 1
#     else:
#         last_user = 1000
#     rand = random.randint(100000, 999000)
#     str_rand = str(rand)
#     password = cryptocode.encrypt(str_rand, str_rand)
#     first = "آقای"
#     mobile = "09121196753"
#     last = "امیدی"
#     userprofile = UserProfile(
#         key=uuid.uuid4(),
#         company="",
#         fullname=first + " " + last,
#         first_name=first,
#         last_name=last,
#         natinal_id="",
#         mobile=mobile,
#         birthday="",
#         image="",
#         state="",
#         unit_name="",
#         gis_code="",
#         operating_licence_capacity=0,
#         number_of_halls=0,
#         tenant="",
#         person_type="",
#         economic_code="",
#         system_code="",
#         epidemiological_code="",
#         breeding_unique_id="",
#         total_capacity=0,
#         licence_number="",
#         health_certificate_number="",
#         number_of_requests=0,
#         number_of_incubators=0,
#         herd_age_by_day=0,
#         herd_age_by_week=0,
#         number_of_party=0,
#         communication_type="",
#         cooperative="",
#         unit_status="",
#         samasat_user_code="",
#         base_order=last_user,
#         password=str_rand
#     )
#     userprofile.save()
#     user = User(
#         first_name=first,
#         username=userprofile.key,
#         password=password,
#     )
#     user.save()
#     userprofile.user = user
#     userprofile.save()
#     # send_sms(mobile, rand)
#     return Response("ok")


# تابع برای ثبت کستارگاه ار لیست اکسل
@api_view(["POST"])
@permission_classes([TokenHasReadWriteScope])
@csrf_exempt
def upload_kill_house(request):
    last_user = UserProfile.objects.all()
    if len(last_user) > 0:
        last_user = last_user.last().base_order + 1
    else:
        last_user = 1000
    rand = random.randint(100000, 999000)
    str_rand = str(rand)
    password = cryptocode.encrypt(str_rand, str_rand)
    role = Group.objects.get(id=4)
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i == 0:
            continue
        [name, family, mobile, national_id, kill_hose, province, city, address, capocity, phone, name_of_bank_user,
         bank_name, shaba,
         account, card
         ] = row
        userprofile = UserProfile(
            key=uuid.uuid4(),
            fullname=name + " " + family,
            first_name=name,
            last_name=family,
            mobile=str(mobile),
            natinal_id=national_id
        )
        userprofile.save()
        user = User(
            first_name=rand,
            last_name=family,
            username=mobile,
            password=password,
        )
        user.save()
        address = Address(province=province, city=city, address=address)
        address.save()
        userprofile.user = user
        userprofile.role = role
        userprofile.address = address
        userprofile.base_order = last_user
        userprofile.save()
        kill__house = KillHouse(user=userprofile, address=address, capacity=capocity, name=kill_hose, phone=phone)
        kill__house.save()
        bank = BankCard(name_of_bank_user=name_of_bank_user, bank_name=bank_name, card=str(card), shaba=str(shaba),
                        account=str(account))
        bank.save()
        userprofile.user_bank_info = bank
        userprofile.save()

    return Response(200)


# تابع برای ثبت ماشین های  کستارگاه برای کشتارگاه های ثبت شده ار لیست اکسل
# @api_view(["POST"])
# @permission_classes([TokenHasReadWriteScope])
# @csrf_exempt
# def upload_kill_house_cars(request):
#     file = request.FILES['file'].read()
#     wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
#     sheet = wb_obj.active
#     for i, row in enumerate(sheet.iter_rows(values_only=True)):
#         if i == 0:
#             continue
#         [kill_house_name, national_id, driver_name, driver_mobile, type_car, type_weight, pelak, capacity,
#          weight_without_load,
#          health_code
#          ] = row
#         user = UserProfile.objects.filter(natinal_id=str(national_id))
#         id = user[0].id
#         userprofile = UserProfile.objects.get(id=id)
#         kill_house = KillHouse.objects.get(user=userprofile, name=kill_house_name)
#         car_dict2 = {}
#         if kill_house.car == None:
#             kill_house.car = []
#             kill_house.save()
#         car_list1 = list(kill_house.car)
#         add_car = KillHouseADDCAR(
#             kill_house=kill_house,
#             driver_name=driver_name,
#             driver_mobile=driver_mobile,
#             type_car=type_car,
#             type_weight=type_weight,
#             pelak=pelak,
#             capocity=capacity,
#             weight_without_load=weight_without_load,
#             health_code=health_code
#
#         )
#         add_car.save()
#         car_dict2.update(
#             {"driver_name": add_car.driver_name,
#              "driver_mobile": add_car.driver_mobile, "pelak": add_car.pelak,
#              "quantity": add_car.capocity,
#              "type_car": add_car.type_car, "health_code": add_car.health_code})
#         car_list1.append(car_dict2)
#         kill_house.car = car_list1
#         kill_house.save()
#
#     return Response(200)


@api_view(["POST"])
@permission_classes([TokenHasReadWriteScope])
@csrf_exempt
def find_password(request):
    user = UserProfile.objects.get(mobile=request.data['mobile'])
    decrypted_password = cryptocode.decrypt(user.user.password, user.user.password)
    return HttpResponse(decrypted_password)


# تابع برای ارسال اطلاعات برای مرغدار
# @api_view(["POST"])
# @csrf_exempt
# @permission_classes([AllowAny])
# def send_info_poultry(request):
#     users = UserProfile.objects.filter(role_id=1).order_by('id')
#     for user in users:
#         mobile = user.mobile
#         password = user.password
#         send_sms(mobile, password)
#     return Response({"result": "done!"}, status=status.HTTP_200_OK)


# تابع برای ارسال اطلاعات برای کشتارگاه
# @api_view(["POST"])
# @csrf_exempt
# @permission_classes([AllowAny])
# def send_info_kill_house(request):
#     users = UserProfile.objects.filter(role_id=4).order_by('id')
#     for user in users:
#         mobile = user.mobile
#         password = user.password
#         send_sms_kill_house(mobile, password)
#     return Response({"result": "done!"}, status=status.HTTP_200_OK)


# تابع برای ارسال اطلاعات برای شهرستان
# @api_view(["POST"])
# @csrf_exempt
# @permission_classes([AllowAny])
# def send_info_city(request):
#     users = UserProfile.objects.filter(role_id=2).order_by('id')
#     for user in users:
#         mobile = user.mobile
#         password = user.password
#         send_sms_city(mobile, password)
#     return Response({"result": "done!"}, status=status.HTTP_200_OK)


#
# def poultry(request):
#     list2 = []
#     users = SystemUserProfile.objects.filter(role__name='Poultry', trash=False).order_by('create_date')
#     for user in users:
#         list2.append(user)
#
#     excel_options = ['نام و نام خانوادگی', 'شماره همراه'
#                      ]
#     output = BytesIO()
#     workbook = xlsxwriter.Workbook(output)
#     worksheet = workbook.add_worksheet()
#     for count in range(len(excel_options)):
#         worksheet.write(0, count, excel_options[count])
#     l = 0
#     for user in users:
#         l += 1
#
#         list1 = [user.fullname, user.mobile]
#         for item in range(len(list1)):
#             worksheet.write(l, item, list1[item])
#
#         list1 = []
#
#     workbook.close()
#     output.seek(0)
#
#     response = HttpResponse(content_type='application/vnd.ms-excel')
#
#     response['Content-Disposition'] = 'attachment;filename="Reporting.xlsx"'
#     response.write(output.getvalue())
#
#     return response


# def hatching_report_excel(request):
#     hatching_list = []
#     today = datetime.now().date()
#     if 'age' in request.GET:
#         hatchings = PoultryHatching.objects.filter(trash=False)
#         input_age = int(request.GET['age'])
#         if hatchings.count() > 0:
#             for hatching in hatchings:
#                 age = (today - hatching.date.date()).days + 1
#                 if int(age) == input_age:
#                     hatching_list.append(hatching)
#
#         excel_options = [
#             'نام و نام خانوادگی',
#             'تاریخ جوجه ریزی',
#             'سن مرغ',
#             'تعداد جوجه ریزی',
#             'تعداد باقی مانده',
#             'شماره همراه',
#             'استان',
#             'شهرستان',
#         ]
#         output = BytesIO()
#         workbook = xlsxwriter.Workbook(output, {'strings_to_numbers': True})
#         worksheet = workbook.add_worksheet()
#
#         # Set the cell format for right alignment
#         right_align_format = workbook.add_format({'align': 'right'})
#
#         # Adjust the column width in reverse order
#         for count, option in enumerate(reversed(excel_options)):
#             worksheet.write(0, count, option)
#             worksheet.set_column(count, count, None, right_align_format)
#
#         l = 0
#         for hatch in hatching_list:
#             l += 1
#             age = (today - hatch.date.date()).days + 1
#             gregorian_date = jdatetime.date.fromgregorian(
#                 day=hatch.date.day,
#                 month=hatch.date.month,
#                 year=hatch.date.year
#             )
#             incubation_date = gregorian_date
#
#             list1 = [
#                 hatch.poultry.user.fullname,
#                 str(incubation_date),
#                 str(age),
#                 hatch.quantity,
#                 hatch.left_over,
#                 hatch.poultry.user.mobile,
#                 hatch.poultry.address.province.name,
#                 hatch.poultry.address.city.name,
#             ]
#             for item in range(len(list1)):
#                 worksheet.write(l, item, list1[item])
#             list1 = []
#         workbook.close()
#         output.seek(0)
#
#         response = HttpResponse(content_type='application/vnd.ms-excel')
#         response['Content-Disposition'] = 'attachment;filename="Reporting.xlsx"'
#         response.write(output.getvalue())
#
#         return response


# def hatching_report_excel(request):
#     hatching_list = []
#     today = datetime.now().date()
#     if 'age' in request.GET:
#         hatchings = PoultryHatching.objects.filter(trash=False)
#         input_age = int(request.GET['age'])
#         if hatchings.count() > 0:
#             for hatching in hatchings:
#                 age = (today - hatching.date.date()).days + 1
#                 if int(age) == input_age:
#                     hatching_list.append(hatching)
#
#         excel_options = [
#             'نام و نام خانوادگی',
#             'تاریخ جوجه ریزی',
#             'سن مرغ',
#             'تعداد جوجه ریزی',
#             'تعداد باقی مانده',
#             'شماره همراه',
#             'استان',
#             'شهرستان',
#         ]
#         output = BytesIO()
#         workbook = Workbook()
#         worksheet = workbook.active
#
#         # Set the right-to-left direction
#         worksheet.sheet_view.rightToLeft = True
#
#         # Set the fill color for the first row
#         yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
#         for col_num, option in enumerate(excel_options, 1):
#             col_letter = get_column_letter(col_num)
#             cell = worksheet.cell(row=1, column=col_num, value=option)
#             cell.alignment = Alignment(horizontal='center')
#             cell.fill = yellow_fill
#
#             # Set the font size for the first row
#             cell.font = Font(size=12, bold=True)
#
#             # Set the width of the column
#             worksheet.column_dimensions[col_letter].width = 20.01
#
#         l = 0
#         for hatch in hatching_list:
#             l += 1
#             age = (today - hatch.date.date()).days + 1
#             gregorian_date = jdatetime.date.fromgregorian(
#                 day=hatch.date.day,
#                 month=hatch.date.month,
#                 year=hatch.date.year
#             )
#             incubation_date = gregorian_date
#
#             list1 = [
#                 hatch.poultry.user.fullname,
#                 str(incubation_date),
#                 str(age),
#                 hatch.quantity,
#                 hatch.left_over,
#                 hatch.poultry.user.mobile,
#                 hatch.poultry.address.province.name,
#                 hatch.poultry.address.city.name,
#             ]
#             for item in range(len(list1)):
#                 cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
#                 cell.alignment = Alignment(horizontal='center')
#
#             list1 = []
#
#         workbook.save(output)
#         output.seek(0)
#
#         response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
#         response['Content-Disposition'] = 'attachment; filename="Reporting.xlsx"'
#         response.write(output.getvalue())
#
#         return response


def vet_check_excel(request):
    kill_house_req = KillHouseRequest.objects.filter(trash=False, clearance_code=None,
                                                     ).order_by('-create_date')

    excel_options = [
        'نام و نام خانوادگی مرغدار',
        'تاریخ',
        'نام دکتر ',
        'تعداد بار',
        'کشتارگاه',
        'کد بهداشتی',
    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    # worksheet.merge_cells(start_row=1, end_row=2, start_column=1, end_column=1)
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    l = 0

    for kill in kill_house_req:
        l += 1
        vet_farm = VetFarm.objects.filter(trash=False, poultry=kill.province_request.poultry_request.poultry)
        for vets in vet_farm:
            date = jdatetime.date.fromgregorian(
                day=kill.province_request.poultry_request.send_date.day,
                month=kill.province_request.poultry_request.send_date.month,
                year=kill.province_request.poultry_request.send_date.year
            )
            list1 = [
                kill.province_request.poultry_request.poultry.unit_name,
                str(date),
                vets.vet.user.fullname,
                kill.quantity,
                kill.kill_request.kill_house.name,
                kill.traffic_code
            ]

            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="Reporting.xlsx"'
    response.write(output.getvalue())
    return response


def kill_house_request_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    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',
        'poultry__user__fullname',
        'poultry__user__mobile',
        'poultry__unit_name',
    ]
    filtered_kill_reqs = (
        KillRequest.objects.filter(trash=False, recive_date__date__gte=date1, recive_date__date__lte=date2,
                                   poultry__isnull=True)
            .select_related('kill_house').order_by('-recive_date'))
    if 'search' in request.GET:
        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=filtered_kill_reqs
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=filtered_kill_reqs)
                        filtered_kill_reqs = ps.filter()
    excel_options = [
        'ردیف',
        'نام خریدار',
        'ماهیت خریدار',
        'محل کشتار',
        'تاریخ ایجاد درخواست',
        'تعداد درخواست(قطعه)',
        'مانده(قطعه)',
        'تعداد تخصیص داده شده(قطعه)',
        'زمان دریافت',
        'تاریخ درخواستی کشتار',
        'وضعیت تایید استان',
    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')

    create_header_freez(worksheet, excel_options, 1, 5, 6, height=30, width=20.1)
    l = 4
    m = 1

    worksheet['A2'] = f'اعلام نیاز خریداران و کشتارگاه ها'

    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range2 = 'A2:B2'

    worksheet.merge_cells(merge_range2)
    worksheet['A2'].font = Font(size=11)

    from_date_1 = shamsi_date(date1)
    to_date_1 = shamsi_date(date2)
    worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')

    merge_range1 = 'A3:B3'

    worksheet.merge_cells(merge_range1)

    worksheet['A3'].font = Font(color="C00000", bold=True)

    header_list = [
        'تعداد خریداران',
        'مجموع تعداد درخواست (قطعه)',
        'مانده(قطعه)',
        'مجموع تعداد تخصیص داده شده(قطعه)',

    ]

    create_header(worksheet, header_list, 3, 2, height=21, width=16.01)
    all_kill_capacity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity', 0)
    all_remain_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('remain_quantity')).get(
        'total_quantity', 0)
    if filtered_kill_reqs:
        for kill_request in filtered_kill_reqs:
            l += 1

            create_date = jdatetime.date.fromgregorian(
                day=kill_request.create_date.day,
                month=kill_request.create_date.month,
                year=kill_request.create_date.year,
            )
            recive_date = jdatetime.date.fromgregorian(
                day=kill_request.recive_date.day,
                month=kill_request.recive_date.month,
                year=kill_request.recive_date.year
            )

            if kill_request.kill_house.killer == False:
                killer = 'کشتارگاه'
            else:
                killer = 'کشتار کن'
            if kill_request.slaughter_house != None:
                kill_place = kill_request.slaughter_house.name
            else:
                kill_place = kill_request.kill_house.name
            if kill_request.province_state == 'accepted':
                province_state = 'تایید شده'
            elif kill_request.province_state == 'pending':
                province_state = 'در انتظار تایید'
            else:
                province_state = 'رد شده'

            allocation = kill_request.kill_capacity - kill_request.remain_quantity
            list1 = [
                m,
                kill_request.kill_house.name,
                killer,
                kill_place,
                str(create_date),
                kill_request.kill_capacity,
                kill_request.remain_quantity,
                allocation,
                kill_request.recive_time,
                str(recive_date),
                province_state,
            ]
            m += 1

            create_value(worksheet, list1, l + 1, 1)
    value_list = [
        len(filtered_kill_reqs),
        all_kill_capacity,
        all_remain_quantity,
        all_kill_capacity - all_remain_quantity if all_kill_capacity and all_remain_quantity != None else 0,

    ]

    create_value(worksheet, value_list, 3, 3)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        all_kill_capacity,
        all_remain_quantity,
        all_kill_capacity - all_remain_quantity if all_kill_capacity and all_remain_quantity != None else 0,
        '',
        '',
        '',

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="درخواست کشتارگاه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def request_report_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    today = datetime.datetime.now().date()
    poultry_reqs = PoultryRequest.objects.filter(trash=False).order_by('-send_date')
    filtered_poultry_reqs = [
        poultry_req for poultry_req in poultry_reqs
        if date1 <= poultry_req.send_date.date() <= date2
    ]

    excel_options = [
        'کد سفارش',
        'نام واحد',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'آدرس',
        'تاریخ جوجه ریزی',
        'تعداد کل جوجه ریزی',
        'سن مرغ',
        'کشتار شده',
        'تعداد باقی مانده',
        'نژاد',
        'تاریخ درخواست کشتار',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'زمان تخصیص',
        'ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس خریدار',
        'محل کشتار',
        'دامپزشک کشتارگاه',
        'تلفن دامپزشک کشتارگاه',
        'راننده',
        'تلفن راننده',
        'ماشین حمل',
        'کد بهداشتی حمل و نقل',
        'کد رهگیری سامانه قرنطینه',
        'تعداد تحویلی',
        'وزن بار',
        'تاریخ تخلیه کشتارگاه',
        'مبلغ فاکتور',
        'تاریخ پرداخت فاکتور',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0

    for filtered_poultry_req in filtered_poultry_reqs:
        l += 1
        vet_farm = VetFarm.objects.filter(poultry=filtered_poultry_req.poultry, trash=False).last()
        vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
        vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'

        age = (today - filtered_poultry_req.hatching.date.date()).days + 1
        gregorian_date = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.hatching.date.day,
            month=filtered_poultry_req.hatching.date.month,
            year=filtered_poultry_req.hatching.date.year
        )
        incubation_date = gregorian_date

        province_kill_reqs = ProvinceKillRequest.objects.filter(province_request__poultry_request=filtered_poultry_req,
                                                                trash=False)
        for province_kill_req in province_kill_reqs:
            kill_house_vet = KillHouseVet.objects.filter(kill_house=province_kill_req.kill_request.kill_house,
                                                         trash=False).last()
            kill_house_vet_name = kill_house_vet.vet.user.fullname if kill_house_vet else '-'
            kill_house_vet_mobile = kill_house_vet.vet.user.mobile if kill_house_vet else '-'
            date_of_inner_bar = '-'
            kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_req, trash=False)
            for kill_house_request in kill_house_requests:
                vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_request)
                killers = 'کشتارکن'
                if kill_house_request.killhouse_user.killer == False:
                    killers = 'کشتارگاه'
                assignment = KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_request).last()
                assignment_quantity = assignment.real_quantity if assignment else '-'
                assignment_weight = assignment.net_weight if assignment else '-'

                factor = ProvinceFactorToKillHouse.objects.filter(
                    province_check_info__kill_house_assignment__kill_house_request=kill_house_request).last()
                factor_amount = factor.total_price if factor else '-'
                date_factor = '-'
                factor_payment = KillHouseFactorToProvince.objects.filter(
                    province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request).last()
                if factor_payment:
                    date_factor = jdatetime.date.fromgregorian(
                        day=factor_payment.create_date.day,
                        month=factor_payment.create_date.month,
                        year=factor_payment.create_date.year
                    )
                date_of_kill = jdatetime.date.fromgregorian(
                    day=filtered_poultry_req.create_date.day,
                    month=filtered_poultry_req.create_date.month,
                    year=filtered_poultry_req.create_date.year
                )

                time = jdatetime.date.fromgregorian(
                    day=kill_house_request.create_date.day,
                    month=kill_house_request.create_date.month,
                    year=kill_house_request.create_date.year
                )
                for vet_checks in vet_check:
                    date_of_inner_bar = jdatetime.date.fromgregorian(
                        day=vet_checks.create_date.day,
                        month=vet_checks.create_date.month,
                        year=vet_checks.create_date.year
                    )

                code = kill_house_request.clearance_code if kill_house_request.clearance_code else '-'
                list1 = [
                    filtered_poultry_req.order_code,
                    filtered_poultry_req.poultry.unit_name,
                    filtered_poultry_req.poultry.user.fullname,
                    filtered_poultry_req.poultry.user.mobile,
                    filtered_poultry_req.poultry.user.city.name,
                    str(incubation_date),
                    filtered_poultry_req.hatching.quantity,
                    str(age),
                    filtered_poultry_req.quantity,
                    filtered_poultry_req.hatching.left_over,
                    filtered_poultry_req.hatching.chicken_breed,
                    str(date_of_kill),
                    vet_farm_name,
                    vet_farm_mobile,
                    str(time),
                    killers,
                    province_kill_req.kill_request.kill_house.name,
                    province_kill_req.kill_request.kill_house.phone,
                    province_kill_req.kill_request.kill_house.system_address.city.name,
                    province_kill_req.kill_request.kill_house.system_address.city.name,
                    kill_house_vet_name,
                    kill_house_vet_mobile,
                    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.traffic_code,
                    code,
                    assignment_quantity,
                    assignment_weight,
                    str(date_of_inner_bar),
                    factor_amount,
                    str(date_factor)
                ]

                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="Reporting.xlsx"'
    response.write(output.getvalue())

    return response


def allocated_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date() if 'start' in request.GET else now
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date() if 'end' in request.GET else now
    filterset_class = ProvinceKillRequestNewFilterSet
    if request.GET.get('type') == 'deleted':
        filtered_province_kill = ProvinceKillRequest.objects.filter(
            province_request__poultry_request__send_date__date__gte=date1,
            province_request__poultry_request__send_date__date__lte=date2, trash=True, delete_message__isnull=False) \
            .select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry',
            'province_request__poultry_request__poultry__user',
            'province_request__poultry_request__poultry__address').order_by('-create_date')
    else:
        filtered_province_kill = ProvinceKillRequest.objects.filter(
            province_request__poultry_request__send_date__date__gte=date1,
            province_request__poultry_request__send_date__date__lte=date2, trash=False).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry',
            'province_request__poultry_request__poultry__user',
            'province_request__poultry_request__poultry__address').order_by('-create_date')
    if 'role' in request.GET:
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        if request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(trash=False, user=user)
            filtered_province_kill_reqs = filtered_province_kill.filter(
                province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
        elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
            filtered_province_kill_reqs = filtered_province_kill.filter(
                province_request__poultry_request__poultry__user__city=user.city)
        elif request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(trash=False, kill_house_operator__user=user)
            filtered_province_kill_reqs = filtered_province_kill.filter(
                Q(killhouse_user__in=kill_house) | Q(
                    kill_request__slaughter_house__in=kill_house))
        else:
            filtered_province_kill_reqs = filtered_province_kill
    else:
        filtered_province_kill_reqs = filtered_province_kill
    value = request.GET.get('value')
    search = request.GET.get('filter')
    if value and search == 'search':
        if value != 'undefined' and value.strip():
            filtered_province_kill_reqs = filtered_province_kill.filter(
                build_query(filterset_class, value)
            )
    if request.GET.get('type') == 'deleted':
        excel_options = [
            'ردیف',
            'وضعیت',
            'کد سفارش',
            'نوع درخواست',
            'نوع فروش',
            'کشتار',
            'نام فارم',
            'نام و نام خانوادگی مرغدار',
            'موبایل',
            'شهر',
            'تاریخ کشتار',
            'تعداد کشتار',
            'وزن کشتار',
            'زمان تخصیص',
            'نوع تخصیص',
            'خریدار',
            'تعداد تخصیص داده شده',
            'مانده قابل تخصیص',
            ' تلفن خریدار',
            ' آدرس خریدار',
            'قیمت مرغدار',
            'قیمت کشتارگاه',
            'وضعیت تایید خریدار',
            'تخصیص ماشین',
            'پیام حذف',

        ]
    else:
        excel_options = [
            'ردیف',
            'وضعیت',
            'کد سفارش',
            'درخواست',
            'نوع فروش',
            'کشتار',
            'نام فارم',
            'نام و نام خانوادگی مرغدار',
            'موبایل',
            'شهر',
            'تاریخ کشتار',
            'تعداد کشتار',
            'وزن کشتار',
            'زمان تخصیص',
            'نوع تخصیص',
            'خریدار',
            'تعداد تخصیص داده شده',
            'مانده قابل تخصیص',
            ' تلفن خریدار',
            ' آدرس خریدار',
            'قیمت مرغدار',
            'قیمت کشتارگاه',
            'وضعیت تایید خریدار',
            'تخصیص ماشین',

        ]
    header_list = [
        'تعداد تخصیصات',
        'مجموع کل کشتار(قطعه)',
        'وزن کل کشتار',
        'مجموع تخصیص داده شده(قطعه)',
        'تعداد تایید شده',
        'تعداد تخصیصی ماشین',

    ]

    to_date_1 = shamsi_date(date1)

    to_date_2 = shamsi_date(date2)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    create_header(worksheet, header_list, 3, 2, height=21, width=16.01)
    if request.GET.get('type') == 'deleted':
        excel_description(worksheet, 'A1', f' مدیریت تخصیصات حذف شده', color='red', row2='B1')
    else:
        excel_description(worksheet, 'A1', f' مدیریت تخصیصات', color='red', row2='B1')
    excel_description(worksheet, 'A3', f'از تاریخ {to_date_1} تا {to_date_2}', color='red', row2='B3')

    if filtered_province_kill_reqs.exists():
        province = filtered_province_kill_reqs.first().province_request.poultry_request.poultry.address.province.name
        excel_description(worksheet, 'A2', f'استان {province}', color='red', row2='B2')

    create_header_freez(worksheet, excel_options, 1, 5, 6, height=19, width=21.01)

    l = 4
    m = 1
    all_state = 0
    all_car = 0
    all_return_quantity = 0
    for filtered_province_kill_req in filtered_province_kill_reqs:

        if KillHouseRequest.objects.filter(province_kill_request=filtered_province_kill_req,
                                           trash=False).exists():
            car = 'دارد'
            all_car += 1
        else:
            car = '-'
        l += 1
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_province_kill_req.province_request.poultry_request.send_date.day,
            month=filtered_province_kill_req.province_request.poultry_request.send_date.month,
            year=filtered_province_kill_req.province_request.poultry_request.send_date.year
        )
        date_of_allocation = jdatetime.date.fromgregorian(
            day=filtered_province_kill_req.create_date.day,
            month=filtered_province_kill_req.create_date.month,
            year=filtered_province_kill_req.create_date.year
        )
        if filtered_province_kill_req.state == "accepted":
            state_1 = 'تایید شده'
            all_state += 1
        elif filtered_province_kill_req.state == "pending":
            state_1 = 'در انتظار تایید'
        else:
            state_1 = 'رد شده'

        automatic = 'خودکار' if filtered_province_kill_req.automatic else 'دستی'
        if filtered_province_kill_req.province_request.poultry_request.union == True:
            type = 'اتحادیه'
        elif filtered_province_kill_req.province_request.poultry_request.direct_buying == True:
            type = 'خرید مستقیم'
        elif filtered_province_kill_req.market == True:
            type = 'پنل معاملات'

        else:
            type = 'اتحادیه'
        if filtered_province_kill_req.province_request.poultry_request.free_sale_in_province == True:
            free_type = 'آزاد'
        else:
            free_type = 'دولتی'

        freez_state = 'منجمد' if filtered_province_kill_req.province_request.poultry_request.freezing == True else 'عادی'

        if filtered_province_kill_req.return_to_province == True:
            state = 'تخصیص برگشت داده شده'
        elif filtered_province_kill_req.quantity == 0:
            state = 'تخصیص بسته شده'
        elif filtered_province_kill_req.trash == True:
            state = 'حذف شده'
        else:
            state = 'فعال'
        message = filtered_province_kill_req.message if filtered_province_kill_req.message is not None else '-'
        return_quantity = filtered_province_kill_req.quantity if filtered_province_kill_req.return_to_province == False else 0
        all_return_quantity += return_quantity
        if request.GET.get('type') == 'deleted':
            list1 = [
                m,
                state,
                str(filtered_province_kill_req.province_request.poultry_request.order_code),
                type,
                free_type,
                freez_state,
                filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
                filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
                filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
                filtered_province_kill_req.province_request.poultry_request.poultry.address.city.name,
                str(date_of_kill),
                filtered_province_kill_req.province_request.poultry_request.quantity,
                str(filtered_province_kill_req.province_request.poultry_request.Index_weight),
                str(date_of_allocation),
                automatic,
                filtered_province_kill_req.killhouse_user.name,
                filtered_province_kill_req.main_quantity,
                return_quantity,
                filtered_province_kill_req.killhouse_user.kill_house_operator.user.mobile,
                filtered_province_kill_req.kill_request.kill_house.system_address.city.name,
                filtered_province_kill_req.province_request.city_request_Poultry.poultry_request.amount,
                filtered_province_kill_req.kill_house_price,
                state_1,
                car,
                message

            ]
        else:
            list1 = [
                m,
                state,
                str(filtered_province_kill_req.province_request.poultry_request.order_code),
                type,
                free_type,
                freez_state,
                filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
                filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
                filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
                filtered_province_kill_req.province_request.poultry_request.poultry.address.city.name,
                str(date_of_kill),
                filtered_province_kill_req.province_request.poultry_request.quantity,
                str(filtered_province_kill_req.province_request.poultry_request.Index_weight),
                str(date_of_allocation),
                automatic,
                filtered_province_kill_req.killhouse_user.name,
                filtered_province_kill_req.main_quantity,
                return_quantity,
                filtered_province_kill_req.killhouse_user.kill_house_operator.user.mobile,
                filtered_province_kill_req.kill_request.kill_house.system_address.city.name,
                filtered_province_kill_req.province_request.city_request_Poultry.poultry_request.amount,
                filtered_province_kill_req.kill_house_price,
                state_1,
                car

            ]
        create_value(worksheet, list1, l + 1, 1)

        m += 1
    total_requests_quantity = \
        filtered_province_kill_reqs.aggregate(total=Sum('province_request__poultry_request__quantity'))['total'] or 0
    total_main_quantity = \
        filtered_province_kill_reqs.aggregate(total=Sum('main_quantity'))['total'] or 0
    total_requests_weight = filtered_province_kill_reqs.aggregate(
        total=Sum(
            F('province_request__poultry_request__quantity') * F('province_request__poultry_request__Index_weight')))[
                                'total'] or 0

    value_list = [
        m - 1,
        total_requests_quantity,
        int(total_requests_weight),
        total_main_quantity,
        all_state,
        all_car
    ]
    create_value(worksheet, value_list, 3, 3)

    total_requests_quantity = \
        filtered_province_kill_reqs.aggregate(total=Sum('province_request__poultry_request__quantity'))['total'] or 0
    if request.GET.get('type') == 'deleted':
        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            total_requests_quantity,
            '',
            '',
            '',
            '',
            total_main_quantity,
            all_return_quantity,
            '',
            '',
            '',
            '',
            '',

        ]
    else:
        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            total_requests_quantity,
            '',
            '',
            '',
            '',
            total_main_quantity,
            all_return_quantity,
            '',
            '',
            '',
            '',
            '',
            '',

        ]
    create_value(worksheet, list2, l + 3, 1, color='green')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت تخصیصات.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    prvince_kill_requests = ProvinceKillRequest.objects.filter(trash=True, delete_message__isnull=False).order_by(
        '-create_date')
    filtered_province_kill_reqs = [
        province_kill for province_kill in prvince_kill_requests
        if date1 <= province_kill.province_request.poultry_request.send_date.date() <= date2
    ]
    excel_options = [
        'کد سفارش',
        'نام فارم',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'آدرس',
        'تاریخ کشتار',
        'تعداد کشتار',
        'زمان تخصیص',
        'خریدار',
        'تعداد تخصیص داده شده',
        ' تلفن خریدار',
        ' آدرس خریدار',
        'تایید تخصیص',
        'تخصیص ماشین',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    for filtered_province_kill_req in filtered_province_kill_reqs:
        if KillHouseRequest.objects.filter(province_kill_request=filtered_province_kill_req, trash=False).exists():
            car = 'دارد'
        else:
            car = '-'
        l += 1
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_province_kill_req.province_request.poultry_request.send_date.day,
            month=filtered_province_kill_req.province_request.poultry_request.send_date.month,
            year=filtered_province_kill_req.province_request.poultry_request.send_date.year
        )
        date_of_allocation = jdatetime.date.fromgregorian(
            day=filtered_province_kill_req.create_date.day,
            month=filtered_province_kill_req.create_date.month,
            year=filtered_province_kill_req.create_date.year
        )
        if filtered_province_kill_req.state == "accepted":
            state = 'تایید شده'
        elif filtered_province_kill_req.state == "pending":
            state = 'در انتظار تایید'
        else:
            state = 'رد شده'
        list1 = [
            filtered_province_kill_req.province_request.poultry_request.order_code,
            filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
            filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
            filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
            filtered_province_kill_req.province_request.poultry_request.poultry.user.city.name,
            str(date_of_kill),
            filtered_province_kill_req.province_request.poultry_request.quantity,
            str(date_of_allocation),
            filtered_province_kill_req.killhouse_user.name,
            filtered_province_kill_req.main_quantity,
            filtered_province_kill_req.killhouse_user.kill_house_operator.user.mobile,
            filtered_province_kill_req.killhouse_user.system_address.city.name,
            state,
            car

        ]

        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت تخصیصات حذف شده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def poultry_kill_request_excel(request):
    access = AccessToken.objects.get(token=request.GET['token'])
    user = get_object_or_404(SystemUserProfile, user=access.user)
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    filterset_class = PoultryRequestFilterSet
    filterset_fields = [
        'order_code',
        'poultry__user__mobile',
        'poultry__user__fullname',
        'poultry__user__first_name',
        'poultry__user__last_name',
        'poultry__address__city__name',

    ]
    if request.GET['role'] == 'CityOperator':
        city_operator = CityOperator.objects.get(user=user)
        filtered_province_kill_reqs = PoultryRequest.objects.filter(poultry__city_operator=city_operator.unit_name,
                                                                    trash=False, send_date__date__gte=date1,
                                                                    send_date__date__lte=date2).select_related(
            'poultry', 'poultry__user').order_by(
            '-send_date')
    elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
        filtered_province_kill_reqs = PoultryRequest.objects.filter(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,
                                                                    poultry__address__city=user.city, ).select_related(
            'poultry', 'poultry__user').order_by(
            '-send_date')
    else:
        filtered_province_kill_reqs = PoultryRequest.objects.filter(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).select_related(
            'poultry', 'poultry__user').order_by(
            '-send_date')

    if 'search' in request.GET:
        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=filtered_province_kill_reqs
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=filtered_province_kill_reqs)
                        filtered_province_kill_reqs = ps.filter()

    excel_options = [
        'ردیف',
        'کد سفارش',
        'فروش',
        'کشتار',
        'درخواست',
        'تاریخ ثبت درخواست',
        'تاریخ کشتار',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'کشتارگاه های پیشنهادی',
        'آدرس',
        'سن مرغ',
        'میانگین وزنی هر قطعه(کیلوگرم)',
        'وزن تقریبی(کیلوگرم)',
        'حجم درخواست کشتار',
        'قیمت مرغدار(ریال)',
        'مانده در سالن',
        'تایید شده',
        'تخصیص داده شده',
        'مانده قابل تخصیص',
        'وضعیت',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')

    header_list = [
        'تعداد درخواست',
        'مجموع تعداد قطعه',
        'وزن تقریبی کل درخواست',
        'مجموع مانده در سالن',
        'میانگین سنی',
    ]
    create_header(worksheet, header_list, 4, 2, height=17)

    excel_description(worksheet, 'A2', 'درخواست کشتار مرغداران', size=11, row2='B2')

    from_date_1 = shamsi_date(date1)
    to_date_1 = shamsi_date(date2)

    excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})', color='red', row2='C3')
    m = 1

    create_header_freez(worksheet, excel_options, 1, 5, 6, height=23, width=21.01)
    l = 4
    all_quantity = 0
    all_wight = 0
    all_left_over = 0
    all_age = []
    if filtered_province_kill_reqs:
        for filtered_poultry_kill_request in filtered_province_kill_reqs:
            all_quantity += filtered_poultry_kill_request.quantity
            all_wight += int(filtered_poultry_kill_request.quantity * filtered_poultry_kill_request.Index_weight)
            l += 1
            date_of_create = jdatetime.date.fromgregorian(
                day=filtered_poultry_kill_request.create_date.day,
                month=filtered_poultry_kill_request.create_date.month,
                year=filtered_poultry_kill_request.create_date.year
            )
            date_of_kill = jdatetime.date.fromgregorian(
                day=filtered_poultry_kill_request.send_date.day,
                month=filtered_poultry_kill_request.send_date.month,
                year=filtered_poultry_kill_request.send_date.year
            )
            state = 'تایید شده'
            if filtered_poultry_kill_request.state == 'pending':
                state = 'در انتظار تایید'
            kill_house = '-'
            if filtered_poultry_kill_request.kill_house_list is not None:
                for name in filtered_poultry_kill_request.kill_house_list:
                    kill_house += name + '/'
            age = (
                          filtered_poultry_kill_request.send_date.date() - filtered_poultry_kill_request.hatching.date.date()).days + 1

            if age not in all_age:
                all_age.append(age)

            if filtered_poultry_kill_request.union == True:
                type = 'اتحادیه'
            elif filtered_poultry_kill_request.direct_buying == True:
                type = 'خرید مستقیم'
            elif filtered_poultry_kill_request.market == True:
                type = 'پنل معاملات'

            else:
                type = 'اتحادیه'

            freez_state = 'منجمد' if filtered_poultry_kill_request.freezing == True else 'عادی'

            sale_type = 'دولتی' if filtered_poultry_kill_request.free_sale_in_province == False else 'آزاد'
            all_left_over += filtered_poultry_kill_request.hatching.left_over

            list1 = [
                m,
                str(filtered_poultry_kill_request.order_code),
                sale_type,
                freez_state,
                type,
                str(date_of_create),
                str(date_of_kill),
                filtered_poultry_kill_request.poultry.unit_name,
                filtered_poultry_kill_request.poultry.user.mobile,
                kill_house,
                filtered_poultry_kill_request.poultry.address.city.name,
                str(age),
                str(filtered_poultry_kill_request.Index_weight),
                int(filtered_poultry_kill_request.quantity * filtered_poultry_kill_request.Index_weight),
                filtered_poultry_kill_request.first_quantity,
                filtered_poultry_kill_request.amount,
                filtered_poultry_kill_request.hatching.left_over,
                filtered_poultry_kill_request.quantity,
                filtered_poultry_kill_request.quantity - filtered_poultry_kill_request.remain_quantity,
                filtered_poultry_kill_request.remain_quantity,

                state
            ]
            m += 1
            create_value(worksheet, list1, l + 1, 1)
    all_age1 = sorted(all_age)
    value_header_list = [
        len(filtered_province_kill_reqs),
        all_quantity,
        all_wight,
        all_left_over,
        int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-',

    ]
    create_value(worksheet, value_header_list, 3, 4)
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="درخواست مرغدار.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    kill_requests = KillRequest.objects.filter(
        kill_house__kill_house_operator__user_id=SystemUserProfile.objects.get(user_id=request.user),
        trash=False).order_by('-recive_date')
    filtered_kill_reqs = [
        kill_request for kill_request in kill_requests
        if date1 <= kill_request.recive_date.date() <= date2
    ]

    excel_options = [
        'نام خریدار',
        'تاریخ ایجاد درخواست',
        'تعداد درخواست(قطعه)',
        'مانده(قطعه)',
        'تعداد تخصیص داده شده(قطعه)',
        'زمان دریافت',
        'تاریخ درخواستی کشتار',
        'وضعیت تایید استان',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    if filtered_kill_reqs:
        for kill_request in filtered_kill_reqs:
            l += 1
            create_date = jdatetime.date.fromgregorian(
                day=kill_request.create_date.day,
                month=kill_request.create_date.month,
                year=kill_request.create_date.year
            )
            recive_date = jdatetime.date.fromgregorian(
                day=kill_request.recive_date.day,
                month=kill_request.recive_date.month,
                year=kill_request.recive_date.year
            )

            if kill_request.province_state == 'accepted':
                province_state = 'تایید شده'
            elif kill_request.province_state == 'pending':
                province_state = 'در انتظار تایید'
            else:
                province_state = 'رد شده'

            allocation = kill_request.kill_capacity - kill_request.remain_quantity
            list1 = [
                kill_request.kill_house.name,
                str(create_date),
                kill_request.kill_capacity,
                kill_request.remain_quantity,
                allocation,
                kill_request.recive_time,
                str(recive_date),
                province_state,
            ]
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)
    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="kill_request {date1} to {date2}.xlsx"'
    response.write(output.getvalue())
    return response


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

    prvince_kill_requests = ProvinceKillRequest.objects.filter(
        killhouse_user__kill_house_operator__user_id=SystemUserProfile.objects.get(user_id=request.user),
        trash=False).order_by('-create_date')
    filtered_province_kill_reqs = [
        province_kill for province_kill in prvince_kill_requests
        if date1 <= province_kill.province_request.poultry_request.send_date.date() <= date2
    ]
    excel_options = [
        'کد سفارش',
        'تاریخ درخواست',
        'نام فارم',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'آدرس',
        'سن مرغ',
        'تعداد کشتار',
        'نژاد',
        'میانگین وزن',
        'زمان تخصیص',
        'تعداد تخصیص داده شده',
        'تایید تخصیص',
        'تخصیص ماشین',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    for filtered_province_kill_req in filtered_province_kill_reqs:
        if KillHouseRequest.objects.filter(province_kill_request=filtered_province_kill_req, trash=False).exists():
            car = 'دارد'
        else:
            car = '-'
        l += 1
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_province_kill_req.province_request.poultry_request.send_date.day,
            month=filtered_province_kill_req.province_request.poultry_request.send_date.month,
            year=filtered_province_kill_req.province_request.poultry_request.send_date.year
        )
        date_of_allocation = jdatetime.date.fromgregorian(
            day=filtered_province_kill_req.create_date.day,
            month=filtered_province_kill_req.create_date.month,
            year=filtered_province_kill_req.create_date.year
        )
        age = (
                      filtered_province_kill_req.create_date - filtered_province_kill_req.province_request.poultry_request.hatching.date).days + 1
        if filtered_province_kill_req.state == "accepted":
            state = 'تایید شده'
        elif filtered_province_kill_req.state == "pending":
            state = 'در انتظار تایید'
        else:
            state = 'رد شده'
        list1 = [
            filtered_province_kill_req.province_request.poultry_request.order_code,
            str(date_of_kill),
            filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
            filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
            filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
            filtered_province_kill_req.province_request.poultry_request.poultry.user.city.name,
            age,
            filtered_province_kill_req.province_request.poultry_request.quantity,
            filtered_province_kill_req.province_request.poultry_request.chicken_breed,
            filtered_province_kill_req.province_request.poultry_request.Index_weight,
            str(date_of_allocation),
            filtered_province_kill_req.main_quantity,
            state,
            car,

        ]

        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="Awaiting confirmation {date1} to {date2} .xlsx"'
    response.write(output.getvalue())

    return response


def new_load_of_kill_house_vet(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    kill_house_requests = KillHouseRequest.objects.filter(
        killhouse_user__kill_house_operator__user=SystemUserProfile.objects.get(user=request.user),
        trash=False).order_by('-create_date')

    filtered_kill_house_requests = [
        kill_house for kill_house in kill_house_requests
        if date1 <= kill_house.kill_request.recive_date.date() <= date2
    ]
    excel_options = [
        'کد بار',
        'کد رهگیری سامانه قرنطینه',
        'خریدار',
        'تاریخ درخواست',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'سن مرغ',
        'تعداد',
        'راننده',
        'ماشین',
        'پلاک',
        'نژاد',
        'میانگین وزن',
        'کد حمل و نقل'
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    for filtered_kill_house_request in filtered_kill_house_requests:
        l += 1
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_kill_house_request.kill_request.recive_date
                .day,
            month=filtered_kill_house_request.kill_request.recive_date
                .month,
            year=filtered_kill_house_request.kill_request.recive_date
                .year
        )
        traffic_code = filtered_kill_house_request.traffic_code if filtered_kill_house_request.traffic_code else '-'
        clearance_code = filtered_kill_house_request.clearance_code if filtered_kill_house_request.clearance_code else '-'
        age = (
                      filtered_kill_house_request.kill_request.recive_date - filtered_kill_house_request.province_request.poultry_request.hatching.date).days + 1
        list1 = [
            str(filtered_kill_house_request.bar_code),
            clearance_code,
            filtered_kill_house_request.killhouse_user.name,
            str(date_of_kill),
            filtered_kill_house_request.province_request.poultry_request.poultry.unit_name,
            filtered_kill_house_request.province_request.poultry_request.poultry.user.mobile,
            filtered_kill_house_request.province_request.poultry_request.poultry.address.city.name,
            age,
            filtered_kill_house_request.province_kill_request.main_quantity,
            filtered_kill_house_request.add_car.driver.driver_name,
            filtered_kill_house_request.add_car.driver.type_car,
            filtered_kill_house_request.add_car.driver.pelak,
            filtered_kill_house_request.province_request.poultry_request.chicken_breed,
            filtered_kill_house_request.province_request.poultry_request.Index_weight,
            traffic_code,

        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="kill_house_vet {date1} to {date2} .xlsx"'
    response.write(output.getvalue())
    return response


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

    kill_house_requests = KillHouseRequest.objects.filter(
        killhouse_user__kill_house_operator__user=SystemUserProfile.objects.get(user=request.user),
        trash=False).order_by('-create_date')

    filtered_kill_house_requests = [
        kill_house for kill_house in kill_house_requests
        if date1 <= kill_house.kill_request.recive_date.date() <= date2
    ]
    excel_options = [
        'کد سفارش',
        'کد بار',
        'تاریخ کشتار',
        'تاریخ ثبت خودرو',
        'مرغدار',
        'راننده',
        'ماشین',
        'پلاک',
        'تعداد',
        'کد حمل و نقل'
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    for filtered_kill_house_request in filtered_kill_house_requests:
        l += 1
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_kill_house_request.kill_request.recive_date
                .day,
            month=filtered_kill_house_request.kill_request.recive_date
                .month,
            year=filtered_kill_house_request.kill_request.recive_date
                .year
        )
        date_of_allocation_car = jdatetime.date.fromgregorian(
            day=filtered_kill_house_request.create_date
                .day,
            month=filtered_kill_house_request.create_date
                .month,
            year=filtered_kill_house_request.create_date
                .year
        )
        list1 = [
            filtered_kill_house_request.province_request.poultry_request.order_code,
            str(filtered_kill_house_request.bar_code),
            str(date_of_kill),
            str(date_of_allocation_car),
            filtered_kill_house_request.province_request.poultry_request.poultry.unit_name,
            filtered_kill_house_request.add_car.driver.driver_name,
            filtered_kill_house_request.add_car.driver.type_car,
            filtered_kill_house_request.add_car.driver.pelak,
            filtered_kill_house_request.quantity,
            filtered_kill_house_request.traffic_code,

        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="car allocation {date1} to {date2} .xlsx"'
    response.write(output.getvalue())
    return response


@permission_classes([TokenHasReadWriteScope])
@csrf_exempt
def Test(request):
    user = SystemUserProfile.objects.get(user=request.user, trash=False)
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date() if 'start' in request.GET else now
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date() + timedelta(
        days=1) if 'end' in request.GET else now
    killhouse_names = KillHouse.objects.filter(trash=False, system_address__province=user.province).values_list('name',
                                                                                                                flat=True).distinct()

    names_list = []
    for killhouse_name in killhouse_names:
        names_list.append(killhouse_name)

    excel_options = [
        'کد بار',
        'مرغدار',
        'تلفن مرغدار',
        'کدسفارش مرغدار',
        ' شهر مرغدار',
        ' تاریخ کشتار',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'خریدار',
        ' تلفن خریدار',
        ' ماهیت خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'کد رهگیری سامانه قرنطینه',
        'تعداد تخصیصی',
        'تعداد تخلیه شده',
        'وزن بار',
        'تاریخ تخلیه (کشتارگاه)',
        'مبلغ فاکتور',
        'تاریخ پرداخت فاکتور',

    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    for name in names_list:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')

        for col_num, option in enumerate(excel_options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=1, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            worksheet.column_dimensions[col_letter].width = 20.01
            worksheet.row_dimensions[1].height = 18
            worksheet.freeze_panes = worksheet['A2']
            max_col = worksheet.max_column
            range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str

        l = 0
        for kill in KillHouseRequest.objects.filter(trash=False, killhouse_user__name=name,
                                                    kill_request__recive_date__range=(date1, date2)):
            if kill:
                l += 1
                vet_farm = VetFarm.objects.filter(poultry=kill.province_request.poultry_request.poultry,
                                                  trash=False).last()
                vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
                vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'
                kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.killhouse_user).last()
                vet_checks = VetCheckRequest.objects.filter(kill_house_request=kill).last()
                kill_house_vet_name = kil_house_vet.vet.user.fullname if kil_house_vet else '-'
                kill_house_vet_mobile = kil_house_vet.vet.user.mobile if kil_house_vet else '-'
                factor = ProvinceFactorToKillHouse.objects.filter(
                    province_check_info__kill_house_assignment__kill_house_request=kill).last()
                factor_amount = factor.total_price if factor else '-'
                factor_payment = KillHouseFactorToProvince.objects.filter(
                    province_factor__province_check_info__kill_house_assignment__kill_house_request=kill).last()
                date_factor = jdatetime.date.fromgregorian(
                    day=factor_payment.create_date.day,
                    month=factor_payment.create_date.month,
                    year=factor_payment.create_date.year
                ) if factor_payment else '-'
                code = kill.clearance_code if kill.clearance_code else '-'
                quantity = kill.quantity if kill.quantity else '-'
                date_of_poultry_request = jdatetime.date.fromgregorian(
                    day=kill.province_request.poultry_request.send_date.day,
                    month=kill.province_request.poultry_request.send_date.month,
                    year=kill.province_request.poultry_request.send_date.year
                )
                killers = 'کشتارکن'
                if kill.killhouse_user.killer == False:
                    killers = 'کشتارگاه'
                assignment = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request=kill, trash=False).last()
                net_weighte = assignment.net_weight if assignment else '-'
                real_quantity = assignment.real_quantity if assignment else '-'
                date_of_inner_bar = jdatetime.date.fromgregorian(
                    day=vet_checks.create_date.day,
                    month=vet_checks.create_date.month,
                    year=vet_checks.create_date.year
                ) if vet_checks else '-'
                if kill.kill_request.slaughter_house != None:
                    kill_place = kill.kill_request.slaughter_house.name
                else:
                    kill_place = kill.killhouse_user.name

                list1 = [
                    str(kill.bar_code),
                    kill.province_request.poultry_request.poultry.unit_name,
                    str(kill.province_request.poultry_request.poultry.user.mobile),
                    kill.province_request.poultry_request.order_code,
                    kill.province_request.poultry_request.poultry.user.city.name,
                    str(date_of_poultry_request),
                    kill.province_request.poultry_request.chicken_breed,
                    vet_farm_name,
                    vet_farm_mobile,
                    kill.kill_request.kill_house.name,
                    kill.killhouse_user.phone,
                    killers,
                    kill.killhouse_user.system_address.city.name,
                    kill_place,
                    kill_house_vet_name,
                    kill_house_vet_mobile,
                    kill.add_car.driver.driver_name,
                    kill.add_car.driver.driver_mobile,
                    kill.add_car.driver.type_car,
                    kill.add_car.driver.health_code,
                    code,
                    quantity,
                    real_quantity,
                    net_weighte,
                    str(date_of_inner_bar),
                    factor_amount,
                    str(date_factor)
                ]
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="Reporting.xlsx"'
    response.write(output.getvalue())
    return response


@permission_classes([AllowAny])
def Test1(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    today = datetime.datetime.now().date()
    poultry_reqs = PoultryRequest.objects.filter(trash=False).order_by('-send_date')
    total = 0
    filtered_poultry_reqs = [
        poultry_req for poultry_req in poultry_reqs
        if date1 <= poultry_req.send_date.date() <= date2
    ]

    excel_options = [
        'کد سفارش',
        'نام واحد',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'آدرس',
        'تاریخ جوجه ریزی',
        'تعداد کل جوجه ریزی',
        'سن مرغ',
        'تعداد درخواست کشتار',
        'تعداد باقی مانده',
        'نژاد',
        'تاریخ درخواست کشتار',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'زمان تخصیص',
        'ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس خریدار',
        'محل کشتار',
        'دامپزشک کشتارگاه',
        'تلفن دامپزشک کشتارگاه',
        'راننده',
        'تلفن راننده',
        'ماشین حمل',
        'کد بهداشتی حمل و نقل',
        'کد رهگیری سامانه قرنطینه',
        'تعداد تحویلی',
        'وزن بار',
        'تاریخ تخلیه کشتارگاه',
        'مبلغ فاکتور',
        'تاریخ پرداخت فاکتور',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0

    for filtered_poultry_req in filtered_poultry_reqs:
        vet_farm = VetFarm.objects.filter(poultry=filtered_poultry_req.poultry, trash=False).last()
        vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
        vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'

        age = (today - filtered_poultry_req.hatching.date.date()).days + 1
        gregorian_date = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.hatching.date.day,
            month=filtered_poultry_req.hatching.date.month,
            year=filtered_poultry_req.hatching.date.year
        )
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.create_date.day,
            month=filtered_poultry_req.create_date.month,
            year=filtered_poultry_req.create_date.year
        )
        incubation_date = gregorian_date

        province_kill_reqs = ProvinceKillRequest.objects.filter(province_request__poultry_request=filtered_poultry_req,
                                                                trash=False)
        for province_kill_req in province_kill_reqs:
            kill_house_vet = KillHouseVet.objects.filter(kill_house=province_kill_req.kill_request.kill_house,
                                                         trash=False).last()
            kill_house_vet_name = kill_house_vet.vet.user.fullname if kill_house_vet else '-'
            kill_house_vet_mobile = kill_house_vet.vet.user.mobile if kill_house_vet else '-'
            date_of_inner_bar = '-'
            kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_req, trash=False)
            for kill_house_request in kill_house_requests:
                vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_request)
                killers = 'کشتارکن'
                if kill_house_request.killhouse_user.killer == False:
                    killers = 'کشتارگاه'
                assignment = KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_request).last()
                assignment_quantity = assignment.real_quantity if assignment else '-'
                assignment_weight = assignment.net_weight if assignment else '-'

                factor = ProvinceFactorToKillHouse.objects.filter(
                    province_check_info__kill_house_assignment__kill_house_request=kill_house_request).last()
                factor_amount = factor.total_price if factor else '-'
                date_factor = '-'
                factor_payment = KillHouseFactorToProvince.objects.filter(
                    province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request).last()
                if factor_payment:
                    date_factor = jdatetime.date.fromgregorian(
                        day=factor_payment.create_date.day,
                        month=factor_payment.create_date.month,
                        year=factor_payment.create_date.year
                    )

                time = jdatetime.date.fromgregorian(
                    day=kill_house_request.create_date.day,
                    month=kill_house_request.create_date.month,
                    year=kill_house_request.create_date.year
                )
                for vet_checks in vet_check:
                    date_of_inner_bar = jdatetime.date.fromgregorian(
                        day=vet_checks.create_date.day,
                        month=vet_checks.create_date.month,
                        year=vet_checks.create_date.year
                    )
                total += filtered_poultry_req.hatching.quantity
                code = kill_house_request.clearance_code if kill_house_request.clearance_code else '-'
                list1 = [
                    filtered_poultry_req.order_code,
                    filtered_poultry_req.poultry.unit_name,
                    filtered_poultry_req.poultry.user.fullname,
                    filtered_poultry_req.poultry.user.mobile,
                    filtered_poultry_req.poultry.user.city.name,
                    str(incubation_date),
                    filtered_poultry_req.hatching.quantity,
                    str(age),
                    filtered_poultry_req.quantity,
                    filtered_poultry_req.hatching.left_over,
                    filtered_poultry_req.hatching.chicken_breed,
                    str(date_of_kill),
                    vet_farm_name,
                    vet_farm_mobile,
                    str(time),
                    killers,
                    province_kill_req.kill_request.kill_house.name,
                    province_kill_req.kill_request.kill_house.phone,
                    province_kill_req.kill_request.kill_house.system_address.city.name,
                    province_kill_req.kill_request.kill_house.system_address.city.name,
                    kill_house_vet_name,
                    kill_house_vet_mobile,
                    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.traffic_code,
                    code,
                    assignment_quantity,
                    assignment_weight,
                    str(date_of_inner_bar),
                    factor_amount,
                    str(date_factor)
                ]
                l += 1

                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')

        list1 = [
            filtered_poultry_req.order_code,
            filtered_poultry_req.poultry.unit_name,
            filtered_poultry_req.poultry.user.fullname,
            filtered_poultry_req.poultry.user.mobile,
            filtered_poultry_req.poultry.user.city.name,
            str(incubation_date),
            filtered_poultry_req.hatching.quantity,
            str(age),
            filtered_poultry_req.quantity,
            filtered_poultry_req.hatching.left_over,
            filtered_poultry_req.hatching.chicken_breed,
            str(date_of_kill),
            vet_farm_name,
            vet_farm_mobile,
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-'
        ]
        l += 1

        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')

    # اضافه کردن ستون جدید
    max_col = worksheet.max_column
    worksheet.insert_cols(max_col + 1)

    # افزودن هدر جدید
    header_cell = worksheet.cell(row=1, column=max_col + 1, value="تعداد کل کشتار")
    header_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    header_cell.fill = PatternFill(start_color="9fff40", end_color="9fff40", fill_type="solid")
    header_cell.font = Font(size=10, bold=True, color='D9FFFFFF')

    # افزودن مقدار جدید
    header_cell_below = worksheet.cell(row=2, column=max_col + 1, value=total)
    header_cell_below.alignment = Alignment(horizontal='center', vertical='center')
    worksheet.column_dimensions[get_column_letter(max_col + 1)].width = 20.01

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="file {date1} to {date2}.xlsx"'
    response.write(output.getvalue())

    return response


from io import BytesIO
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment, Font
from openpyxl.utils import get_column_letter


@permission_classes([AllowAny])
@csrf_exempt
def excel_for_all_user(request):
    users = SystemUserProfile.objects.filter(trash=False)
    poultry_list = Poultry.objects.filter(trash=False)
    kill_house_list = KillHouse.objects.filter(trash=False)
    vet_list = VetFarm.objects.filter(trash=False)

    excel_options = {
        'مرغدار': ['نام کامل',
                   'شماره تلفن',
                   'تاریخ تولد',
                   'کد کاربری',
                   'شهر',
                   'کلمه عبور',
                   'نام فارم',
                   'آدرس',
                   'شهر',
                   'کد پستی',
                   'موبایل',
                   'شناسه یکتا',
                   'کد اقتصادی',
                   'کد اپیدمیولوژیک',
                   'تعداد سالن', ],
        'دامپزشک کشتارگاه': ['کد بار', 'نام دامپزشک', 'شماره تلفن'],
        'دامپزشک فارم': ['کد بار', 'نام دامپزشک', 'شماره تلفن'],
        'کشتارگاه': ['کد بار', 'نام کشتارگاه', 'شماره تلفن'],
    }
    output = BytesIO()
    workbook = Workbook()
    for name, options in excel_options.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=1, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')

            worksheet.column_dimensions[col_letter].width = 20.01
            worksheet.row_dimensions[1].height = 18
            worksheet.freeze_panes = worksheet['A2']
            max_col = worksheet.max_column
            range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        l = 0
        if sheet_name == 'مرغدار':
            for p in poultry_list:
                list1 = [
                    p.user.fullname,
                    p.user.mobile,
                    p.user.birthday,
                    p.user.base_order,
                    p.user.city.name,
                    p.user.password,
                    p.unit_name,
                    p.address.address,
                    p.address.city.name,
                    p.address.postal_code,
                    p.address.phone,
                    p.breeding_unique_id,
                    p.economic_code,
                    p.epidemiological_code,
                    p.number_of_halls,
                ]
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
        elif sheet_name == 'کشتارگاه':
            for kill in kill_house_list:
                list1 = [
                    kill.name
                ]
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
        elif sheet_name == 'دامپزشک فارم':
            for vet in vet_list:
                list1 = [
                    vet.state
                ]
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="Reporting.xlsx"'
    response.write(output.getvalue())
    return response


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

    kill_house = KillHouse.objects.filter(key=request.GET['kill_house_key'], trash=False).select_related(
        'system_address__province').first()

    if kill_house.killer == True:
        percentage = KillHousePercentage.objects.get(kill_house=kill_house, trash=False)
        kill_house_vet = KillHouseVet.objects.filter(kill_house=percentage.kill_house_for_killer,
                                                     trash=False).select_related(
            'vet__user').last()
    else:
        kill_house_vet = KillHouseVet.objects.filter(kill_house=kill_house, trash=False).select_related(
            'vet__user').last()

    kill_house_ware_house = KillHouseWareHouse.objects.filter(kill_house=kill_house,
                                                              date__year=date.year,
                                                              date__month=date.month,
                                                              date__day=date.day,
                                                              trash=False).last()
    kill_house_free_bar_info_list = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house,
                                                                               date__year=date.year,
                                                                               date__month=date.month,
                                                                               date__day=date.day,
                                                                               trash=False)
    date = date - timedelta(days=1)

    queryset = PoultryRequest.objects.filter(
        poultry__address__province=kill_house.system_address.province,
        final_state__in=('pending', 'archive'),
        trash=False, out=False,
        send_date__date=date,

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

    excel_options = {

        'اطلاعات بارهای سیستمی': ['کد بار',
                                  'مرغدار',
                                  'کد سفارش',
                                  'شهر مرغدار',
                                  'تاریخ کشتار',
                                  'نژاد',
                                  'دامپزشک فارم',
                                  ' موبایل دامپزشک فارم',
                                  ' دامپزشک کشتارگاه',
                                  'موبایل دامپزشک کشتارگاه',
                                  'راننده',
                                  'نوع خودرو',
                                  'کدبهداشتی حمل و نقل',
                                  'کدرهگیری قرنطینه',
                                  'تعداد تخصیصی',
                                  'وضعیت',
                                  'تعداد تخلیه شده',
                                  'وزن بار(کیلوگرم)'],
        'اطلاعات بارهای آزاد': ['مرغدار',
                                'استان/شهر',
                                'تاریخ خرید',
                                'نام دامپزشک',
                                'موبایل دامپزشک',
                                'ماشین',
                                'راننده',
                                ' موبایل راننده',
                                'کدقرنطینه',
                                'تعداد قطعه',
                                'وزن زنده (کیلوگرم)',
                                'تعداد لاشه',
                                'وزن لاشه(کیلوگرم)',
                                ],
    }
    red_font = Font(color="C00000", bold=True)

    output = BytesIO()
    workbook = Workbook()
    for name, options in excel_options.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="0070C0", fill_type="solid")
        blue_fill1 = PatternFill(start_color="00B0F0", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=5, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')

            worksheet.column_dimensions[col_letter].width = 20.01
            worksheet.row_dimensions[5].height = 32
            worksheet.freeze_panes = worksheet['A6']
            max_col = worksheet.max_column
            range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        l = 4
        if sheet_name == 'اطلاعات بارهای سیستمی':
            worksheet['B1'] = f'موجودی انبار'
            worksheet['A4'] = f'اطلاعات بارهای سیستمی'

            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A4'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:C1'
            merge_range2 = 'A4:C4'
            # merge_range2 = 'B2:C2'

            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            # worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['A4'].font = red_font
            header_list = ['تعداد بار سیستمی',
                           'تعداد قطعه تخصیصی',
                           'وزن بار زنده',
                           'تعداد لاشه',
                           'وزن لاشه ها (افت 25٪) کیلوگرم',
                           'میانگین وزن لاشه ها (کیلوگرم)'
                , 'تعداد بار (خرید آزاد)', 'تعداد لاشه (خرید آزاد)'
                , 'وزن لاشه (خرید آزاد) (کیلوگرم)'
                , 'مجموع بارها'
                , 'مجموع لاشه ها '
                , 'مجموع وزن لاشه ها (کیلوگرم)',
                           'تعداد لاشه(ویرایش شده)',
                           'وزن لاشه ها (افت 25٪) کیلوگرم(ویرایش شده)',
                           ]
            for item in range(len(header_list)):
                cell = worksheet.cell(row=2, column=item + 2, value=header_list[item])
                value = header_list[item]
                cell.fill = blue_fill1
                cell.font = Font(size=9, bold=True, color='FFFFFF')
                worksheet.row_dimensions[2].height = 25
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            if len(queryset) > 0:
                for poultry_req in queryset:
                    vet_farm = VetFarm.objects.filter(poultry=poultry_req.poultry).select_related('vet__user').last()
                    if vet_farm:
                        vet_name = vet_farm.vet.user.fullname
                        vet_mobile = vet_farm.vet.user.mobile
                    else:
                        vet_name = None
                        vet_mobile = None

                    kill_house_requests = KillHouseRequest.objects.filter(
                        province_kill_request__province_request__poultry_request=poultry_req,
                        killhouse_user=kill_house, trash=False).select_related(
                        'kill_request__kill_house__kill_house_operator__user', 'add_car__driver',
                        'kill_request__kill_house')
                    if kill_house_requests:
                        for kill_house_request in kill_house_requests:

                            assignment = KillHouseAssignmentInformation.objects.filter(
                                kill_house_request=kill_house_request).last()
                            if assignment:
                                assignment_state = 'تایید نهایی'
                                assignment_real_quantity = kill_house_request.accepted_real_quantity
                                assignment_net_weight = kill_house_request.accepted_real_weight

                            else:
                                if kill_house_request.vet_state == 'pending':
                                    assignment_state = 'در انتظار تایید تخلیه'
                                else:
                                    assignment_state = 'در انتظار وروداطلاعات بار'
                                assignment_real_quantity = kill_house_request.accepted_real_quantity
                                assignment_net_weight = kill_house_request.accepted_real_weight
                            clearance_code = kill_house_request.clearance_code if kill_house_request.clearance_code else '-'

                            list1 = [
                                str(kill_house_request.bar_code),
                                poultry_req.poultry.unit_name,
                                str(poultry_req.order_code),
                                poultry_req.poultry.address.city.name,
                                str(date),
                                poultry_req.chicken_breed,
                                vet_name,
                                vet_mobile,
                                kill_house_vet.vet.user.fullname,
                                kill_house_vet.vet.user.mobile,
                                kill_house_request.add_car.driver.driver_name,
                                kill_house_request.add_car.driver.type_car,
                                kill_house_request.traffic_code,
                                clearance_code,
                                kill_house_request.quantity,
                                assignment_state,
                                assignment_real_quantity,
                                assignment_net_weight
                            ]
                            l += 1
                            for item in range(len(list1)):
                                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                                cell.alignment = Alignment(horizontal='center')
                                value = list1[item]
                                if isinstance(value, (int, float)):
                                    if value != 0:
                                        cell.number_format = '#,##0'  # Apply general number format
                                else:
                                    cell.value = value  # Keep as text for other values
                                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                if kill_house_ware_house:
                    list1 = [
                        kill_house_ware_house.bar_quantity,
                        kill_house_ware_house.allocated_quantity,
                        kill_house_ware_house.bar_live_weight,
                        kill_house_ware_house.number_of_carcasses,
                        kill_house_ware_house.weight_of_carcasses,
                        kill_house_ware_house.ave_weight_of_carcasses,
                        kill_house_ware_house.free_bar_quantity,
                        kill_house_ware_house.number_of_free_carcasses,
                        kill_house_ware_house.free_weight_of_carcasses,
                        kill_house_ware_house.total_bar_quantity,
                        kill_house_ware_house.total_number_of_carcasses,
                        kill_house_ware_house.total_weight_of_carcasses,
                        kill_house_ware_house.updated_number_of_carcasses,
                        kill_house_ware_house.updated_weight_of_carcasses,

                    ]
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=3, column=item + 2, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')
                        value = list1[item]
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,##0'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values
                        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                        cell.font = Font(size=10, bold=True)
                else:
                    list1 = [
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,

                    ]
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=3, column=item + 2, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')
                        value = list1[item]
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,##0'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values
                        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                        cell.font = Font(size=10, bold=True)
        elif sheet_name == 'اطلاعات بارهای آزاد':
            header_list = [
                'تعداد بار (خرید آزاد)',
                'تعداد لاشه (خرید آزاد)',
                'وزن لاشه (خرید آزاد) (کیلوگرم)',
                'مجموع بارها',
                'مجموع لاشه ها ',
                'مجموع وزن لاشه ها (کیلوگرم)',
                'تعداد لاشه(ویرایش شده)',
                'وزن لاشه ها (افت 25٪) کیلوگرم(ویرایش شده)',
            ]
            for item in range(len(header_list)):
                cell = worksheet.cell(row=2, column=item + 2, value=header_list[item])
                value = header_list[item]
                cell.fill = blue_fill1
                cell.font = Font(size=9, bold=True, color='FFFFFF')
                worksheet.row_dimensions[2].height = 25
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            for kill_house_free_bar in kill_house_free_bar_info_list:
                date = jdatetime.date.fromgregorian(year=kill_house_free_bar.date.year,
                                                    month=kill_house_free_bar.date.month,
                                                    day=kill_house_free_bar.date.day)
                list1 = [
                    kill_house_free_bar.poultry_name,
                    kill_house_free_bar.province + ' ' + kill_house_free_bar.city,
                    str(date),
                    kill_house_free_bar.vet_farm_name,
                    kill_house_free_bar.vet_farm_mobile,
                    kill_house_free_bar.car,
                    kill_house_free_bar.driver_name,
                    kill_house_free_bar.driver_mobile,
                    kill_house_free_bar.clearance_code,
                    kill_house_free_bar.quantity,
                    kill_house_free_bar.live_weight,
                    kill_house_free_bar.number_of_carcasses,
                    kill_house_free_bar.weight_of_carcasses,
                ]
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
            if kill_house_ware_house:
                list1 = [
                    kill_house_ware_house.free_bar_quantity,
                    kill_house_ware_house.number_of_free_carcasses,
                    kill_house_ware_house.free_weight_of_carcasses,
                    kill_house_ware_house.total_bar_quantity,
                    kill_house_ware_house.total_number_of_carcasses,
                    kill_house_ware_house.total_weight_of_carcasses,
                    kill_house_ware_house.updated_number_of_carcasses,
                    kill_house_ware_house.updated_weight_of_carcasses,

                ]
                for item in range(len(list1)):
                    cell = worksheet.cell(row=3, column=item + 2, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
                    value = list1[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'
                    else:
                        cell.value = value
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.font = Font(size=10, bold=True)
    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="{kill_house.name} در تاریخ {str(date)}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def steward_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Guilds")
    l = 0
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 0:
            continue
        mobile = str(row[5])
        if len(mobile) == 10:
            mobile = '0' + str.zfill(mobile, 10)
        postal_code = row[4]
        national_code = row[9]
        guild_id = row[8]
        first_name = row[2]
        last_name = row[3]
        license_num = 0
        password = '00100'
        hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
        province = Province.objects.filter(name='مرکزی')
        province = province.first()
        city = City.objects.filter(name='اراک')
        city = city.first()
        system_profile = SystemUserProfile.objects.filter(mobile=mobile, trash=False).first()
        if system_profile:
            pass
        # if not system_profile:
        #     pass
        #     # data = {
        #     #     "username": mobile,
        #     #     "first_name": first_name,
        #     #     "last_name": last_name,
        #     #     "password": hashed_password,
        #     #     "national_code": '0',
        #     #     "role": "Guilds",
        #     #     "api_key": PROJECT_API_KEY
        #     # }
        #     # req = requests.post(
        #     #     url=ARTA_REGISTER,
        #     #     data=data,
        #     #     verify=False
        #     # )
        #     #
        #     # if req.status_code == 200:
        #     #     user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
        #     #     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=mobile,
        #     #         first_name=first_name,
        #     #         last_name=last_name,
        #     #         fullname=first_name + ' ' + last_name,
        #     #         user=user,
        #     #         base_order=base_id,
        #     #         password=password,
        #     #         birthday=str(datetime.datetime.now().date()),
        #     #         city=city,
        #     #         province=province
        #     #     )
        #     #     system_profile.save()
        #     #     system_profile.role.add(group)
        #     #     l+=1
        # else:
        #     guilds = Guilds.objects.filter(user=system_profile).exists()
        #     if not guilds:
        #         address = SystemAddress(city=city, province=province, address=row[6])
        #         address.save()
        #         wallet = Wallet()
        #         wallet.save()
        #         guilds = Guilds(
        #             user=system_profile,
        #             address=address,
        #             wallet=wallet,
        #             guilds_name=first_name + ' ' + last_name,
        #             type_activity='خرده فروش',
        #             area_activity='گوشت و مرغ',
        #             guilds_id=guild_id,
        #             license_number=license_num,
        #
        #         )
        #         guilds.save()
        #         l += 1

    # Guilds.objects.bulk_create(guilds_list)
    return Response(
        l
    )


def Broadcast_management(request):
    abc_list = ['A', 'B', 'C', 'D', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S']

    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(request.GET['date'],
                                       '%Y-%m-%d').date() if 'date' in request.GET else now
    date2 = datetime.datetime.strptime(request.GET['date2'],
                                       '%Y-%m-%d').date() if 'date2' in request.GET else now
    kill_house = KillHouse.objects.get(key=request.GET['kill_house_key'], trash=False)

    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,
        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')

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    # to_date = jdatetime.date.fromgregorian(
    #     year=date2.year,
    #     month=date2.month,
    #     day=date2.day
    # ).strftime('%Y-%m-%d')
    # reversed_date = reversed(to_date.split("-"))
    # separate = "-"
    # to_date_1 = separate.join(reversed_date)

    names_list = [kill_house.name]
    output = BytesIO()
    workbook = Workbook()
    for name in names_list:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

        worksheet['F2'] = f'اطلاعات کلی توزیع و پخش مرغ گرم در تاریخ {from_date_1}'

        worksheet['F2'].alignment = Alignment(horizontal='center', vertical='center')
        merge_range122 = 'F2:N2'
        worksheet.merge_cells(merge_range122)

        worksheet['F2'].font = Font(size=10)

        for abc in abc_list[2:11]:
            worksheet[f'{abc}3'].border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='medium'),
                right=openpyxl.styles.Side(style='medium'),
                top=openpyxl.styles.Side(style='medium'),
                bottom=openpyxl.styles.Side(style='medium')
            )
        withe_font = Font(size=12, bold=True, color='D9FFFFFF')
        blue = PatternFill(start_color="4472C4", fill_type="solid")
        worksheet['C3'] = f'ورودی از سردخانه'
        worksheet['E3'] = f'پیش سرد'
        worksheet['G3'] = f'خرید خارج از استان'
        worksheet['I3'] = f'بارهای روزانه'
        worksheet['K3'] = f'جمع کل انبار'
        worksheet['M3'] = f'توزیع شده'
        worksheet['O3'] = f'توزیع / تحویل شده'
        worksheet['Q3'] = f'مانده انبار'

        worksheet['C3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['I3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['K3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['M3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['O3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['Q3'].alignment = Alignment(horizontal='center', vertical='center')

        merge_range1 = 'C3:D4'
        merge_range2 = 'E3:F4'
        merge_range3 = 'G3:H4'
        merge_range4 = 'I3:J4'
        merge_range5 = 'K3:L4'
        merge_range6 = 'M3:N4'
        merge_range7 = 'O3:P4'
        merge_range8 = 'Q3:R4'

        worksheet.merge_cells(merge_range1)
        worksheet.merge_cells(merge_range2)
        worksheet.merge_cells(merge_range3)
        worksheet.merge_cells(merge_range4)
        worksheet.merge_cells(merge_range5)
        worksheet.merge_cells(merge_range6)
        worksheet.merge_cells(merge_range7)
        worksheet.merge_cells(merge_range8)

        worksheet['C3'].font = withe_font
        worksheet['E3'].font = withe_font
        worksheet['G3'].font = withe_font
        worksheet['I3'].font = withe_font
        worksheet['K3'].font = withe_font
        worksheet['M3'].font = withe_font
        worksheet['O3'].font = withe_font
        worksheet['Q3'].font = withe_font

        worksheet['C3'].fill = blue
        worksheet['E3'].fill = blue
        worksheet['G3'].fill = blue
        worksheet['I3'].fill = blue
        worksheet['K3'].fill = blue
        worksheet['M3'].fill = blue
        worksheet['O3'].fill = blue
        worksheet['Q3'].fill = blue

        list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

        for item in range(len(list1)):
            cell = worksheet.cell(row=5, column=item + 3, value=list1[item])
            worksheet.row_dimensions[5].height = 19

            cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.font = Font(size=10, bold=True)
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='medium'),
                right=openpyxl.styles.Side(style='medium'),
                top=openpyxl.styles.Side(style='medium'),
                bottom=openpyxl.styles.Side(style='medium')
            )

        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']

        list2 = [

            0,
            0,
            total_pre_cold_quantity if total_pre_cold_quantity != None else 0,
            total_pre_cold_weight if total_pre_cold_weight != None else 0,
            total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
            total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
            total_number_of_carcasses if total_number_of_carcasses != None else 0,
            total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
            final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
            final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
            total_allocated_quantity if total_allocated_quantity != None else 0,
            total_allocated_weight if total_allocated_weight != None else 0,
            total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
            total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
            total_remain_quantity if total_remain_quantity != None else 0,
            total_remain_weight if total_remain_weight != None else 0,

        ]
        for item in range(len(list2)):
            cell = worksheet.cell(row=6, column=item + 3, value=list2[item])
            value = list2[item]
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,##0'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.font = Font(size=10, bold=True)
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='medium'),
                right=openpyxl.styles.Side(style='medium'),
                top=openpyxl.styles.Side(style='medium'),
                bottom=openpyxl.styles.Side(style='medium')
            )

        excel_options = [
            'ردیف',
            'شناسه صنف',
            'تاریخ ثبت',
            'ماهیت',
            'نوع تخصیص',
            'نام واحد صنفی',
            'نام شخص',
            'کد ملی',
            'موبایل',
            'نوع فعالیت',
            'حوزه فعالیت',
            'شماره مجوز',
            'شهرستان',
            'تعداد لاشه تخصیص',
            'وزن لاشه تخصیصی',
            'تعداد لاشه تحویلی',
            'وزن لاشه تحویلی',
            'وضعیت',
            'کد احراز',
        ]

        for col_num, option in enumerate(excel_options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=9, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            if len(option) > worksheet.column_dimensions[col_letter].width:
                worksheet.column_dimensions[col_letter].width = len(option) + 3

                # تنظیم ارتفاع سطر
                # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
            worksheet.row_dimensions[9].height = 26
            worksheet.freeze_panes = worksheet['A10']
            max_col = worksheet.max_column
            range_str = f'A9:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        m = 1
        l = 10

        stewards = (
            StewardAllocation.objects.filter(trash=False, ware_house__kill_house=kill_house, date__date=date1,
                                             )
                .select_related('guilds',
                                'guilds__user',
                                'guilds__address__city',
                                'kill_house',
                                'kill_house__kill_house_operator').order_by(
                'id'))

        if stewards.exists():
            for steward_allocation in stewards:
                create_date = jdatetime.date.fromgregorian(
                    day=steward_allocation.create_date.day,
                    month=steward_allocation.create_date.month,
                    year=steward_allocation.create_date.year
                )
                steward = 'مباشر' if steward_allocation.seller_type == 'steward' else 'صنف'
                sell_type = 'اختصاصی' if steward_allocation.sell_type == 'exclusive' else 'آزاد'
                type = 'دستی' if steward_allocation.type == 'manual' else 'اتوماتیک'
                try:
                    guilds_name = steward_allocation.steward.guilds.guilds_name
                    guilds_id = steward_allocation.steward.guilds.guilds_id
                    fullname = steward_allocation.steward.guilds.user.fullname
                    national_id = steward_allocation.steward.guilds.user.national_id
                    mobile = steward_allocation.steward.guilds.user.mobile
                    type_activity = steward_allocation.steward.guilds.type_activity
                    area_activity = steward_allocation.steward.guilds.area_activity
                    license_number = steward_allocation.steward.guilds.license_number
                    city_name = steward_allocation.steward.guilds.address.city.name
                except:
                    guilds_name = steward_allocation.guilds.guilds_name
                    guilds_id = steward_allocation.guilds.guilds_id
                    fullname = steward_allocation.guilds.user.fullname
                    national_id = steward_allocation.guilds.user.national_id
                    mobile = steward_allocation.guilds.user.mobile
                    type_activity = steward_allocation.guilds.type_activity
                    area_activity = steward_allocation.guilds.area_activity
                    license_number = steward_allocation.guilds.license_number
                    city_name = steward_allocation.guilds.address.city.name
                if steward_allocation.receiver_state == 'pending':
                    reciver_type = 'در انتظار تحویل'
                    register = '-'
                elif steward_allocation.receiver_state == 'accepted':
                    reciver_type = 'تحویل گرفته شد'
                    register = steward_allocation.logged_registration_code if steward_allocation.logged_registration_code else 'وارد نشده'

                else:
                    reciver_type = 'رد شده'
                    register = '-'

                list2 = [
                    m,
                    guilds_id,
                    str(create_date),
                    steward,
                    f'{sell_type}({type})',
                    guilds_name,
                    fullname,
                    national_id,
                    mobile,
                    type_activity,
                    area_activity,
                    license_number,
                    city_name,
                    steward_allocation.number_of_carcasses,
                    steward_allocation.weight_of_carcasses,
                    steward_allocation.receiver_real_number_of_carcasses,
                    steward_allocation.receiver_real_weight_of_carcasses,
                    reciver_type,
                    register,

                ]
                for item in range(len(list2)):
                    cell = worksheet.cell(row=l, column=item + 1, value=list2[item])
                    value = list2[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

                m += 1
                l += 1

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="{kill_house.name} در تاریخ {str(now)}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def guilds_excel(request):
    filterset_class = GuildsFilterSet
    filterset_fields = [
        'user__mobile',
        'user__first_name',
        'user__last_name',
        'user__city__name',
        'user__province__name',
        'address__city__name',
        'guilds_name',
        'type_activity',
        'area_activity',

    ]
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)

    active_state = request.GET.get('active_state')
    active_filter = {}
    if active_state == 'active':
        active_filter['active'] = True
    elif active_state == 'deactive':
        active_filter['active'] = False
    if request.GET['role'] in ['CityCommerce', 'CityJahad', 'CityPoultry']:
        guilds = Guilds.objects.filter(trash=False, province_accept_state='accepted',
                                       address__city=user.city, **active_filter).order_by('id')
    elif request.GET['role'] == 'Guilds':

        guilds = []

        if request.GET['steward'] == 'true':
            steward = Steward.objects.get(guilds__user=user, trash=False)
            guilds_list = []
            first_guilds = Guilds.objects.filter(trash=False, centers_allocation__isnull=False,
                                                 province_accept_state__in=('pending', 'accepted'),
                                                 **active_filter).order_by('id')
            for guild in first_guilds:

                if len(guild.centers_allocation) == 0 or guild.centers_allocation == None:
                    continue
                if guild.centers_allocation[0]['value'] == str(
                        steward.key):
                    guilds_list.append(guild.key)
            if len(guilds_list) > 0:
                guilds = Guilds.objects.filter(key__in=guilds_list, **active_filter).order_by('id')

    elif request.GET['role'] == 'KillHouse':
        guilds_list = []
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        if 'steward' in request.GET and request.GET['steward'] == 'true':
            guilds = Guilds.objects.filter(trash=False, steward=True,
                                           kill_house_centers_allocation__isnull=False,
                                           province_accept_state__in=('pending', 'accepted'),
                                           **active_filter).order_by('id')
        else:
            guilds = Guilds.objects.filter(trash=False, kill_house_centers_allocation__isnull=False,
                                           province_accept_state__in=('pending', 'accepted'),
                                           **active_filter).order_by('id')
        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.key):
                guilds_list.append(guild.key)
        if len(guilds_list) > 0:
            guilds = Guilds.objects.filter(key__in=guilds_list, **active_filter).order_by('id')
        else:
            guilds = []

    else:
        if 'check' in request.GET:
            if request.GET['state'] == 'pending':
                guilds = Guilds.objects.filter(
                    Q(kill_house_register=True) | Q(steward_register=True) | Q(pos_company_register=True),
                    province_accept_state='pending',
                    trash=False, **active_filter).order_by('id')
            else:
                guilds = Guilds.objects.filter(kill_house_register=True,
                                               trash=False, **active_filter).order_by('id')
        else:
            if 'steward' in request.GET and request.GET['steward'] == 'true':
                guilds = Guilds.objects.filter(province_accept_state='accepted', steward=True,
                                               trash=False, **active_filter).order_by('id')
            else:
                guilds = Guilds.objects.filter(province_accept_state='accepted', trash=False,
                                               **active_filter).order_by('id')
    if 'value' in request.GET and request.GET['value'] == 'undefined':
        pass
    else:
        if 'search' in request.GET and request.GET['search'] == 'filter':
            if request.GET.get('value', '') != "":
                guilds_list = []
                for item in filterset_fields:
                    query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                    filtered_queryset = filterset_class(data=query, queryset=guilds).filter()
                    if filtered_queryset.exists():
                        if len(guilds_list) == 0:
                            guilds_list = list(filtered_queryset.values_list('id', flat=True))
                        else:
                            guilds_list = list(set(guilds_list) & set(filtered_queryset.values_list('id', flat=True)))
                if len(guilds_list) > 0:
                    guilds = guilds.filter(id__in=guilds_list)
    excel_options = [
        'ردیف',
        'کد ملی',
        'نام',
        'نام خانوادگی',
        'شماره شناسنامه',
        'در قید حیات',
        'تاریخ تولد',
        'نام پدر',
        'جنسیت',
        'شهر',
        'شماره همراه',
        'نام واحد',
        'رسته واحد صنفی',
        'استان',
        'شهرستان',
        'تاریخ انقضا مجوز',
        'شماره مجوز',
        'نام اتحادیه',
        'وضعیت',
        'کد پستی',
        'شماره تلفن',
        'آیا اتباع است؟',
        'نام شرکت',
        'شناسه ملی شرکت',
        'وضعیت مجوز',
        'آدرس',
        'مباشر',
        'احراز شماره موبایل',
    ]
    header_list = [
        'تعداد اصناف',
        'تعداد مباشرین',
        'تعداد دارای کارتخوان',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'] = f'گزارش اصناف'
    red_font = Font(color="C00000", bold=True)

    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:C1'
    worksheet['A1'].font = red_font

    worksheet.merge_cells(merge_range1)
    for col_num, option in enumerate(header_list, 4):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        col_letter = get_column_letter(col_num)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 21
        worksheet.column_dimensions[col_letter].width = 16.01

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=5, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[5].height = 18
        worksheet.freeze_panes = worksheet['A6']
        max_col = worksheet.max_column
        range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 4
    m = 1
    has_pos = 0
    is_steward = 0
    for guild in guilds:
        user = guild.user if getattr(guild, 'user', None) else None
        address = guild.address if getattr(guild, 'address', None) else None
        
        national_id = getattr(user, 'national_id', None) if user else None
        national_id = national_id if national_id else '-'
        first_name = getattr(user, 'first_name', '-') if user else '-'
        last_name = getattr(user, 'last_name', '-') if user else '-'
        id_number = getattr(user, 'national_code', None) if user else None
        id_number = id_number if id_number else '-'
        is_alive_value = getattr(user, 'is_alive', None) if user else None
        is_alive = 'بلی' if is_alive_value == True else ('خیر' if is_alive_value == False else '-')
        birthday = '-'
        if user:
            birthday_value = getattr(user, 'birthday', None)
            if birthday_value:
                try:
                    if type(birthday_value) == str:
                        birthday_value = convert_str_to_date(birthday_value)
                        birthday = str(shamsi_date(birthday_value, in_value=True))
                    else:
                        birthday = str(shamsi_date(birthday_value, in_value=True))

                except:
                    birthday = '-'
        father_name = getattr(user, 'father_name', None) if user else None
        father_name = father_name if father_name else '-'
        gender_value = getattr(user, 'gender', None) if user else None
        if gender_value == True or str(gender_value).lower() in ['true', '1', 'male', 'مرد', 'm']:
            gender = 'مرد'
        elif gender_value == False or str(gender_value).lower() in ['false', '0', 'female', 'زن', 'f']:
            gender = 'زن'
        else:
            gender = '-'
        user_city = getattr(user.city, 'name', '-') if user and getattr(user, 'city', None) else '-'
        mobile = getattr(user, 'mobile', '-') if user else '-'
        user_province = getattr(user.province, 'name', '-') if user and getattr(user, 'province', None) else '-'
        
        guild_name = getattr(guild, 'guilds_name', None)
        guild_name = guild_name if guild_name else '-'
        area_activity = getattr(guild, 'area_activity', None)
        area_activity = area_activity if area_activity else '-'
        
        address_city = getattr(address.city, 'name', '-') if address and getattr(address, 'city', None) else '-'
        postal_code = getattr(address, 'postal_code', '-') if address else '-'
        phone = getattr(address, 'phone', None) if address else None
        phone = phone if phone else '-'
        address_value = getattr(address, 'address', '-') if address else '-'
        
        license_expire_date = '-'
        if getattr(guild, 'license_expire_date', None):
            try:
                license_expire_date = str(shamsi_date(guild.license_expire_date.date(), in_value=True))
            except:
                license_expire_date = '-'
        license_number = getattr(guild, 'license_number', None)
        license_number = license_number if license_number else '-'
        union_name = getattr(guild, 'union_name', None)
        union_name = union_name if union_name else '-'
        license_status = getattr(guild, 'license_status', None)
        license_status = license_status if license_status else '-'
        
        active_status = 'فعال' if getattr(guild, 'active', False) else 'غیر فعال'
        
        is_foreign = getattr(guild, 'is_foreign_national', None)
        if is_foreign == True:
            is_foreign_national = 'بلی'
        elif is_foreign == False:
            is_foreign_national = 'خیر'
        else:
            is_foreign_national = '-'
        
        company_name = getattr(guild, 'company_name', None)
        company_name = company_name if company_name else '-'
        company_identifier = getattr(guild, 'company_identifier', None)
        company_identifier = company_identifier if company_identifier else '-'
        
        if guild.steward == True:
            steward = 'می باشد'
            is_steward += 1
        else:
            steward = 'نمی باشد'
        
        register_code = getattr(guild, 'register_code', None)
        mobile_verified = 'احراز دارد' if register_code and str(register_code).strip() else '-'
        
        if guild.has_pos == True:
            has_pos += 1
        
        list1 = [
            m,
            national_id,
            first_name,
            last_name,
            id_number,
            is_alive,
            birthday,
            father_name,
            gender,
            user_city,
            mobile,
            guild_name,
            area_activity,
            user_province,
            address_city,
            license_expire_date,
            license_number,
            union_name,
            active_status,
            postal_code,
            phone,
            is_foreign_national,
            company_name,
            company_identifier,
            license_status,
            address_value,
            steward,
            mobile_verified,
        ]
        l += 1
        m += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
    value_list = [
        m - 1,
        is_steward,
        has_pos

    ]
    for item in range(len(value_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=value_list[item])
        cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت اصناف.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def commerce_report_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    today = datetime.datetime.now().date()
    poultry_reqs = PoultryRequest.objects.filter(trash=False).select_related('poultry').order_by('-send_date')
    filtered_poultry_reqs = [
        poultry_req for poultry_req in poultry_reqs
        if date1 <= poultry_req.send_date.date() <= date2
    ]

    excel_options = [
        'کد سفارش',
        'نام واحد',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'آدرس',
        'تاریخ جوجه ریزی',
        'تعداد کل جوجه ریزی',
        'سن مرغ',
        'تعداد درخواست کشتار',
        'تعداد باقی مانده',
        'نژاد',
        'تاریخ درخواست کشتار',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'زمان تخصیص',
        'ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس خریدار',
        'محل کشتار',
        'دامپزشک کشتارگاه',
        'تلفن دامپزشک کشتارگاه',
        'راننده',
        'تلفن راننده',
        'ماشین حمل',
        'کد بهداشتی حمل و نقل',
        'کد رهگیری سامانه قرنطینه',
        'تعداد تحویلی',
        'وزن بار',
        'تاریخ تخلیه کشتارگاه',
        'مبلغ فاکتور',
        'تاریخ پرداخت فاکتور',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0

    for filtered_poultry_req in filtered_poultry_reqs:
        vet_farm = VetFarm.objects.filter(poultry=filtered_poultry_req.poultry, trash=False).last()
        vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
        vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'

        age = (today - filtered_poultry_req.hatching.date.date()).days + 1
        gregorian_date = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.hatching.date.day,
            month=filtered_poultry_req.hatching.date.month,
            year=filtered_poultry_req.hatching.date.year
        )
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.create_date.day,
            month=filtered_poultry_req.create_date.month,
            year=filtered_poultry_req.create_date.year
        )
        incubation_date = gregorian_date

        province_kill_reqs = ProvinceKillRequest.objects.filter(province_request__poultry_request=filtered_poultry_req,
                                                                trash=False)
        for province_kill_req in province_kill_reqs:
            kill_house_vet = KillHouseVet.objects.filter(kill_house=province_kill_req.kill_request.kill_house,
                                                         trash=False).only('vet__user__fullname',
                                                                           'vet__user__mobile').last()
            kill_house_vet_name = kill_house_vet.vet.user.fullname if kill_house_vet else '-'
            kill_house_vet_mobile = kill_house_vet.vet.user.mobile if kill_house_vet else '-'
            date_of_inner_bar = '-'
            kill_house_requests = KillHouseRequest.objects.filter(province_kill_request=province_kill_req, trash=False)
            for kill_house_request in kill_house_requests:
                vet_check = VetCheckRequest.objects.filter(kill_house_request=kill_house_request).only('create_date')
                killers = 'کشتارکن'
                if kill_house_request.killhouse_user.killer == False:
                    killers = 'کشتارگاه'
                assignment = KillHouseAssignmentInformation.objects.filter(kill_house_request=kill_house_request).only(
                    'real_quantity', 'net_weight').last()
                assignment_quantity = assignment.real_quantity if assignment else '-'
                assignment_weight = assignment.net_weight if assignment else '-'

                factor = ProvinceFactorToKillHouse.objects.filter(
                    province_check_info__kill_house_assignment__kill_house_request=kill_house_request).only(
                    'total_price').last()
                factor_amount = factor.total_price if factor else '-'
                date_factor = '-'
                factor_payment = KillHouseFactorToProvince.objects.filter(
                    province_factor__province_check_info__kill_house_assignment__kill_house_request=kill_house_request).only(
                    'create_date').last()
                if factor_payment:
                    date_factor = jdatetime.date.fromgregorian(
                        day=factor_payment.create_date.day,
                        month=factor_payment.create_date.month,
                        year=factor_payment.create_date.year
                    )

                time = jdatetime.date.fromgregorian(
                    day=kill_house_request.create_date.day,
                    month=kill_house_request.create_date.month,
                    year=kill_house_request.create_date.year
                )
                for vet_checks in vet_check:
                    date_of_inner_bar = jdatetime.date.fromgregorian(
                        day=vet_checks.create_date.day,
                        month=vet_checks.create_date.month,
                        year=vet_checks.create_date.year
                    )

                code = kill_house_request.clearance_code if kill_house_request.clearance_code else '-'
                list1 = [
                    filtered_poultry_req.order_code,
                    filtered_poultry_req.poultry.unit_name,
                    filtered_poultry_req.poultry.user.fullname,
                    filtered_poultry_req.poultry.user.mobile,
                    filtered_poultry_req.poultry.user.city.name,
                    str(incubation_date),
                    filtered_poultry_req.hatching.quantity,
                    str(age),
                    filtered_poultry_req.quantity,
                    filtered_poultry_req.hatching.left_over,
                    filtered_poultry_req.hatching.chicken_breed,
                    str(date_of_kill),
                    vet_farm_name,
                    vet_farm_mobile,
                    str(time),
                    killers,
                    province_kill_req.kill_request.kill_house.name,
                    province_kill_req.kill_request.kill_house.phone,
                    province_kill_req.kill_request.kill_house.system_address.city.name,
                    province_kill_req.kill_request.kill_house.system_address.city.name,
                    kill_house_vet_name,
                    kill_house_vet_mobile,
                    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.traffic_code,
                    code,
                    assignment_quantity,
                    assignment_weight,
                    str(date_of_inner_bar),
                    factor_amount,
                    str(date_factor)
                ]
                l += 1

                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')

        list1 = [
            filtered_poultry_req.order_code,
            filtered_poultry_req.poultry.unit_name,
            filtered_poultry_req.poultry.user.fullname,
            filtered_poultry_req.poultry.user.mobile,
            filtered_poultry_req.poultry.user.city.name,
            str(incubation_date),
            filtered_poultry_req.hatching.quantity,
            str(age),
            filtered_poultry_req.quantity,
            filtered_poultry_req.hatching.left_over,
            filtered_poultry_req.hatching.chicken_breed,
            str(date_of_kill),
            vet_farm_name,
            vet_farm_mobile,
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-',
            '-'
        ]
        l += 1

        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="وضعیت پرونده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    kill_requests = KillHouseRequest.objects.filter(trash=False).order_by('-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry')
    filtered_kill_reqs = [
        kill_request for kill_request in kill_requests
        if date1 <= kill_request.kill_request.recive_date.date() <= date2
    ]
    excel_options = [
        'کد بار',
        'مرغدار',
        'تلفن مرغدار',
        'کدسفارش مرغدار',
        ' شهر مرغدار',
        ' تاریخ کشتار',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'خریدار',
        ' تلفن خریدار',
        ' ماهیت خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'کد رهگیری سامانه قرنطینه',
        'تعداد تخصیصی',
        'تعداد تخلیه شده',
        'وزن بار',
        'تاریخ تخلیه (کشتارگاه)',
        'مبلغ فاکتور',
        'تاریخ پرداخت فاکتور',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            l += 1
            vet_farm = VetFarm.objects.filter(poultry=kill.province_request.poultry_request.poultry, trash=False).last()
            vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
            vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.killhouse_user).last()
            vet_checks = VetCheckRequest.objects.filter(kill_house_request=kill).only('create_date').last()
            kill_house_vet_name = kil_house_vet.vet.user.fullname if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.vet.user.mobile if kil_house_vet else '-'
            factor = ProvinceFactorToKillHouse.objects.filter(
                province_check_info__kill_house_assignment__kill_house_request=kill).only('total_price').last()
            factor_amount = factor.total_price if factor else '-'
            factor_payment = KillHouseFactorToProvince.objects.filter(
                province_factor__province_check_info__kill_house_assignment__kill_house_request=kill).only(
                'create_date').last()
            date_factor = jdatetime.date.fromgregorian(
                day=factor_payment.create_date.day,
                month=factor_payment.create_date.month,
                year=factor_payment.create_date.year
            ) if factor_payment else '-'
            code = kill.clearance_code if kill.clearance_code else '-'
            quantity = kill.quantity if kill.quantity else '-'
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=kill.province_request.poultry_request.send_date.day,
                month=kill.province_request.poultry_request.send_date.month,
                year=kill.province_request.poultry_request.send_date.year
            )
            killers = 'کشتارکن'
            if kill.killhouse_user.killer == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request=kill, trash=False).last()
            net_weighte = assignment.net_weight if assignment else '-'
            real_quantity = assignment.real_quantity if assignment else '-'
            date_of_inner_bar = jdatetime.date.fromgregorian(
                day=vet_checks.create_date.day,
                month=vet_checks.create_date.month,
                year=vet_checks.create_date.year
            ) if vet_checks else '-'
            if kill.kill_request.slaughter_house != None:
                kill_place = kill.kill_request.slaughter_house.name
            else:
                kill_place = kill.killhouse_user.name

            list1 = [
                str(kill.bar_code),
                kill.province_request.poultry_request.poultry.unit_name,
                str(kill.province_request.poultry_request.poultry.user.mobile),
                kill.province_request.poultry_request.order_code,
                kill.province_request.poultry_request.poultry.user.city.name,
                str(date_of_poultry_request),
                kill.province_request.poultry_request.chicken_breed,
                vet_farm_name,
                vet_farm_mobile,
                kill.kill_request.kill_house.name,
                kill.killhouse_user.phone,
                killers,
                kill.killhouse_user.system_address.city.name,
                kill_place,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.add_car.driver.driver_name,
                kill.add_car.driver.driver_mobile,
                kill.add_car.driver.type_car,
                kill.add_car.driver.health_code,
                code,
                quantity,
                real_quantity,
                net_weighte,
                str(date_of_inner_bar),
                factor_amount,
                str(date_factor)
            ]
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارها.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def number_of_kills_weight_excel(request):
    now = datetime.datetime.now().date()
    excel_options = [
        'ردیف',
        'کد بار',
        'مرغدار',
        'تلفن مرغدار',
        'کدسفارش مرغدار',
        ' شهر مرغدار',
        ' تاریخ کشتار',
        ' نژاد',
        'خریدار',
        ' ماهیت خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'تعداد تخصیصی',
        'وزن بار',

    ]
    to_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    worksheet['A1'] = f'گزارش تعداد کشتار'
    worksheet['A3'] = f'در تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[4].height = 19
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 3
    m = 1
    now = timezone.now().date()
    ten_days_ago = now - timedelta(days=int(request.GET['day']))
    for day in range(int(request.GET['day']) + 1):
        date = ten_days_ago + timedelta(days=day)

        kill_reqs = KillHouseRequest.objects.filter(
            kill_request__recive_date__date=date,
            trash=False).select_related(
            'killhouse_user', 'province_request__poultry_request__poultry', 'province_request__poultry_request',
            'kill_request').order_by(
            '-kill_request__recive_date')

        if 'role' in request.GET:
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user=user)
                kill_requests = kill_reqs.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                kill_requests = kill_reqs.filter(province_request__poultry_request__poultry__user__city=user.city)
            else:
                kill_requests = kill_reqs
        else:
            kill_requests = kill_reqs
        if kill_requests:
            for kill in kill_requests:
                l += 1
                total_weight = 0
                kill_house_request_information = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request=kill).first()
                if kill_house_request_information:
                    total_weight += kill_house_request_information.net_weight
                else:
                    total_weight += kill.province_request.poultry_request.Index_weight * kill.quantity
                quantity = kill.quantity if kill.quantity else '-'
                date_of_poultry_request = jdatetime.date.fromgregorian(
                    day=kill.province_request.poultry_request.send_date.day,
                    month=kill.province_request.poultry_request.send_date.month,
                    year=kill.province_request.poultry_request.send_date.year
                )
                killers = 'کشتارکن'
                if kill.killhouse_user.killer == False:
                    killers = 'کشتارگاه'

                if kill.kill_request.slaughter_house != None:
                    kill_place = kill.kill_request.slaughter_house.name
                else:
                    kill_place = kill.killhouse_user.name

                list1 = [
                    m,
                    str(kill.bar_code),
                    kill.province_request.poultry_request.poultry.unit_name,
                    str(kill.province_request.poultry_request.poultry.user.mobile),
                    kill.province_request.poultry_request.order_code,
                    kill.province_request.poultry_request.poultry.user.city.name,
                    str(date_of_poultry_request),
                    kill.province_request.poultry_request.chicken_breed,
                    kill.kill_request.kill_house.name,
                    killers,
                    kill.killhouse_user.system_address.city.name,
                    kill_place,
                    quantity,
                    total_weight,

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش تعداد کشتار {request.GET["day"]} روز گذشته (براساس بار).xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def number_of_kills_excel(request):
    now = datetime.datetime.now().date()
    excel_options = [
        'ردیف',
        'کد بار',
        'مرغدار',
        'تلفن مرغدار',
        'کدسفارش مرغدار',
        ' شهر مرغدار',
        ' تاریخ کشتار',
        ' نژاد',
        'خریدار',
        ' ماهیت خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'تعداد تخصیصی',
        'وزن بار',

    ]
    to_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    worksheet['A1'] = f'گزارش تعداد کشتار'
    worksheet['A3'] = f'در تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[4].height = 19
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 3
    m = 1
    now = timezone.now().date()
    ten_days_ago = now - timedelta(days=int(request.GET['day']))
    for day in range(int(request.GET['day']) + 1):
        date = ten_days_ago + timedelta(days=day)

        kill_reqs = KillHouseRequest.objects.filter(
            kill_request__recive_date__date=date,
            trash=False).select_related(
            'killhouse_user', 'province_request__poultry_request__poultry', 'province_request__poultry_request',
            'kill_request').order_by(
            '-kill_request__recive_date')

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

        if kill_requests:
            for kill in kill_requests:
                l += 1
                total_weight = 0
                kill_house_request_information = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request=kill).first()
                if kill_house_request_information:
                    total_weight += kill_house_request_information.net_weight
                else:
                    total_weight += kill.province_request.poultry_request.Index_weight * kill.quantity
                quantity = kill.quantity if kill.quantity else '-'
                date_of_poultry_request = jdatetime.date.fromgregorian(
                    day=kill.province_request.poultry_request.send_date.day,
                    month=kill.province_request.poultry_request.send_date.month,
                    year=kill.province_request.poultry_request.send_date.year
                )
                killers = 'کشتارکن'
                if kill.killhouse_user.killer == False:
                    killers = 'کشتارگاه'

                if kill.kill_request.slaughter_house != None:
                    kill_place = kill.kill_request.slaughter_house.name
                else:
                    kill_place = kill.killhouse_user.name

                list1 = [
                    m,
                    str(kill.bar_code),
                    kill.province_request.poultry_request.poultry.unit_name,
                    str(kill.province_request.poultry_request.poultry.user.mobile),
                    kill.province_request.poultry_request.order_code,
                    kill.province_request.poultry_request.poultry.user.city.name,
                    str(date_of_poultry_request),
                    kill.province_request.poultry_request.chicken_breed,
                    kill.kill_request.kill_house.name,
                    killers,
                    kill.killhouse_user.system_address.city.name,
                    kill_place,
                    quantity,
                    total_weight,

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش تعداد کشتار {request.GET["day"]} روز گذشته (براساس بار).xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def single_hatching_age_range_excel(request):
    filtered_poultry_hatchs = PoultryHatching.objects.filter(state__in=('pending', 'complete'), archive=False,
                                                             allow_hatching='pending',
                                                             trash=False).order_by('-create_date').select_related(
        'poultry')

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

    excel_options = [
        'ردیف',
        'نام فارم',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن',
        'تعداد جوجه ریزی',
        'تلفات دوره',
        'کشتار شده',
        'مانده در سالن',
    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    header_list = [
        'تعداد کل فارم ها',
        'مجموع جوجه ریزی',
        'مجموع کشتار شده',
        'مجموع مانده در سالن',
    ]
    for col_num, option in enumerate(header_list, 3):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="31869B", fill_type="solid")
        cell.font = Font(size=10, bold=True, color='FFFFFF')
        worksheet.row_dimensions[2].height = 30
        cell.border = openpyxl.styles.Border(
            left=openpyxl.styles.Side(style='thin'),
            right=openpyxl.styles.Side(style='thin'),
            top=openpyxl.styles.Side(style='thin'),
            bottom=openpyxl.styles.Side(style='thin')
        )
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=5, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A6']
        max_col = worksheet.max_column
        range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    l = 4
    m = 1
    for poultry_hatching in filtered_poultry_hatch:
        l += 1
        create_date = jdatetime.date.fromgregorian(
            day=poultry_hatching.create_date.day,
            month=poultry_hatching.create_date.month,
            year=poultry_hatching.create_date.year
        )
        date = jdatetime.date.fromgregorian(
            day=poultry_hatching.date.day,
            month=poultry_hatching.date.month,
            year=poultry_hatching.date.year
        )
        poultry_requests = PoultryRequest.objects.filter(hatching=poultry_hatching, trash=False).only('quantity')
        age = (datetime.datetime.now().date() - poultry_hatching.date.date()).days + 1
        quantity_sum = 0
        for poultry_request in poultry_requests:
            if poultry_request and hasattr(poultry_request, 'quantity'):
                quantity_sum += poultry_request.quantity
        list1 = [
            m,
            poultry_hatching.poultry.unit_name,
            poultry_hatching.hall,
            poultry_hatching.period,
            str(create_date),
            str(date),
            poultry_hatching.chicken_breed,
            age,
            poultry_hatching.quantity,
            poultry_hatching.losses,
            poultry_hatching.killed_quantity,
            poultry_hatching.left_over,

        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        m += 1
    total_poultry_hatchings_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    total_poultry_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get(
        'total_quantity') or 0
    total_poultry_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get(
        'total_quantity') or 0
    value_list = [
        m - 1,
        total_poultry_hatchings_quantity,
        total_poultry_killed_quantity,
        total_poultry_left_over,

    ]
    for item in range(len(value_list)):
        cell = worksheet.cell(row=3, column=item + 3, value=value_list[item])
        cell.alignment = Alignment(horizontal='center')
        value = value_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="موجودی جوجه ریزی (مانده در سالن) بر اساس سن.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def total_poultry_request_dashboard_excel(request):
    now = datetime.datetime.now().date()

    filtered_province_kill = PoultryRequest.objects.filter(send_date__date=now, trash=False).order_by('-send_date')

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

    excel_options = [
        'ردیف',
        'کد سفارش',
        'تاریخ ثبت درخواست',
        'تاریخ کشتار',
        'نام و نام خانوادگی مرغدار',
        'نام فارم',
        'موبایل',
        'کشتارگاه های پیشنهادی',
        'آدرس',
        'سن مرغ',
        'تعداد درخواست کشتار',
        'مانده در سالن',
        'تایید شده',
    ]
    to_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)
    if filtered_province_kill_reqs.exists():
        province = filtered_province_kill_reqs.first().poultry.address.province.name
        worksheet['A2'] = f'استان {province}'
        worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')

    worksheet['A1'] = f'درخواست های کشتار'
    worksheet['A3'] = f'در تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[4].height = 19
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 3
    m = 1
    if filtered_province_kill_reqs:
        for filtered_poultry_kill_request in filtered_province_kill_reqs:
            l += 1
            date_of_create = jdatetime.date.fromgregorian(
                day=filtered_poultry_kill_request.create_date.day,
                month=filtered_poultry_kill_request.create_date.month,
                year=filtered_poultry_kill_request.create_date.year
            )
            date_of_kill = jdatetime.date.fromgregorian(
                day=filtered_poultry_kill_request.send_date.day,
                month=filtered_poultry_kill_request.send_date.month,
                year=filtered_poultry_kill_request.send_date.year
            )
            state = 'تایید شده'
            if filtered_poultry_kill_request.state == 'pending':
                state = 'در انتظار تایید'
            kill_house = ''
            for name in filtered_poultry_kill_request.kill_house_list:
                kill_house += name + '-'
            age = (
                          filtered_poultry_kill_request.send_date.date() - filtered_poultry_kill_request.hatching.date.date()).days + 1
            list1 = [
                m,
                filtered_poultry_kill_request.order_code,
                str(date_of_create),
                str(date_of_kill),
                filtered_poultry_kill_request.poultry.user.fullname,
                filtered_poultry_kill_request.poultry.unit_name,
                filtered_poultry_kill_request.poultry.user.mobile,
                kill_house,
                filtered_poultry_kill_request.poultry.address.city.name,
                age,
                filtered_poultry_kill_request.quantity,
                filtered_poultry_kill_request.hatching.left_over,
                state
            ]
            m += 1

            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="درخواست کشتار .xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def total_poultry_hatching_dashboard_excel(request):
    excel_options = [
        'تعداد فارم',
        'جوجه ریزی',
        'تلفات (10٪)',
        'کشتار شده',
        'مانده در سالن',
    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    l = 1
    poultry_counts = Poultry.objects.filter(trash=False)
    poultry_hatchings = PoultryHatching.objects.filter(state='pending', allow_hatching='pending', archive=False,
                                                       trash=False)
    total_poultry_hatchings_quantity = poultry_hatchings.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    total_poultry_hatchings_left = poultry_hatchings.aggregate(total_quantity=Sum('left_over')).get(
        'total_quantity', 0)
    losses = poultry_hatchings.aggregate(total_quantity=Sum('losses')).get(
        'total_quantity', 0)
    total_kill_house_request_quantity = KillHouseRequest.objects.filter(
        trash=False
    ).aggregate(total_quantity=Sum('quantity'))['total_quantity'] or 0

    list1 = [
        poultry_counts.count(),
        total_poultry_hatchings_quantity,
        losses,
        total_kill_house_request_quantity,
        total_poultry_hatchings_left
    ]
    for item in range(len(list1)):
        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
        cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="فارم های فعال.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def doughnut_left_hatching_excel(request):
    now = datetime.datetime.now().date()
    # user = SystemUserProfile.objects.get(token=request.GET['token'])
    # total = 0
    # city_list = []
    # hatchings_list = []
    hatchings = PoultryHatching.objects.filter(state='pending', allow_hatching='pending', archive=False
                                               ).order_by('-date')

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

    excel_options = [
        'ردیف',
        'نام فارم',
        'شهر',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن',
        'تعداد جوجه ریزی',
        'تلفات دوره',
        'کشتار شده',
        'مانده در سالن',
    ]

    to_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)
    if hatchingss_list.exists():
        province = hatchingss_list.first().poultry.address.province.name
        worksheet['A2'] = f'استان {province}'
        worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'] = f'گزارش کل جوجه ریزی بر اساس شهرستان'
    worksheet['A3'] = f'در تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[4].height = 19
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 3
    m = 1
    for hatchingss in hatchingss_list:

        if (jdatetime.datetime.fromgregorian(year=hatchingss.date.year, month=hatchingss.date.month,
                                             day=hatchingss.date.day)).month == int(request.GET['month']):
            # hatchings_list.append(hatchingss)
            # total += hatchingss.quantity
            # if hatchingss.poultry.address.city not in city_list:
            #     city_list.append(hatchingss.poultry.address.city)

            create_date = jdatetime.date.fromgregorian(
                day=hatchingss.create_date.day,
                month=hatchingss.create_date.month,
                year=hatchingss.create_date.year
            )
            date = jdatetime.date.fromgregorian(
                day=hatchingss.date.day,
                month=hatchingss.date.month,
                year=hatchingss.date.year
            )
            age = (datetime.datetime.now().date() - hatchingss.date.date()).days + 1
            # for city in city_list:
            # for hatch in hatchings_list:
            list1 = [
                m,
                hatchingss.poultry.unit_name,
                hatchingss.poultry.address.city.name,
                hatchingss.hall,
                hatchingss.period,
                str(create_date),
                str(date),
                hatchingss.chicken_breed,
                age,
                hatchingss.quantity,
                hatchingss.losses,
                hatchingss.killed_quantity,
                hatchingss.left_over,
            ]
            l += 1
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش کل جوجه ریزی بر اساس شهرستان .xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def doughnut_hatching_excel(request):
    now = datetime.datetime.now().date()
    # total = 0
    # city_list = []
    # hatchings_list = []
    hatchings = PoultryHatching.objects.filter(state='pending', allow_hatching='pending', archive=False
                                               ).order_by('-date')

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

    province = hatchingss_list.first().poultry.address.province.name
    excel_options = [
        'ردیف',
        'نام فارم',
        'شهر',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن',
        'تعداد جوجه ریزی',
        'تلفات دوره',
        'کشتار شده',
        'مانده در سالن',
    ]

    to_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    worksheet['A1'] = f'گزارش کل جوجه ریزی بر اساس شهرستان'
    worksheet['A2'] = f'استان {province}'
    worksheet['A3'] = f'در تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[4].height = 19
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 3
    m = 1
    for hatchingss in hatchingss_list:

        if (jdatetime.datetime.fromgregorian(year=hatchingss.date.year, month=hatchingss.date.month,
                                             day=hatchingss.date.day)).month == int(request.GET['month']):
            # hatchings_list.append(hatchingss)
            # total += hatchingss.quantity
            # if hatchingss.poultry.address.city not in city_list:
            #     city_list.append(hatchingss.poultry.address.city)

            create_date = jdatetime.date.fromgregorian(
                day=hatchingss.create_date.day,
                month=hatchingss.create_date.month,
                year=hatchingss.create_date.year
            )
            date = jdatetime.date.fromgregorian(
                day=hatchingss.date.day,
                month=hatchingss.date.month,
                year=hatchingss.date.year
            )
            age = (datetime.datetime.now().date() - hatchingss.date.date()).days + 1
            # for city in city_list:
            # for hatch in hatchings_list:
            list1 = [
                m,
                hatchingss.poultry.unit_name,
                hatchingss.poultry.address.city.name,
                hatchingss.hall,
                hatchingss.period,
                str(create_date),
                str(date),
                hatchingss.chicken_breed,
                age,
                hatchingss.quantity,
                hatchingss.losses,
                hatchingss.killed_quantity,
                hatchingss.left_over,
            ]
            l += 1
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش کل جوجه ریزی بر اساس شهرستان های استان {province}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def forecast_hatching_left_over_excel(request):
    user = SystemUserProfile.objects.get(user=request.user)
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    age = int(request.GET['age'])
    days_interval = (date2 - date1).days
    hatchings = PoultryHatching.objects.filter(state='pending', poultry__address__province=user.province,
                                               allow_hatching='pending', archive=False,
                                               trash=False)
    excel_options = [
        'نام فارم',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'تعداد جوجه ریزی',
        'تلفات دوره',
        'کشتار شده',
        'مانده در سالن',
    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    if hatchings:
        l = 0
        for i in range(days_interval + 1):
            hatching_left_over = 0
            first_date = date1 + timedelta(days=i)
            for hatch in hatchings:
                if (first_date - hatch.date.date()).days + 1 == age:
                    l += 1
                    hatching_left_over += hatch.left_over
                    create_date = jdatetime.date.fromgregorian(
                        day=hatch.create_date.day,
                        month=hatch.create_date.month,
                        year=hatch.create_date.year
                    )
                    date = jdatetime.date.fromgregorian(
                        day=hatch.date.day,
                        month=hatch.date.month,
                        year=hatch.date.year
                    )
                    poultry_requests = PoultryRequest.objects.filter(hatching=hatch, trash=False).only('quantity')
                    quantity_sum = 0
                    for poultry_request in poultry_requests:
                        if poultry_request and hasattr(poultry_request, 'quantity'):
                            quantity_sum += poultry_request.quantity
                    list1 = [
                        hatch.poultry.unit_name,
                        hatch.hall,
                        hatch.period,
                        str(create_date),
                        str(date),
                        hatch.chicken_breed,
                        hatch.quantity,
                        hatch.losses,
                        quantity_sum,
                        hatching_left_over,

                    ]
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')
                # hatching_list.append({"date": first_date, "hatching_left_over": hatching_left_over})
                if days_interval == 0:
                    break

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="جوجه ریزی.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def manager_of_farm_excel(request):
    now = datetime.datetime.now().date()
    filtered_kill_reqs = KillHouseRequest.objects.filter(kill_request__recive_date__date=now, trash=False).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry')

    excel_options = [
        'کد بار',
        'مرغدار',
        'تلفن مرغدار',
        'کدسفارش مرغدار',
        ' شهر مرغدار',
        ' تاریخ کشتار',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'خریدار',
        ' تلفن خریدار',
        ' ماهیت خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'کد رهگیری سامانه قرنطینه',
        'تعداد تخصیصی',
        'تعداد تخلیه شده',
        'وزن بار',
        'تاریخ تخلیه (کشتارگاه)',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            vet_farm = VetFarm.objects.filter(poultry=kill.province_request.poultry_request.poultry, trash=False).last()
            vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
            vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.killhouse_user).last()
            vet_checks = VetCheckRequest.objects.filter(kill_house_request=kill).only('create_date').last()
            kill_house_vet_name = kil_house_vet.vet.user.fullname if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.vet.user.mobile if kil_house_vet else '-'

            code = kill.clearance_code if kill.clearance_code else '-'
            quantity = kill.quantity if kill.quantity else '-'
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=kill.province_request.poultry_request.send_date.day,
                month=kill.province_request.poultry_request.send_date.month,
                year=kill.province_request.poultry_request.send_date.year
            )
            killers = 'کشتارکن'
            if kill.killhouse_user.killer == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request=kill, trash=False).last()
            net_weighte = assignment.net_weight if assignment else '-'
            real_quantity = assignment.real_quantity if assignment else '-'
            date_of_inner_bar = jdatetime.date.fromgregorian(
                day=vet_checks.create_date.day,
                month=vet_checks.create_date.month,
                year=vet_checks.create_date.year
            ) if vet_checks else '-'
            if kill.kill_request.slaughter_house != None:
                kill_place = kill.kill_request.slaughter_house.name
            else:
                kill_place = kill.killhouse_user.name
            if kill.clearance_code:
                l += 1
                list1 = [
                    str(kill.bar_code),
                    kill.province_request.poultry_request.poultry.unit_name,
                    str(kill.province_request.poultry_request.poultry.user.mobile),
                    kill.province_request.poultry_request.order_code,
                    kill.province_request.poultry_request.poultry.user.city.name,
                    str(date_of_poultry_request),
                    kill.province_request.poultry_request.chicken_breed,
                    vet_farm_name,
                    vet_farm_mobile,
                    kill.kill_request.kill_house.name,
                    kill.killhouse_user.phone,
                    killers,
                    kill.killhouse_user.system_address.city.name,
                    kill_place,
                    kill_house_vet_name,
                    kill_house_vet_mobile,
                    code,
                    quantity,
                    real_quantity,
                    net_weighte,
                    str(date_of_inner_bar),

                ]
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="Reporting.xlsx"'
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                         kill_request__recive_date__date__lte=date2,
                                                         trash=False).order_by('-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry')
    # filtered_kill_reqs = [
    #     kill_request for kill_request in kill_requests
    #     if date1 <= kill_request.kill_request.recive_date.date() <= date2
    # ]
    excel_options = [
        'کد بار',
        'مرغدار',
        'تلفن مرغدار',
        'کدسفارش مرغدار',
        ' تاریخ کشتار',
        ' نژاد',
        'خریدار',
        ' تلفن خریدار',
        ' ماهیت خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'تعداد تخصیصی',
        'تعداد تخلیه شده',
        'وزن بار',
        'تاریخ تخلیه (کشتارگاه)',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            l += 1
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.killhouse_user).last()
            vet_checks = VetCheckRequest.objects.filter(kill_house_request=kill).only('create_date').last()
            kill_house_vet_name = kil_house_vet.vet.user.fullname if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.vet.user.mobile if kil_house_vet else '-'

            quantity = kill.quantity if kill.quantity else '-'
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=kill.province_request.poultry_request.send_date.day,
                month=kill.province_request.poultry_request.send_date.month,
                year=kill.province_request.poultry_request.send_date.year
            )
            killers = 'کشتارکن'
            if kill.killhouse_user.killer == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request=kill, trash=False).last()
            net_weighte = assignment.net_weight if assignment else '-'
            real_quantity = assignment.real_quantity if assignment else '-'
            date_of_inner_bar = jdatetime.date.fromgregorian(
                day=vet_checks.create_date.day,
                month=vet_checks.create_date.month,
                year=vet_checks.create_date.year
            ) if vet_checks else '-'
            if kill.kill_request.slaughter_house != None:
                kill_place = kill.kill_request.slaughter_house.name
            else:
                kill_place = kill.killhouse_user.name

            list1 = [
                str(kill.bar_code),
                kill.province_request.poultry_request.poultry.unit_name,
                str(kill.province_request.poultry_request.poultry.user.mobile),
                kill.province_request.poultry_request.order_code,
                str(date_of_poultry_request),
                kill.province_request.poultry_request.chicken_breed,
                kill.kill_request.kill_house.name,
                kill.killhouse_user.phone,
                killers,
                kill.killhouse_user.system_address.city.name,
                kill_place,
                kill_house_vet_name,
                kill_house_vet_mobile,
                quantity,
                real_quantity,
                net_weighte,
                str(date_of_inner_bar),

            ]
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="دامپزشک کشتارگاه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_percent_excel(request):
    user_profile = SystemUserProfile.objects.get(user=request.user, trash=False)
    # kill_house = KillHouse.objects.filter(system_address__province=user_profile.province, trash=False)
    kill_house = KillHousePercentage.objects.filter(
        kill_house__system_address__province=user_profile.province).prefetch_related('kill_house',
                                                                                     'kill_house_for_killer')
    excel_options = [
        'نام واحد',
        'نام و نام خانوادگی',
        'تلفن',
        'آدرس',
        'ماهیت',
        'محل کشتار',
        'نام دامپزشک',
        'تلفن دامپزشک',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 0
    if kill_house:
        for kill in kill_house:
            l += 1
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.kill_house).prefetch_related('vet__user').last()
            kill_house_vet_name = kil_house_vet.vet.user.fullname if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.vet.user.mobile if kil_house_vet else '-'
            kill_place = kill.kill_house_for_killer.name if kill.kill_house_for_killer else kill.kill_house.name
            killer = 'کشتارکن' if kill.kill_house.killer == True else 'کشتارگاه'
            list1 = [
                kill.kill_house.name,
                kill.kill_house.kill_house_operator.user.fullname,
                kill.kill_house.kill_house_operator.user.mobile,
                kill.kill_house.kill_house_operator.address.address,
                killer,
                kill_place,
                kill_house_vet_name,
                kill_house_vet_mobile
            ]
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="محل کشتار.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def poultry_request_out_excel(request):
    now = datetime.datetime.now().date()
    date = datetime.datetime.strptime(request.GET['date'], '%Y-%m-%d') if 'date' in request.GET else now
    user = SystemUserProfile.objects.get(user=request.user, trash=False)

    poultry_requests = 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, out_province_request_cancel=False).order_by(
        '-send_date').select_related(
        'poultry__user')
    list1 = []
    for poultry_request in poultry_requests:
        for buyer in poultry_request.buyer:
            list1.append(buyer)
    return HttpResponse(list1)

    # excel_options = [
    #     'نام فارم',
    #     'سالن',
    #     ' دوره جوجه ریزی',
    #     'تاریخ ثبت جوجه ریزی',
    #     'تاریخ جوجه ریزی',
    #     'نژاد',
    #     'سن',
    #     'تعداد جوجه ریزی',
    #     'تلفات دوره',
    #     'کشتار شده',
    #     'مانده در سالن',
    # ]
    # output = BytesIO()
    # workbook = Workbook()
    # worksheet = workbook.active
    # worksheet.sheet_view.rightToLeft = True
    # worksheet.insert_rows(1)
    # blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    # cell = worksheet.cell(row=1, column=1)
    # cell.alignment = Alignment(horizontal='center', vertical='center')
    # for col_num, option in enumerate(excel_options, 1):
    #     col_letter = get_column_letter(col_num)
    #     cell = worksheet.cell(row=1, column=col_num, value=option)
    #     cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    #     cell.fill = blue_fill
    #     cell.font = Font(size=10, bold=True, color='D9FFFFFF')
    #     worksheet.column_dimensions[col_letter].width = 20.01
    #     worksheet.row_dimensions[1].height = 18
    #     worksheet.freeze_panes = worksheet['A2']
    #     max_col = worksheet.max_column
    #     range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
    #     worksheet.auto_filter.ref = range_str
    #
    # l = 0
    # if poultry_requests:
    #     for poultry_request in poultry_requests:
    #         buyer_list = poultry_request.buyer
    #         for buyer in buyer_list:
    #             list1 = [
    #                 poultry_request.poultry.unit_name,
    #             ]
    #             for item in range(len(list1)):
    #                 cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
    #                 cell.alignment = Alignment(horizontal='center')
    # workbook.save(output)
    # output.seek(0)
    #
    # response = HttpResponse(
    #     content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    # response[
    #     'Content-Disposition'] = f'attachment; filename="دامپزشک کشتارگاه.xlsx"'.encode(
    #     'utf-8')
    # response.write(output.getvalue())
    # return response


def get_all_user_excel(request):
    users = SystemUserProfile.objects.filter(trash=False).prefetch_related('role').only(
        'role__name', 'fullname', 'mobile', 'city__name', 'user_gate_way_id'
    ).exclude(role__name='Rancher').order_by('id')

    excel_options = [
        'ردیف',
        'نام کامل',
        'شماره تلفن',
        'رمز',
        'توکن',
        'شهرستان',
        'مرغدار',
        'کشتارگاه',
        'اپراتور استان',
        'اپراتور شهرستان',
        'دامپزشک فارم',
        'دامپزشک کشتارگاه',
        'راننده',
        'اصناف',
        'مباشر',
        'اپراتور مالی',
        'دامپزشک کل',
        'شرکت psp',
        'استانداری',
        'بازرس استان',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=3, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 26.01
        worksheet.row_dimensions[3].height = 25
        worksheet.freeze_panes = worksheet['A4']
        max_col = worksheet.max_column
        range_str = f'A3:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    worksheet['A2'] = f'گزارش کاربران استان {users.first().province.name}'

    worksheet['A2'].font = Font(color="C00000", bold=True)
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    merge_range1 = 'A2:B2'

    worksheet.merge_cells(merge_range1)
    l = 2
    m = 1

    for user in users:
        role_list = [role.name for role in user.role.all()]

        poultry = '✔' if 'Poultry' in role_list else '-'
        KillHouse = '✔' if 'KillHouse' in role_list else '-'
        ProvinceOperator = '✔' if 'ProvinceOperator' in role_list else '-'
        CityOperator = '✔' if 'CityOperator' in role_list else '-'
        VetFarm = '✔' if 'VetFarm' in role_list else '-'
        KillHouseVet = '✔' if 'KillHouseVet' in role_list else '-'
        Driver = '✔' if 'Driver' in role_list else '-'
        Guilds = '✔' if 'Guilds' in role_list else '-'
        Steward = '✔' if 'Steward' in role_list else '-'
        ProvinceFinancial = '✔' if 'ProvinceFinancial' in role_list else '-'
        VetSupervisor = '✔' if 'VetSupervisor' in role_list else '-'
        PosCompany = '✔' if 'PosCompany' in role_list else '-'
        ProvincialGovernment = '✔' if 'ProvincialGovernment' in role_list else '-'
        ProvinceInspector = '✔' if 'ProvinceInspector' in role_list else '-'
        city = user.city.name if user.city else '-'
        list1 = [
            m,
            user.fullname,
            user.mobile,
            user.password,
            user.user_gate_way_id,
            city,
            poultry,
            KillHouse,
            ProvinceOperator,
            CityOperator,
            VetFarm,
            KillHouseVet,
            Driver,
            Guilds,
            Steward,
            ProvinceFinancial,
            VetSupervisor,
            PosCompany,
            ProvincialGovernment,
            ProvinceInspector,

        ]
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        m += 1
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت کاربران.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def stewards_excel(request):
    stewards = Steward.objects.filter(guilds__steward=True, trash=False).order_by('-create_date')
    user = SystemUserProfile.objects.get(key=request.GET['key'])
    if request.GET['role'] in ['CityCommerce', 'CityJahad', 'CityPoultry']:
        stewards = stewards.filter(guilds__address__city=user.city).order_by('id')

    elif request.GET['role'] in ['ProvinceOperator', 'Commerce', 'ProvinceSupervisor''GuildRoom', 'SuperAdmin',
                                 'ImprovingLivestock', 'AdminX', 'Supporter']:
        stewards = stewards.filter(guilds__address__province=user.province,
                                   ).order_by('id')
    else:
        stewards = stewards

    excel_options = [
        'ردیف',
        'شناسه صنف',
        'نام واحد صنفی',
        'نام شخص/شرکت',
        'موبایل شخص/شرکت',
        'کدملی',
        'نوع فعالیت',
        'حوزه فعالیت',
        'شماره مجوز',
        'استان',
        'شهرستان',
        'آدرس واحد صنفی',
        'محدودیت تخصیص',
        'حداکثر تخصیص',
        'مراکز تخصیص',
        'کارتخوان دارد / ندارد',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[4].height = 18
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    header_list = [
        'تعداد کل مباشرین',
        'تعداد مباشرین فاقد کشتارگاه',
        'تعداد مباشرین دارای کارتخوان',
    ]
    if stewards:
        city = 'استان' + ' ' + stewards.first().guilds.address.province.name
    else:
        city = ''
    worksheet['A2'] = f'مدیریت مباشرین {city}'

    worksheet['A2'].font = Font(color="C00000", bold=True)
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    merge_range1 = 'A2:B2'
    worksheet.merge_cells(merge_range1)

    l = 3
    m = 1
    all_centers_allocations = 0
    all_has_pos = 0
    for steward in stewards:
        l += 1
        max_allocation = steward.allocation_limit if steward.allocation_limit else 0
        limitation_allocation = 'دارد' if steward.limitation_allocation == True else 'ندارد'

        centers_allocations = '-'
        if steward.centers_allocation == None:
            centers_allocations = '-'
            all_centers_allocations += 1

        else:
            for center_allocation in steward.centers_allocation:
                centers_allocations = center_allocation['label']

        if steward.guilds.has_pos == True:
            has_pos = 'دارد'
            all_has_pos += 1
        else:
            has_pos = 'ندارد'
        list1 = [
            m,
            steward.guilds.guilds_id,
            steward.guilds.guilds_name,
            steward.guilds.user.fullname,
            steward.guilds.user.mobile,
            steward.guilds.user.national_id if steward.guilds.user.national_id else '-',
            steward.guilds.type_activity,
            steward.guilds.area_activity,
            steward.guilds.license_number,
            steward.guilds.address.province.name,
            steward.guilds.address.city.name,
            steward.guilds.address.address,
            limitation_allocation,
            max_allocation,
            centers_allocations,
            has_pos
        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

        m += 1
    for col_num, option in enumerate(header_list, 4):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        col_letter = get_column_letter(col_num)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 21
        worksheet.column_dimensions[col_letter].width = 16.01
    values_list = [
        m - 1,
        all_centers_allocations,
        all_has_pos

    ]
    for item in range(len(values_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
        cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت مباشرین.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def all_kill_house_total_wage_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                       '%Y-%m-%d').date() if 'date1' in request.GET else None
    date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                       '%Y-%m-%d').date() if 'date2' in request.GET else None
    kill_house_list = []
    access = AccessToken.objects.get(token=request.GET['token'])

    user = get_object_or_404(SystemUserProfile, user=access.user)
    kill_houses = KillHouse.objects.filter(system_address__province=user.province, trash=False)
    if 'date1' in request.GET:
        for kill_house in kill_houses:
            if ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                  kill_request__recive_date__lte=date2, killhouse_user=kill_house,
                                                  trash=False).exists():
                if kill_house not in kill_house_list:
                    kill_house_list.append(kill_house)
    else:
        for kill_house in kill_houses:
            if ProvinceKillRequest.objects.filter(killhouse_user=kill_house, trash=False).exists():
                if kill_house not in kill_house_list:
                    kill_house_list.append(kill_house)
    excel_options = [
        'ردیف',
        'خریدار',
        'مالک',
        'تلفن خریدار',
        'شهر',
        'تعداد کل سفارشات',
        'تعداد کل قطعه ها',
        'وزن کل(کیلوگرم)',
        'مبلغ کل(ریال)',
        'تعداد سفارشات پرداخت شده',
        'تعداد قطعات پرداخت شده',
        'وزن قطعات پرداخت شده(کیلوگرم)',
        'مبلغ قطعات پرداخت شده(ریال)',
        'تعداد سفارشات پرداخت نشده',
        'تعداد قطعات پرداخت نشده',
        'وزن قطعات پرداخت نشده(کیلوگرم)',
        'مبلغ قطعات پرداخت نشده(ریال)',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=5, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[5].height = 29
        worksheet.freeze_panes = worksheet['A6']
        max_col = worksheet.max_column
        range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    l = 4
    m = 1
    if 'date1' in request.GET:
        province_kill_requests = ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                                    kill_request__recive_date__lte=date2,
                                                                    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)),
        )
    else:
        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)),
        )
    if 'date1' in request.GET:
        from_date = jdatetime.date.fromgregorian(
            year=date1.year,
            month=date1.month,
            day=date1.day
        ).strftime('%Y-%m-%d')
        reversed_date = reversed(from_date.split("-"))
        separate = "-"
        from_date_1 = separate.join(reversed_date)

        to_date = jdatetime.date.fromgregorian(
            year=date2.year,
            month=date2.month,
            day=date2.day
        ).strftime('%Y-%m-%d')
        reversed_date1 = reversed(to_date.split("-"))
        separate = "-"
        from_date_2 = separate.join(reversed_date1)
        worksheet['A2'] = f'گزارش کارمزدها از {from_date_1} تا {from_date_2}'

        worksheet['A2'].font = Font(color="C00000", bold=True)
        worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        merge_range1 = 'A2:B2'

        worksheet.merge_cells(merge_range1)
    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']
    head_list = [
        'تعداد خریداران',
        'تعداد کل سفارشات',
        'تعداد کل قطعه',
        'وزن کل سفارشات (کیلوگرم)',
        'مبلغ کل سفارشات (ریال)',
        'تعداد سفارش پرداخت شده',
        'تعداد قطعه پرداخت شده',
        'وزن سفارشات پرداخت شده (کیلوگرم)',
        'مبلغ سفارشات پرداخت شده (ریال)',
        'تعداد سفارش پرداخت نشده',
        'تعداد قطعه پرداخت نشده',
        'وزن سفارشات پرداخت نشده (کیلوگرم)',
        'مبلغ سفارشات پرداخت نشده (ریال)',
        'تعداد سفارش بایگانی شده',
        'تعداد قطعه بایگانی شده',
        'وزن سفارشات بایگانی شده (کیلوگرم)',
        'مبلغ سفارشات بایگانی شده (ریال)',
    ]
    for col_num, option in enumerate(head_list, 3):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="31869B", fill_type="solid")
        cell.font = Font(size=10, bold=True, color='FFFFFF')
        worksheet.row_dimensions[2].height = 36
        worksheet.column_dimensions[col_letter].width = 16
    value_list = [
        total_requests_buyers,
        total_requests,
        total_requests_quantity,
        total_requests_weight,
        total_requests_amount,
        total_paid_requests,
        total_paid_requests_quantity if total_paid_requests_quantity != None else 0,
        total_paid_requests_weight if total_paid_requests_weight != None else 0,
        total_paid_requests_amount if total_paid_requests_amount != None else 0,
        total_unpaid_requests,
        total_unpaid_requests_quantity,
        total_unpaid_requests_weight,
        total_unpaid_requests_amount,
        total_archive_requests,
        total_archive_requests_quantity,
        total_archive_requests_weight,
        total_archive_requests_amount,

    ]
    for item in range(len(value_list)):
        cell = worksheet.cell(row=3, column=item + 3, value=value_list[item])
        cell.alignment = Alignment(horizontal='center')
        value = value_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values
    for kill_houses in kill_house_list:
        l += 1
        province_kill_request = province_kill_requests.filter(killhouse_user=kill_houses)

        paid_count = 0  #
        unpaid_count = 0  #
        total_weight_unpaid = 0  #
        total_weight_paid = 0  #
        total_unpaid_wage = 0  #
        total_paid_wage = 0  #
        total_paid_quantity = 0  #
        total_unpaid_quantity = 0  #
        fullname = kill_houses.kill_house_operator.user.fullname
        city = kill_houses.kill_house_operator.user.city.name
        mobile = kill_houses.kill_house_operator.user.mobile
        total_count = len(province_kill_request)  #
        total_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity', 0)  #

        for province_kill in province_kill_request:
            if province_kill.wage_pay == True:
                paid_count += 1  #
                total_paid_quantity += province_kill.total_killed_quantity  #
                total_paid_wage += int(province_kill.depositor['total_amount'])  #
                total_weight_paid += province_kill.total_killed_weight  #
            elif province_kill.wage_pay == False and province_kill.archive_by_province == False:
                unpaid_count += 1  #
                total_unpaid_quantity += province_kill.total_killed_quantity  #
                total_unpaid_wage += province_kill.total_killed_weight * province_kill.wage  #
                total_weight_unpaid += province_kill.total_killed_weight  #

            else:
                pass
        killer = 'کشتارگاه' if kill_houses.killer == False else 'کشتارکن'
        list1 = [
            m,
            killer + '(' + kill_houses.name + ')',
            fullname,
            mobile,
            city,
            total_count,
            total_quantity,
            int(total_weight_paid + total_weight_unpaid),
            total_paid_wage + total_unpaid_wage,
            paid_count,
            total_paid_quantity,
            int(total_weight_paid),
            total_paid_wage,
            unpaid_count,
            total_unpaid_quantity,
            int(total_weight_unpaid),
            total_unpaid_wage,

        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        m += 1
        workbook.save(output)
        output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش کارمزد ها.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_total_wage_not_payid_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                       '%Y-%m-%d').date() if 'date1' in request.GET else None
    date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                       '%Y-%m-%d').date() if 'date2' in request.GET else None
    kill_house_list = []
    access = AccessToken.objects.get(token=request.GET['token'])
    user = get_object_or_404(SystemUserProfile, user=access.user)
    kill_houses = KillHouse.objects.filter(system_address__province=user.province, trash=False)
    if 'date1' in request.GET:

        for kill_house in kill_houses:
            if ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                  kill_request__recive_date__lte=date2, killhouse_user=kill_house,
                                                  wage_pay=True,
                                                  archive_by_province=False, return_to_province=False,
                                                  trash=False).exists():
                if kill_house not in kill_house_list:
                    kill_house_list.append(kill_house)
    else:
        for kill_house in kill_houses:
            if ProvinceKillRequest.objects.filter(killhouse_user=kill_house, wage_pay=True,
                                                  archive_by_province=False, return_to_province=False,
                                                  trash=False).exists():
                if kill_house not in kill_house_list:
                    kill_house_list.append(kill_house)
    excel_options = [
        'ردیف',
        'کد سفارش',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'تاریخ کشتار',
        'محل کشتار',
        'نژاد',
        'تعداد(قطعه)',
        'وزن(کیلوگرم)',
        'میانگین وزنی(کیلوگرم)',
        'کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)

    sheet_name = 'اطلاعات کلی'
    worksheet = workbook.create_sheet(sheet_name)

    if sheet_name == 'اطلاعات کلی':
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')

        if 'date1' in request.GET:
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date1 = reversed(to_date.split("-"))
            separate = "-"
            from_date_2 = separate.join(reversed_date1)
            worksheet['C2'] = f'کارمزد های پرداخت شده از {from_date_1} تا {from_date_2}'

            worksheet['C2'].font = Font(color="C00000", bold=True)
            worksheet['C2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

        header_list1 = [
            'تعداد کل سفارشات ',
            'مجموع تعداد کل(قطعه)',
            'مجموع وزن کل(کیلوگرم)',
            'میانگین کل کارمزداتحادیه(ریال)',
            'مبلغ کل کارمزدها(ریال)',

        ]
        header_list = [
            'خریدار',
            'مالک',
            'تعداد سفارشات ',
            'مجموع تعداد(قطعه)',
            'مجموع وزن(کیلوگرم)',
            'میانگین کارمزد اتحادیه(ریال)',
            'مبلغ کل کارمزد(ریال)',

        ]
        for col_num, option in enumerate(header_list, 3):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=5, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = PatternFill(start_color="31869B", fill_type="solid")
            cell.font = Font(size=10, bold=True, color='FFFFFF')
            worksheet.row_dimensions[5].height = 45
            worksheet.column_dimensions[col_letter].width = 27
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
        for col_num, option in enumerate(header_list1, 4):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=2, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='FFFFFF')
            worksheet.row_dimensions[2].height = 35
            worksheet.column_dimensions[col_letter].width = 18
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
        l = 6
        all_province_kill_request = 0
        final_quantity = 0
        fianl_wage = 0
        final_wage_all = []
        final_total_amount = 0
        if 'date1' in request.GET:
            for kill_house in kill_house_list:
                province_kill_request = ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                                           kill_request__recive_date__lte=date2,
                                                                           killhouse_user__key=kill_house.key,
                                                                           state__in=('pending', 'accepted'),
                                                                           wage_pay=True,
                                                                           trash=False).select_related(
                    'province_request').only('province_request__key', 'main_quantity', 'wage', 'total_amount').order_by(
                    '-kill_request__recive_date')
                all_quantity = province_kill_request.aggregate(total_quantity=Sum('main_quantity')).get(
                    'total_quantity', 0)
                all_wiegh = 0
                all_wage = []
                all_total_amount = 0
                all_province_kill_request += len(province_kill_request)
                final_quantity += all_quantity
                for province in province_kill_request:
                    province_request = ProvinceCheckOperatorRequest.objects.select_related(
                        'poultry_request').filter(
                        key=province.province_request.key,
                        trash=False).only('poultry_request__Index_weight').first()
                    wieght = int(province.main_quantity * province_request.poultry_request.Index_weight)
                    all_wiegh += wieght
                    wage = province.wage
                    if wage > 0:
                        all_wage.append(wage)
                    total_amount = province.total_amount if province.total_amount > 0 else int(province.wage) * int(
                        province.main_quantity * province_request.poultry_request.Index_weight)
                    all_total_amount += total_amount
                final_total_amount += all_total_amount
                fianl_wage += all_wiegh

                if len(all_wage) > 0:
                    wage_all = sum(all_wage) / len(all_wage)
                    final_wage_all.append(wage_all)
                else:
                    wage_all = 0
                killer = 'کشتارگاه' if kill_house.killer == False else 'کشتارکن'

                values_list = [
                    killer + '(' + kill_house.name + ')',
                    kill_house.kill_house_operator.user.fullname,
                    len(province_kill_request),
                    all_quantity,
                    all_wiegh,
                    wage_all,
                    all_total_amount,

                ]
                for item in range(len(values_list)):
                    cell = worksheet.cell(row=l, column=item + 3, value=values_list[item])
                    cell.alignment = Alignment(horizontal='center')
                    cell.font = Font(size=10, bold=True)
                    cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid")
                    value = values_list[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                l += 1
        else:
            for kill_house in kill_house_list:
                province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user__key=kill_house.key,
                                                                           state__in=('pending', 'accepted'),
                                                                           wage_pay=True,
                                                                           trash=False).select_related(
                    'province_request').only('province_request__key', 'main_quantity', 'wage', 'total_amount').order_by(
                    '-kill_request__recive_date')
                all_quantity = province_kill_request.aggregate(total_quantity=Sum('main_quantity')).get(
                    'total_quantity', 0)
                all_wiegh = 0
                all_wage = []
                all_total_amount = 0
                all_province_kill_request += len(province_kill_request)
                final_quantity += all_quantity
                for province in province_kill_request:
                    province_request = ProvinceCheckOperatorRequest.objects.select_related(
                        'poultry_request').filter(
                        key=province.province_request.key,
                        trash=False).only('poultry_request__Index_weight').first()
                    wieght = int(province.main_quantity * province_request.poultry_request.Index_weight)
                    all_wiegh += wieght
                    wage = province.wage
                    if wage > 0:
                        all_wage.append(wage)
                    total_amount = province.total_amount if province.total_amount > 0 else int(province.wage) * int(
                        province.main_quantity * province_request.poultry_request.Index_weight)
                    all_total_amount += total_amount
                final_total_amount += all_total_amount
                fianl_wage += all_wiegh

                if len(all_wage) > 0:
                    wage_all = sum(all_wage) / len(all_wage)
                    final_wage_all.append(wage_all)
                else:
                    wage_all = 0
                killer = 'کشتارگاه' if kill_house.killer == False else 'کشتارکن'

                values_list = [
                    killer + '(' + kill_house.name + ')',
                    kill_house.kill_house_operator.user.fullname,
                    len(province_kill_request),
                    all_quantity,
                    all_wiegh,
                    wage_all,
                    all_total_amount,

                ]
                for item in range(len(values_list)):
                    cell = worksheet.cell(row=l, column=item + 3, value=values_list[item])
                    cell.alignment = Alignment(horizontal='center')
                    cell.font = Font(size=10, bold=True)
                    cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid")
                    value = values_list[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                l += 1

        if len(final_wage_all) > 0:
            wage = sum(final_wage_all) / len(final_wage_all)
        else:
            wage = 0
        values_list = [
            all_province_kill_request,
            final_quantity,
            fianl_wage,
            wage,
            final_total_amount

        ]
        for item in range(len(values_list)):
            cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10, bold=True)
            cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid")
            value = values_list[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
    for kill_house in kill_house_list:
        sheet_name = kill_house.kill_house_operator.user.fullname
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        if 'date1' in request.GET:
            province_kill_request = ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                                       kill_request__recive_date__lte=date2,
                                                                       killhouse_user__key=kill_house.key,
                                                                       wage_pay=True,
                                                                       state__in=('pending', 'accepted'),
                                                                       trash=False).select_related(
                'province_request__poultry_request', 'province_request__poultry_request__poultry',
                'kill_request').order_by(
                '-kill_request__recive_date')
        else:
            province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user__key=kill_house.key,
                                                                       wage_pay=True,
                                                                       state__in=('pending', 'accepted'),
                                                                       trash=False).select_related(
                'province_request__poultry_request', 'province_request__poultry_request__poultry',
                'kill_request').order_by(
                '-kill_request__recive_date')
        all_quantity = province_kill_request.aggregate(total_quantity=Sum('main_quantity')).get(
            'total_quantity', 0)
        all_wiegh = 0
        all_wage = []

        all_total_amount = 0

        # برای بالای هدر
        header_list = [
            'تعداد سفارشات ',
            'مجموع تعداد(قطعه)',
            'مجموع وزن(کیلوگرم)',
            'میانگین کارمزد اتحادیه(ریال)',
            'مبلغ کل کارمزد(ریال)',

        ]
        for col_num, option in enumerate(header_list, 4):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=2, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = PatternFill(start_color="31869B", fill_type="solid")
            cell.font = Font(size=10, bold=True, color='FFFFFF')
            worksheet.row_dimensions[2].height = 36
            worksheet.column_dimensions[col_letter].width = 16

        l = 4
        m = 1
        for col_num, option in enumerate(excel_options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=5, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            worksheet.column_dimensions[col_letter].width = 20.01
            worksheet.row_dimensions[5].height = 27
            worksheet.freeze_panes = worksheet['A6']
            max_col = worksheet.max_column
            range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str

        for province in province_kill_request:

            province_request = ProvinceCheckOperatorRequest.objects.select_related(
                'poultry_request__poultry__user', 'poultry_request__poultry__address__city', 'poultry_request').filter(
                key=province.province_request.key,
                trash=False).only('poultry_request__send_date', 'poultry_request__order_code',
                                  'poultry_request__poultry__user__fullname', 'poultry_request__poultry__user__mobile',
                                  'poultry_request__poultry__address__city__name', 'poultry_request__chicken_breed',
                                  'poultry_request__Index_weight').first()
            kill_place = province.kill_request.slaughter_house.name if province.kill_request.slaughter_house != None else province.kill_request.kill_house.name
            total_amount = province.total_amount if province.total_amount > 0 else int(province.wage) * int(
                province.main_quantity * province_request.poultry_request.Index_weight)
            all_total_amount += total_amount
            send_date = jdatetime.date.fromgregorian(
                day=province_request.poultry_request.send_date.day,
                month=province_request.poultry_request.send_date.month,
                year=province_request.poultry_request.send_date.year
            ) if province_request.poultry_request.send_date else '-'
            wieght = int(province.main_quantity * province_request.poultry_request.Index_weight)
            all_wiegh += wieght
            wage = province.wage
            if wage > 0:
                all_wage.append(wage)
            list1 = [
                m,
                str(province_request.poultry_request.order_code),
                province_request.poultry_request.poultry.user.fullname,
                province_request.poultry_request.poultry.user.mobile,
                province_request.poultry_request.poultry.address.city.name,
                str(send_date),
                kill_place,
                province_request.poultry_request.chicken_breed,
                province.main_quantity,
                wieght,
                province_request.poultry_request.Index_weight,
                province.wage,
                total_amount
            ]
            l += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10)
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
            m += 1
        if len(all_wage) > 0:
            wage_all = sum(all_wage) / len(all_wage)
        else:
            wage_all = 0
        values_list = [
            m - 1,
            all_quantity,
            all_wiegh,
            wage_all,
            all_total_amount,

        ]
        for item in range(len(values_list)):
            cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10)
            value = values_list[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            f'',
            '',
            '',
            '',
            all_quantity,
            all_wiegh,
            '',
            wage_all,
            all_total_amount,

        ]
        for item in range(len(list2)):
            cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
            value = list2[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values

            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(bold=True)
            cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="کارمزدهای پرداخت شده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def slaughterhouse_fee_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else '-'
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date1' in request.GET else '-'
    user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    if 'date1' and 'date2' in request.GET:

        province_kill_request = (ProvinceKillRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                    kill_request__recive_date__date__lte=date2,
                                                                    killhouse_user=kill_house,
                                                                    state__in=('pending', 'accepted'), wage_pay=True,
                                                                    trash=False,
                                                                    archive_by_province=False,
                                                                    return_to_province=False,
                                                                    ).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
            .only('kill_request__kill_house__name', 'total_killed_quantity', 'province_request__key',
                  'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                  'main_quantity', 'wage', 'total_amount'
                  , 'total_killed_weight')
            .values('kill_request__kill_house__name', 'total_killed_quantity', 'total_killed_weight',
                    'province_request__key',
                    'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                    'main_quantity', 'wage', 'total_amount', ).order_by(
            '-kill_request__recive_date'))
    else:
        province_kill_request = (ProvinceKillRequest.objects.filter(
            killhouse_user=kill_house,
            state__in=('pending', 'accepted'), wage_pay=True,
            trash=False,
            archive_by_province=False,
            return_to_province=False,
        ).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
            .only('kill_request__kill_house__name', 'total_killed_quantity', 'province_request__key',
                  'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                  'main_quantity', 'wage', 'total_amount'
                  , 'total_killed_weight', 'kill_request__recive_date')
            .values('kill_request__kill_house__name', 'total_killed_quantity', 'total_killed_weight',
                    'province_request__key',
                    'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                    'main_quantity', 'wage', 'total_amount', 'kill_request__recive_date').order_by(
            '-kill_request__recive_date'))
    all_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
        'total_quantity', 0)
    all_wiegh = province_kill_request.aggregate(total_quantity=Sum('total_killed_weight')).get(
        'total_quantity', 0)
    all_wage = []

    all_total_amount = 0

    red_font = Font(color="C00000", bold=True)

    excel_options = [
        'ردیف',
        'کد سفارش',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'تاریخ کشتار',
        'محل کشتار',
        'نژاد',
        'تعداد(قطعه)',
        'وزن(کیلوگرم)',
        'میانگین وزنی(کیلوگرم)',
        'کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center', )
    if kill_house:
        if 'date1' in request.GET:
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            worksheet['A2'] = f'کارمزد های پرداخت شده خریدار {kill_house.name} از تاریخ {from_date_1} تا {to_date_1}'
        else:
            first = province_kill_request.first()['kill_request__recive_date']
            last = province_kill_request.last()['kill_request__recive_date']
            from_date = jdatetime.date.fromgregorian(
                year=first.year,
                month=first.month,
                day=first.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=last.year,
                month=last.month,
                day=last.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            worksheet['A2'] = f'کارمزد های پرداخت شده خریدار {kill_house.name} از تاریخ {to_date_1} تا {from_date_1}'

    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    merge_range1 = 'A2:C2'

    worksheet.merge_cells(merge_range1)
    worksheet['A2'].font = red_font
    # برای بالای هدر
    header_list = [
        'تعداد سفارشات ',
        'مجموع تعداد(قطعه)',
        'مجموع وزن(کیلوگرم)',
        'میانگین کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',

    ]
    for col_num, option in enumerate(header_list, 4):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="31869B", fill_type="solid")
        cell.font = Font(size=10, bold=True, color='FFFFFF')
        worksheet.row_dimensions[2].height = 36
        worksheet.column_dimensions[col_letter].width = 16

    l = 4
    m = 1
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=5, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[5].height = 27
        worksheet.freeze_panes = worksheet['A6']
        max_col = worksheet.max_column
        range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    for province in province_kill_request:

        province_request = ProvinceCheckOperatorRequest.objects.select_related(
            'poultry_request__poultry__user', 'poultry_request__poultry__address__city', 'poultry_request').filter(
            key=province['province_request__key'],
            trash=False).only('poultry_request__send_date', 'poultry_request__order_code',
                              'poultry_request__poultry__user__fullname', 'poultry_request__poultry__user__mobile',
                              'poultry_request__poultry__address__city__name', 'poultry_request__chicken_breed',
                              'poultry_request__Index_weight').values('poultry_request__send_date',
                                                                      'poultry_request__order_code',
                                                                      'poultry_request__poultry__user__fullname',
                                                                      'poultry_request__poultry__user__mobile',
                                                                      'poultry_request__poultry__address__city__name',
                                                                      'poultry_request__chicken_breed',
                                                                      'poultry_request__Index_weight').first()
        kill_place = province['kill_request__slaughter_house__name'] if province[
                                                                            'kill_request__slaughter_house'] != None else \
            province['kill_request__kill_house__name']
        total_amount = (province['total_killed_weight'] * province['wage']) if province['total_amount'] == 0 else \
            province['total_amount']
        all_total_amount += total_amount
        send_date = jdatetime.date.fromgregorian(
            day=province_request['poultry_request__send_date'].day,
            month=province_request['poultry_request__send_date'].month,
            year=province_request['poultry_request__send_date'].year
        ) if province_request['poultry_request__send_date'] else '-'
        wieght = province['total_killed_weight']
        wage = province['wage']
        if wage > 0:
            all_wage.append(wage)
        list1 = [
            m,
            str(province_request['poultry_request__order_code']),
            province_request['poultry_request__poultry__user__fullname'],
            province_request['poultry_request__poultry__user__mobile'],
            province_request['poultry_request__poultry__address__city__name'],
            str(send_date),
            kill_place,
            province_request['poultry_request__chicken_breed'],
            province['total_killed_quantity'],
            wieght,
            province_request['poultry_request__Index_weight'],
            province['wage'],
            total_amount
        ]
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10)
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        m += 1
    if len(all_wage) > 0:
        wage_all = sum(all_wage) / len(all_wage)
    else:
        wage_all = 0
    values_list = [
        m - 1,
        all_quantity,
        all_wiegh,
        wage_all,
        all_total_amount,

    ]
    for item in range(len(values_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10)
        value = values_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        f'',
        '',
        '',
        '',
        all_quantity,
        all_wiegh,
        '',
        wage_all,
        all_total_amount,

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    if kill_house:
        response[
            'Content-Disposition'] = f'attachment; filename="کارمزدهای پرداخت شده {kill_house.name}.xlsx"'.encode(
            'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="کارمزدهای پرداخت شده.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def slaughterhouse_fee_not_paid_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else '-'
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date1' in request.GET else '-'
    user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    if 'date1' and 'date2' in request.GET:

        province_kill_request = (ProvinceKillRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                    kill_request__recive_date__date__lte=date2,
                                                                    killhouse_user=kill_house,
                                                                    state__in=('pending', 'accepted'), wage_pay=False,
                                                                    trash=False,
                                                                    archive_by_province=False,
                                                                    return_to_province=False,
                                                                    ).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
            .only('kill_request__kill_house__name', 'total_killed_quantity', 'province_request__key',
                  'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                  'main_quantity', 'wage', 'total_amount'
                  , 'total_killed_weight')
            .values('kill_request__kill_house__name', 'total_killed_quantity', 'total_killed_weight',
                    'province_request__key', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                    'main_quantity', 'wage', 'total_amount', ).order_by(
            '-kill_request__recive_date'))
    else:
        province_kill_request = (ProvinceKillRequest.objects.filter(
            killhouse_user=kill_house,
            state__in=('pending', 'accepted'), wage_pay=False,
            trash=False,
            archive_by_province=False,
            return_to_province=False,
        ).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
            .only('kill_request__kill_house__name', 'total_killed_quantity', 'province_request__key',
                  'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                  'main_quantity', 'wage', 'total_amount'
                  , 'total_killed_weight', 'kill_request__recive_date')
            .values('kill_request__kill_house__name', 'total_killed_quantity', 'total_killed_weight',
                    'province_request__key', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                    'main_quantity', 'wage', 'total_amount', 'kill_request__recive_date').order_by(
            '-kill_request__recive_date'))
    all_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
        'total_quantity', 0)
    all_wiegh = province_kill_request.aggregate(total_quantity=Sum('total_killed_weight')).get(
        'total_quantity', 0)
    all_wage = []

    all_total_amount = 0

    red_font = Font(color="C00000", bold=True)

    excel_options = [
        'ردیف',
        'کد سفارش',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'تاریخ کشتار',
        'محل کشتار',
        'نژاد',
        'تعداد(قطعه)',
        'وزن(کیلوگرم)',
        'میانگین وزنی(کیلوگرم)',
        'کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center', )
    if kill_house:
        if 'date1' in request.GET:
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            worksheet['A2'] = f'کارمزد های پرداخت نشده خریدار {kill_house.name} از تاریخ {from_date_1} تا {to_date_1}'
        else:
            first = province_kill_request.first()['kill_request__recive_date']
            last = province_kill_request.last()['kill_request__recive_date']
            from_date = jdatetime.date.fromgregorian(
                year=first.year,
                month=first.month,
                day=first.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=last.year,
                month=last.month,
                day=last.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            worksheet['A2'] = f'کارمزد های پرداخت شده خریدار {kill_house.name} از تاریخ {to_date_1} تا {from_date_1}'

    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    merge_range1 = 'A2:C2'

    worksheet.merge_cells(merge_range1)
    worksheet['A2'].font = red_font
    # برای بالای هدر
    header_list = [
        'تعداد سفارشات ',
        'مجموع تعداد(قطعه)',
        'مجموع وزن(کیلوگرم)',
        'میانگین کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',

    ]
    for col_num, option in enumerate(header_list, 4):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="31869B", fill_type="solid")
        cell.font = Font(size=10, bold=True, color='FFFFFF')
        worksheet.row_dimensions[2].height = 36
        worksheet.column_dimensions[col_letter].width = 16

    l = 4
    m = 1
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=5, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[5].height = 27
        worksheet.freeze_panes = worksheet['A6']
        max_col = worksheet.max_column
        range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    for province in province_kill_request:

        province_request = ProvinceCheckOperatorRequest.objects.select_related(
            'poultry_request__poultry__user', 'poultry_request__poultry__address__city', 'poultry_request').filter(
            key=province['province_request__key'],
            trash=False).only('poultry_request__send_date', 'poultry_request__order_code',
                              'poultry_request__poultry__user__fullname', 'poultry_request__poultry__user__mobile',
                              'poultry_request__poultry__address__city__name', 'poultry_request__chicken_breed',
                              'poultry_request__Index_weight').values('poultry_request__send_date',
                                                                      'poultry_request__order_code',
                                                                      'poultry_request__poultry__user__fullname',
                                                                      'poultry_request__poultry__user__mobile',
                                                                      'poultry_request__poultry__address__city__name',
                                                                      'poultry_request__chicken_breed',
                                                                      'poultry_request__Index_weight').first()
        kill_place = province['kill_request__slaughter_house__name'] if province[
                                                                            'kill_request__slaughter_house'] != None else \
            province['kill_request__kill_house__name']
        total_amount = (province['total_killed_weight'] * province['wage']) if province['total_amount'] == 0 else \
            province['total_amount']
        all_total_amount += total_amount
        send_date = jdatetime.date.fromgregorian(
            day=province_request['poultry_request__send_date'].day,
            month=province_request['poultry_request__send_date'].month,
            year=province_request['poultry_request__send_date'].year
        ) if province_request['poultry_request__send_date'] else '-'
        wieght = province['total_killed_weight']
        wage = province['wage']
        if wage > 0:
            all_wage.append(wage)
        list1 = [
            m,
            str(province_request['poultry_request__order_code']),
            province_request['poultry_request__poultry__user__fullname'],
            province_request['poultry_request__poultry__user__mobile'],
            province_request['poultry_request__poultry__address__city__name'],
            str(send_date),
            kill_place,
            province_request['poultry_request__chicken_breed'],
            province['total_killed_quantity'],
            wieght,
            province_request['poultry_request__Index_weight'],
            province['wage'],
            total_amount
        ]
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10)
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        m += 1
    if len(all_wage) > 0:
        wage_all = sum(all_wage) / len(all_wage)
    else:
        wage_all = 0
    values_list = [
        m - 1,
        all_quantity,
        all_wiegh,
        wage_all,
        all_total_amount,

    ]
    for item in range(len(values_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10)
        value = values_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        f'',
        '',
        '',
        '',
        all_quantity,
        all_wiegh,
        '',
        wage_all,
        all_total_amount,

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    if kill_house:
        response[
            'Content-Disposition'] = f'attachment; filename="کارمزدهای پرداخت نشده {kill_house.name}.xlsx"'.encode(
            'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="کارمزدهای پرداخت نشده.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def car_province_excel(request):
    user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    cars = KillHouseDriver.objects.filter(trash=False).select_related('user').order_by(
        'id')
    if request.GET['role'] == 'KillHouse':
        kill_house = KillHouse.objects.filter(trash=False, kill_house_operator__user=user).first()
        kill_house_cars = KillHouseADDCAR.objects.filter(kill_house=kill_house, trash=False).values_list('driver__id',
                                                                                                         flat=True).distinct()
        cars = cars.filter(id__in=kill_house_cars)
    excel_options = [
        'ردیف',
        'مدل خودرو',
        'ماهیت',
        'پلاک',
        'ظرفیت',
        'کد بهداشتی',
        'نام راننده',
        'موبایل راننده',
        'کشتارگاه ها/کشتارکن ها',
        'وضعیت'
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=1, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[1].height = 18
        worksheet.freeze_panes = worksheet['A2']
        max_col = worksheet.max_column
        range_str = f'A1:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    l = 0
    m = 1
    for car in cars:
        l += 1

        kill_house_list_name = ''
        kill_house_list = []
        active = 'فعال' if car.active_state else 'غیرفعال'

        add_car = KillHouseADDCAR.objects.filter(driver=car, trash=False).select_related('kill_house').only(
            'kill_house__name')
        kill_house_list = [add_car_obj.kill_house.name if add_car_obj.kill_house else '-' for add_car_obj in add_car]

        if car.type == "rental":
            car_type = "اجاره ای"
            kill_house_list_name = 'همه کشتارگاه ها/کشتارکن ها'
        else:
            car_type = "اختصاصی"
            if kill_house_list:
                if len(kill_house_list) > 1:
                    kill_house_list_name = '/'.join(kill_house_list)
                else:
                    kill_house_list_name = kill_house_list[0]
            else:
                kill_house_list_name = '-'
        fullname = car.user.fullname if car.user else '-'

        mobile = car.user.mobile if car.user else '-'
        list1 = [
            m,
            car.type_car,
            car_type,
            car.pelak,
            car.capocity,
            car.health_code,
            fullname,
            mobile,
            kill_house_list_name,
            active
        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
        m += 1
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="خودروها.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_wage_archive_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if 'date1' in request.GET else '-'
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if 'date1' in request.GET else '-'
    user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    if 'date1' and 'date2' in request.GET:
        province_kill_request = (ProvinceKillRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                    kill_request__recive_date__date__lte=date2,
                                                                    killhouse_user=kill_house,
                                                                    state__in=('pending', 'accepted'), wage_pay=False,
                                                                    archive_by_province=True, return_to_province=False,
                                                                    trash=False).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
            .only('kill_request__kill_house__name', 'total_killed_quantity', 'province_request__key',
                  'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                  'main_quantity', 'wage', 'total_amount'
                  , 'total_killed_weight')
            .values('kill_request__kill_house__name', 'total_killed_quantity', 'total_killed_weight',
                    'province_request__key', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                    'main_quantity', 'wage', 'total_amount', ).order_by(
            '-kill_request__recive_date'))
    else:
        province_kill_request = (ProvinceKillRequest.objects.filter(
            killhouse_user=kill_house,
            state__in=('pending', 'accepted'), wage_pay=False,
            archive_by_province=True, return_to_province=False,
            trash=False).select_related(
            'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
            .only('kill_request__kill_house__name', 'total_killed_quantity', 'province_request__key',
                  'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                  'main_quantity', 'wage', 'total_amount'
                  , 'total_killed_weight', 'kill_request__recive_date')
            .values('kill_request__kill_house__name', 'total_killed_quantity', 'total_killed_weight',
                    'province_request__key', 'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                    'main_quantity', 'wage', 'total_amount', 'kill_request__recive_date').order_by(
            '-kill_request__recive_date'))
    all_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
        'total_quantity', 0)
    all_wiegh = province_kill_request.aggregate(total_quantity=Sum('total_killed_weight')).get(
        'total_quantity', 0)
    all_wage = []

    all_total_amount = 0

    red_font = Font(color="C00000", bold=True)

    excel_options = [
        'ردیف',
        'کد سفارش',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'تاریخ کشتار',
        'محل کشتار',
        'نژاد',
        'تعداد(قطعه)',
        'وزن(کیلوگرم)',
        'میانگین وزنی(کیلوگرم)',
        'کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center', )
    if kill_house:
        if 'date1' in request.GET:
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            worksheet['A2'] = f'کارمزد های بایگانی شده خریدار {kill_house.name} از تاریخ {from_date_1} تا {to_date_1}'
        else:
            first = province_kill_request.first()['kill_request__recive_date']
            last = province_kill_request.last()['kill_request__recive_date']
            from_date = jdatetime.date.fromgregorian(
                year=first.year,
                month=first.month,
                day=first.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=last.year,
                month=last.month,
                day=last.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            worksheet['A2'] = f'کارمزد های پرداخت شده خریدار {kill_house.name} از تاریخ {to_date_1} تا {from_date_1}'

    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    merge_range1 = 'A2:C2'

    worksheet.merge_cells(merge_range1)
    worksheet['A2'].font = red_font
    # برای بالای هدر
    header_list = [
        'تعداد سفارشات ',
        'مجموع تعداد(قطعه)',
        'مجموع وزن(کیلوگرم)',
        'میانگین کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',

    ]
    for col_num, option in enumerate(header_list, 4):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="31869B", fill_type="solid")
        cell.font = Font(size=10, bold=True, color='FFFFFF')
        worksheet.row_dimensions[2].height = 36
        worksheet.column_dimensions[col_letter].width = 16

    l = 4
    m = 1
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=5, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[5].height = 27
        worksheet.freeze_panes = worksheet['A6']
        max_col = worksheet.max_column
        range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    for province in province_kill_request:

        province_request = ProvinceCheckOperatorRequest.objects.select_related(
            'poultry_request__poultry__user', 'poultry_request__poultry__address__city', 'poultry_request').filter(
            key=province['province_request__key'],
            trash=False).only('poultry_request__send_date', 'poultry_request__order_code',
                              'poultry_request__poultry__user__fullname', 'poultry_request__poultry__user__mobile',
                              'poultry_request__poultry__address__city__name', 'poultry_request__chicken_breed',
                              'poultry_request__Index_weight').values('poultry_request__send_date',
                                                                      'poultry_request__order_code',
                                                                      'poultry_request__poultry__user__fullname',
                                                                      'poultry_request__poultry__user__mobile',
                                                                      'poultry_request__poultry__address__city__name',
                                                                      'poultry_request__chicken_breed',
                                                                      'poultry_request__Index_weight').first()
        kill_place = province['kill_request__slaughter_house__name'] if province[
                                                                            'kill_request__slaughter_house'] != None else \
            province['kill_request__kill_house__name']
        total_amount = (province['total_killed_weight'] * province['wage']) if province['total_amount'] == 0 else \
            province['total_amount']
        all_total_amount += total_amount
        send_date = jdatetime.date.fromgregorian(
            day=province_request['poultry_request__send_date'].day,
            month=province_request['poultry_request__send_date'].month,
            year=province_request['poultry_request__send_date'].year
        ) if province_request['poultry_request__send_date'] else '-'
        wieght = province['total_killed_weight']
        wage = province['wage']
        if wage > 0:
            all_wage.append(wage)
        list1 = [
            m,
            str(province_request['poultry_request__order_code']),
            province_request['poultry_request__poultry__user__fullname'],
            province_request['poultry_request__poultry__user__mobile'],
            province_request['poultry_request__poultry__address__city__name'],
            str(send_date),
            kill_place,
            province_request['poultry_request__chicken_breed'],
            province['total_killed_quantity'],
            wieght,
            province_request['poultry_request__Index_weight'],
            province['wage'],
            total_amount
        ]
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10)
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        m += 1
    if len(all_wage) > 0:
        wage_all = sum(all_wage) / len(all_wage)
    else:
        wage_all = 0
    values_list = [
        m - 1,
        all_quantity,
        all_wiegh,
        wage_all,
        all_total_amount,

    ]
    for item in range(len(values_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10)
        value = values_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        f'',
        '',
        '',
        '',
        all_quantity,
        all_wiegh,
        '',
        wage_all,
        all_total_amount,

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    if kill_house:
        response[
            'Content-Disposition'] = f'attachment; filename="کارمزدهای بایگانی شده {kill_house.name}.xlsx"'.encode(
            'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="کارمزدهای بایگانی شده.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_total_wage_archive_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                       '%Y-%m-%d').date() if 'date1' in request.GET else None
    date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                       '%Y-%m-%d').date() if 'date2' in request.GET else None
    kill_house_list = []
    user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    kill_houses = (KillHouse.objects.filter(system_address__province=user.province, trash=False).select_related(
        'kill_house_operator__user')
                   .only('name', 'key', 'kill_house_operator__user__fullname', 'killer').values('name', 'key',
                                                                                                'kill_house_operator__user__fullname',
                                                                                                'killer'))
    if 'date1' in request.GET:
        for kill_house in kill_houses:
            if ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                  kill_request__recive_date__lte=date2,
                                                  killhouse_user__key=kill_house['key'], wage_pay=False,
                                                  archive_by_province=True, return_to_province=False,
                                                  trash=False).exists():
                if kill_house not in kill_house_list:
                    kill_house_list.append(kill_house)
    else:
        for kill_house in kill_houses:
            if ProvinceKillRequest.objects.filter(killhouse_user__key=kill_house['key'], wage_pay=False,
                                                  archive_by_province=True, return_to_province=False,
                                                  trash=False).exists():
                if kill_house not in kill_house_list:
                    kill_house_list.append(kill_house)
    excel_options = [
        'ردیف',
        'کد سفارش',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'تاریخ کشتار',
        'محل کشتار',
        'نژاد',
        'تعداد(قطعه)',
        'وزن(کیلوگرم)',
        'میانگین وزنی(کیلوگرم)',
        'کارمزد اتحادیه(ریال)',
        'مبلغ کل کارمزد(ریال)',
    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)

    sheet_name = 'اطلاعات کلی'
    worksheet = workbook.create_sheet(sheet_name)
    if sheet_name == 'اطلاعات کلی':
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        if 'date1' in request.GET:
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date1 = reversed(to_date.split("-"))
            separate = "-"
            from_date_2 = separate.join(reversed_date1)
            worksheet['C2'] = f'کارمزد های معوقه از {from_date_1} تا {from_date_2}'

            worksheet['C2'].font = Font(color="C00000", bold=True)
            worksheet['C2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        header_list1 = [
            'تعداد کل سفارشات ',
            'مجموع تعداد کل(قطعه)',
            'مجموع وزن کل(کیلوگرم)',
            'میانگین کل کارمزداتحادیه(ریال)',
            'مبلغ کل کارمزدها(ریال)',

        ]
        header_list = [
            'خریدار',
            'مالک',
            'تعداد سفارشات ',
            'مجموع تعداد(قطعه)',
            'مجموع وزن(کیلوگرم)',
            'میانگین کارمزد اتحادیه(ریال)',
            'مبلغ کل کارمزد(ریال)',

        ]
        for col_num, option in enumerate(header_list, 3):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=5, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = PatternFill(start_color="31869B", fill_type="solid")
            cell.font = Font(size=10, bold=True, color='FFFFFF')
            worksheet.row_dimensions[5].height = 45
            worksheet.column_dimensions[col_letter].width = 27
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
        for col_num, option in enumerate(header_list1, 4):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=2, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='FFFFFF')
            worksheet.row_dimensions[2].height = 35
            worksheet.column_dimensions[col_letter].width = 18
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
        l = 6
        all_province_kill_request = 0
        final_quantity = 0
        fianl_wage = 0
        final_wage_all = []
        final_total_amount = 0
        if 'date1' in request.GET:
            for kill_house in kill_house_list:
                province_kill_request = ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                                           kill_request__recive_date__lte=date2,
                                                                           killhouse_user__key=kill_house['key'],
                                                                           state__in=('pending', 'accepted'),
                                                                           wage_pay=False, archive_by_province=True,
                                                                           return_to_province=False,
                                                                           trash=False).select_related(
                    'province_request').only('total_killed_quantity', 'province_request__key', 'main_quantity', 'wage',
                                             'total_amount').order_by(
                    '-kill_request__recive_date')
                all_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
                    'total_quantity', 0)
                all_wiegh = province_kill_request.aggregate(total_quantity=Sum('total_killed_weight')).get(
                    'total_quantity', 0)
                all_wage = []
                all_total_amount = 0
                all_province_kill_request += len(province_kill_request)
                final_quantity += all_quantity
                for province in province_kill_request:
                    wage = province.wage
                    if wage > 0:
                        all_wage.append(wage)
                    total_amount = (province.total_killed_weight * province.wage)
                    all_total_amount += total_amount
                final_total_amount += all_total_amount
                fianl_wage += all_wiegh

                if len(all_wage) > 0:
                    wage_all = sum(all_wage) / len(all_wage)
                    final_wage_all.append(wage_all)
                else:
                    wage_all = 0
                killer = 'کشتارگاه' if kill_house['killer'] == False else 'کشتارکن'
                values_list = [
                    killer + '(' + kill_house['name'] + ')',
                    kill_house['kill_house_operator__user__fullname'],
                    len(province_kill_request),
                    all_quantity,
                    all_wiegh,
                    wage_all,
                    all_total_amount,

                ]
                for item in range(len(values_list)):
                    cell = worksheet.cell(row=l, column=item + 3, value=values_list[item])
                    cell.alignment = Alignment(horizontal='center')
                    cell.font = Font(size=10, bold=True)
                    cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid")
                    value = values_list[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                l += 1
        else:
            for kill_house in kill_house_list:
                province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user__key=kill_house['key'],
                                                                           state__in=('pending', 'accepted'),
                                                                           wage_pay=False, archive_by_province=True,
                                                                           return_to_province=False,
                                                                           trash=False).select_related(
                    'province_request').only('total_killed_quantity', 'province_request__key', 'main_quantity',
                                             'wage',
                                             'total_amount').order_by(
                    '-kill_request__recive_date')
                all_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
                    'total_quantity', 0)
                all_wiegh = province_kill_request.aggregate(total_quantity=Sum('total_killed_weight')).get(
                    'total_quantity', 0)
                all_wage = []
                all_total_amount = 0
                all_province_kill_request += len(province_kill_request)
                final_quantity += all_quantity
                for province in province_kill_request:
                    wage = province.wage
                    if wage > 0:
                        all_wage.append(wage)
                    total_amount = (province.total_killed_weight * province.wage)
                    all_total_amount += total_amount
                final_total_amount += all_total_amount
                fianl_wage += all_wiegh

                if len(all_wage) > 0:
                    wage_all = sum(all_wage) / len(all_wage)
                    final_wage_all.append(wage_all)
                else:
                    wage_all = 0
                killer = 'کشتارگاه' if kill_house['killer'] == False else 'کشتارکن'
                values_list = [
                    killer + '(' + kill_house['name'] + ')',
                    kill_house['kill_house_operator__user__fullname'],
                    len(province_kill_request),
                    all_quantity,
                    all_wiegh,
                    wage_all,
                    all_total_amount,

                ]
                for item in range(len(values_list)):
                    cell = worksheet.cell(row=l, column=item + 3, value=values_list[item])
                    cell.alignment = Alignment(horizontal='center')
                    cell.font = Font(size=10, bold=True)
                    cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid")
                    value = values_list[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                l += 1

        if len(final_wage_all) > 0:
            wage = sum(final_wage_all) / len(final_wage_all)
        else:
            wage = 0
        values_list = [
            all_province_kill_request,
            final_quantity,
            fianl_wage,
            wage,
            final_total_amount

        ]
        for item in range(len(values_list)):
            cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10, bold=True)
            cell.fill = PatternFill(start_color="EEEAF2", fill_type="solid")
            value = values_list[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
    for kill_house in kill_house_list:
        sheet_name = kill_house['name']
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        if 'date1' in request.GET:
            province_kill_request = (
                ProvinceKillRequest.objects.filter(kill_request__recive_date__gte=date1,
                                                   kill_request__recive_date__lte=date2,
                                                   killhouse_user__key=kill_house['key'], wage_pay=False,
                                                   archive_by_province=True, return_to_province=False,
                                                   state__in=('pending', 'accepted'),
                                                   trash=False).select_related(
                    'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
                    .only('total_killed_quantity', 'province_request__key', 'kill_request__slaughter_house',
                          'kill_request__slaughter_house__name',
                          'main_quantity', 'wage', 'total_amount'
                          , 'total_killed_weight')
                    .values('total_killed_quantity', 'total_killed_weight', 'province_request__key',
                            'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                            'main_quantity', 'wage', 'total_amount', ).order_by(
                    '-kill_request__recive_date'))
        else:
            province_kill_request = (
                ProvinceKillRequest.objects.filter(killhouse_user__key=kill_house['key'], wage_pay=False,
                                                   archive_by_province=True, return_to_province=False,
                                                   state__in=('pending', 'accepted'),
                                                   trash=False).select_related(
                    'province_request__poultry_request', 'province_request__poultry_request__poultry', 'kill_request')
                    .only('total_killed_quantity', 'province_request__key', 'kill_request__slaughter_house',
                          'kill_request__slaughter_house__name',
                          'main_quantity', 'wage', 'total_amount'
                          , 'total_killed_weight')
                    .values('total_killed_quantity', 'total_killed_weight', 'province_request__key',
                            'kill_request__slaughter_house', 'kill_request__slaughter_house__name',
                            'main_quantity', 'wage', 'total_amount', ).order_by(
                    '-kill_request__recive_date'))
        all_quantity = province_kill_request.aggregate(total_quantity=Sum('total_killed_quantity')).get(
            'total_quantity', 0)
        all_wiegh = province_kill_request.aggregate(total_quantity=Sum('total_killed_weight')).get(
            'total_quantity', 0)
        all_wage = []

        all_total_amount = 0

        # برای بالای هدر
        header_list = [
            'تعداد سفارشات ',
            'مجموع تعداد(قطعه)',
            'مجموع وزن(کیلوگرم)',
            'میانگین کارمزد اتحادیه(ریال)',
            'مبلغ کل کارمزد(ریال)',

        ]
        for col_num, option in enumerate(header_list, 4):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=2, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = PatternFill(start_color="31869B", fill_type="solid")
            cell.font = Font(size=10, bold=True, color='FFFFFF')
            worksheet.row_dimensions[2].height = 36
            worksheet.column_dimensions[col_letter].width = 16

        l = 4
        m = 1
        for col_num, option in enumerate(excel_options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=5, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            worksheet.column_dimensions[col_letter].width = 20.01
            worksheet.row_dimensions[5].height = 27
            worksheet.freeze_panes = worksheet['A6']
            max_col = worksheet.max_column
            range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str

        for province in province_kill_request:

            province_request = ProvinceCheckOperatorRequest.objects.select_related(
                'poultry_request__poultry__user', 'poultry_request__poultry__address__city', 'poultry_request').filter(
                key=province['province_request__key'],
                trash=False).only('poultry_request__send_date', 'poultry_request__order_code',
                                  'poultry_request__poultry__user__fullname', 'poultry_request__poultry__user__mobile',
                                  'poultry_request__poultry__address__city__name', 'poultry_request__chicken_breed',
                                  'poultry_request__Index_weight').values('poultry_request__send_date',
                                                                          'poultry_request__order_code',
                                                                          'poultry_request__poultry__user__fullname',
                                                                          'poultry_request__poultry__user__mobile',
                                                                          'poultry_request__poultry__address__city__name',
                                                                          'poultry_request__chicken_breed',
                                                                          'poultry_request__Index_weight').first()
            kill_place = province['kill_request__slaughter_house__name'] if province[
                                                                                'kill_request__slaughter_house'] != None else \
                province['kill_request__slaughter_house__name']
            total_amount = (province['total_killed_weight'] * province['wage'])
            all_total_amount += total_amount
            send_date = jdatetime.date.fromgregorian(
                day=province_request['poultry_request__send_date'].day,
                month=province_request['poultry_request__send_date'].month,
                year=province_request['poultry_request__send_date'].year
            ) if province_request['poultry_request__send_date'] else '-'
            wieght = province['total_killed_weight']
            wage = province['wage']
            if wage > 0:
                all_wage.append(wage)
            list1 = [
                m,
                str(province_request['poultry_request__order_code']),
                province_request['poultry_request__poultry__user__fullname'],
                province_request['poultry_request__poultry__user__mobile'],
                province_request['poultry_request__poultry__address__city__name'],
                str(send_date),
                kill_place,
                province_request['poultry_request__chicken_breed'],
                province['total_killed_quantity'],
                wieght,
                province_request['poultry_request__Index_weight'],
                province['wage'],
                total_amount
            ]
            l += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10)
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
            m += 1
        if len(all_wage) > 0:
            wage_all = sum(all_wage) / len(all_wage)
        else:
            wage_all = 0
        values_list = [
            m - 1,
            all_quantity,
            all_wiegh,
            wage_all,
            all_total_amount,

        ]
        for item in range(len(values_list)):
            cell = worksheet.cell(row=3, column=item + 4, value=values_list[item])
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10)
            value = values_list[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            f'',
            '',
            '',
            '',
            all_quantity,
            all_wiegh,
            '',
            wage_all,
            all_total_amount,

        ]
        for item in range(len(list2)):
            cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
            value = list2[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values

            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(bold=True)
            cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="کارمزدهای معوقه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def process_for_each_hatching(request):
    hatching = PoultryHatching.objects.get(trash=False, key=request.GET['key'])
    name = hatching.poultry.unit_name
    province_name = hatching.poultry.address.province.name
    now = datetime.datetime.now().date()
    now_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(now_date.split("-"))
    separate = "-"
    date_now = separate.join(reversed_date)

    hatch_date = jdatetime.date.fromgregorian(
        day=hatching.date.day,
        month=hatching.date.month,
        year=hatching.date.year
    )
    quantity = hatching.quantity
    ninety_percent = (quantity * 90) / 100
    killed = 0

    poultry_requests = PoultryRequest.objects.filter(out_province_request_cancel=False, trash=False, hatching=hatching,
                                                     archive=False,
                                                     state_process__in=('accepted', 'pending')).order_by('id')
    all_quantity_of_request = poultry_requests.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)

    excel_options = [
        'ردیف',
        'کد سفارش',
        'تاریخ ثبت درخواست',
        'تاریخ کشتار',
        'سن کشتار',
        'نوع درخواست',
        'فروش',
        'تعداد درخواست کشتار',
        'میانگین وزنی درخواست',
        'وزن کل درخواست ',
        'ماهیت خریدار',
        'خریدار',
        'تلفن خریدار',
        'تعداد تخصیصی استان به خریدار(قطعه)',
        'وزن تخصیصی استان به خریدار',
        'مانده در سالن',
        ' تعداد بار',
        'تعداد بار قطعه',
        'وزن بار',
        'تعداد قطعه وارد شده در قرنطینه',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',
        'تعداد بار ورودی به انبار',
        'حجم لاشه ها',
        'وزن لاشه ها',
        'درصد افت بارها',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    red_font = Font(color="C00000", bold=True)
    sheet_list = [
        'مدیریت بارها',
        'بار های زنجیره'
    ]

    for name in sheet_list:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)

        if sheet_name == 'مدیریت بارها':
            header_list = [
                'نام واحد',
                'نام مالک',
                'تاریخ جوجه ریزی',
                'تعداد جوجه ریزی',
                'نود درصد جوجه ریزی',
                'تعداد نهایی قطعه کشتار شده',
                'وزن نهایی کشتار شده',
                'مجموع تلفات',
                'مانده در سالن',
                'متوسط سن کشتار',
                'تعداد ثبت سفارش',
                'تعداد درخواست کشتار (قطعه)',
                'مجموع تعداد کشتار خارج از استان',
                'مجموع وزن کشتار خارج از استان',
                'تعداد تخصیصی استان به خریدار(قطعه)',
                'وزن تخصیصی استان به خریدار(کیلوگرم)',
                'درصد کشتار نسبت به جوجه ریزی',
                'مجموع تخصیصی به ماشین(قطعه)',
                'مجموع وزن تخصیصی به ماشین(کیلوگرم)',
                'تعداد  تخلیه شده دامپزشک',
                'وزن  تخلیه شده دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'تعداد بار ورودی به انبار',
                'حجم لاشه ها',
                'وزن لاشه ها',
                'درصد افت بارها',
                'حجم زنجیره',
                'وزن زنجیره',

            ]
            # برای بالای هدر
            for col_num, option in enumerate(header_list, 2):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=3, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="31869B", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='FFFFFF')
                worksheet.row_dimensions[3].height = 36
                worksheet.column_dimensions[col_letter].width = 14

            worksheet['A5'] = 'جزئیات سفارشات'
            worksheet[
                'F1'] = f'گزارش پایش اطلاعاتی مرغداری {name} سامانه رصدیار استان {province_name} در تاریخ {date_now}'
            worksheet['C2'] = f'اطلاعات کلی'

            worksheet['F1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['C2'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A5'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'F1:K1'

            worksheet.merge_cells(merge_range1)
            worksheet['F1'].font = red_font

            create_header_freez(worksheet, excel_options, 1, 6, 7, height=36, width=15)

            l = 6

            final_left_over = []
            all_quantity_of_car = 0
            average_age_list = []
            all_percent = 0
            m = 1
            all_weight = []
            all_quantity_of_car_vet_state_accepted = 0
            request_weight = []
            all_request_weight = []
            all_free_sale_in_province_true = 0
            all_kill_province_request_poultry_request_Index_weight = []
            all_weight_of_car = 0
            all_weight_of_car_vet_state_accepted = 0
            all_main_quantity = 0
            sum_quantity_qarantineh = 0
            sum_all_quantity_vet_kill = 0
            sum_all_wight_vet_kill = 0
            sum_net_weight = 0
            sum_real_quantity_assigment = 0
            sum_accepted_real_quantity = 0
            sum_accepted_real_weight = 0
            all_free_sale_in_province_false = 0
            all_loses = 0
            all_province_quantity = 0
            for poultry_request in poultry_requests:
                all_loses += poultry_request.hatching.losses
                kill_request = ProvinceKillRequest.objects.filter(province_request__poultry_request=poultry_request,
                                                                  trash=False,
                                                                  state__in=('pending', 'accepted'),
                                                                  return_to_province=False).select_related(
                    'killhouse_user', 'province_request__poultry_request').order_by('-create_date')
                car_date = shamsi_date(poultry_request.send_date, in_value=True)

                create_date = shamsi_date(poultry_request.create_date, in_value=True)

                average_age = (poultry_request.send_date.date() - hatching.date.date()).days + 1
                average_age_list.append(average_age)

                if poultry_request.direct_buying == True:
                    type = 'خرید مستقیم'
                else:
                    type = 'اتحادیه'
                free_sale_in_province_false = 0
                Index_weight_sale_in_province_false = 0
                free_sale_in_province_true = 0

                all_province_quantity += poultry_request.quantity
                if poultry_request.out == True:
                    sale_type = 'خارج از استان'
                elif poultry_request.free_sale_in_province == False:
                    free_sale_in_province_false = poultry_request.quantity
                    all_free_sale_in_province_false += free_sale_in_province_false
                    Index_weight_sale_in_province_false = poultry_request.Index_weight
                    sale_type = 'دولتی'
                else:
                    sale_type = 'آزاد'
                    free_sale_in_province_true = poultry_request.quantity

                all_free_sale_in_province_true += free_sale_in_province_true

                all_request_weight.append(poultry_request.Index_weight * poultry_request.quantity)
                list1 = [
                    m,
                    str(poultry_request.order_code),
                    str(create_date),
                    str(car_date),
                    average_age,
                    type,
                    sale_type,
                    poultry_request.quantity,
                    poultry_request.Index_weight,
                    round(poultry_request.quantity * poultry_request.Index_weight, 2),

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    value = list1[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center', vertical='center')
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                    # worksheet.column_dimensions[get_column_letter(item + 1)].width = 17.01
                    worksheet.row_dimensions[l + 1].height = 21
                    if m % 2 == 0:
                        cell.fill = PatternFill(start_color="DAE1F6", fill_type="solid")
                # l += 1
                if kill_request.exists():
                    o = l + 1
                    if len(kill_request) > 1:
                        s = len(kill_request) - 1

                        for col in range(ord('A'), ord('J') + 1):
                            # rng = chr(col) + '7:{}'.format(r)
                            rng = f'{chr(col)}{o}:{chr(col)}{o + s}'
                            worksheet.merge_cells(rng)
                            worksheet[chr(col) + f'{o}'].alignment = Alignment(horizontal='center', vertical='center')
                    for kill in kill_request:

                        all_main_quantity += kill.main_quantity
                        state_s = ''
                        if kill.state == 'pending':
                            state_s = 'درانتظار تایید'
                        elif kill.state == 'accepted':
                            state_s = ' تایید شده'
                        quantity_of_car_vet_state_accepted = 0
                        weight_of_car_vet_state_accepted = 0
                        quantity_of_car = 0
                        weight_of_car = 0

                        kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                                              province_kill_request=kill).order_by(
                            'id').only('create_date', 'vet_state')
                        all_net_weight = 0
                        all_real_quantity_assigment = 0
                        if kill_house_requests:
                            for kill_house_request in kill_house_requests:
                                assignment = KillHouseAssignmentInformation.objects.filter(
                                    kill_house_request=kill_house_request, trash=False).only('net_weight',
                                                                                             'real_quantity').first()
                                if assignment:
                                    all_net_weight += assignment.net_weight if assignment.net_weight != None else 0
                                    all_real_quantity_assigment += assignment.real_quantity if assignment.real_quantity != None else 0
                                quantity_of_car += kill_house_request.quantity
                                all_quantity_of_car += kill_house_request.quantity
                                weight_of_car += int(
                                    kill_house_request.quantity * kill_house_request.province_request.poultry_request.Index_weight)

                                if kill_house_request.vet_state == 'accepted':
                                    quantity_of_car_vet_state_accepted += kill_house_request.quantity
                                    weight_of_car_vet_state_accepted += kill_house_request.accepted_real_weight
                                    all_quantity_of_car_vet_state_accepted += kill_house_request.quantity
                        killed += kill.main_quantity
                        all_quantity_qarantineh = kill_house_requests.aggregate(
                            total_quantity=Sum('quarantine_quantity')).get(
                            'total_quantity', 0)

                        all_quantity_vet_kill = kill_house_requests.aggregate(
                            total_quantity=Sum('vet_accepted_real_quantity')).get(
                            'total_quantity', 0)
                        all_weight_vet_kill = kill_house_requests.aggregate(
                            total_quantity=Sum('vet_accepted_real_weight')).get(
                            'total_quantity', 0)
                        all_accepted_real_quantity = kill.total_killed_quantity
                        all_accepted_real_weight = kill.total_killed_weight
                        sum_all_wight_vet_kill += all_weight_vet_kill if all_weight_vet_kill != None else 0
                        sum_all_quantity_vet_kill += all_quantity_vet_kill if all_quantity_vet_kill != None else 0
                        sum_quantity_qarantineh += all_quantity_qarantineh if all_quantity_qarantineh != None else 0
                        sum_accepted_real_quantity += all_accepted_real_quantity if all_accepted_real_quantity != None else 0
                        sum_accepted_real_weight += all_accepted_real_weight if all_accepted_real_weight != None else 0
                        left_over = (quantity - killed)
                        final_left_over.append(left_over)
                        percent_after_assigment = (quantity_of_car_vet_state_accepted * 100) / quantity
                        all_percent += percent_after_assigment

                        all_weight.append(kill.main_quantity * kill.province_request.poultry_request.Index_weight)
                        killer = 'کشتارکن' if kill.killhouse_user.killer == True else 'کشتارگاه'

                        request_weight.append(Index_weight_sale_in_province_false)
                        all_kill_province_request_poultry_request_Index_weight.append(
                            kill.province_request.poultry_request.Index_weight)
                        all_weight_of_car_vet_state_accepted += weight_of_car_vet_state_accepted
                        all_weight_of_car += weight_of_car

                        ware_house_bars = kill_house_requests.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
                        list1 = [
                            killer,
                            kill.killhouse_user.name,
                            kill.killhouse_user.kill_house_operator.user.mobile,
                            kill.main_quantity,
                            kill.province_request.poultry_request.Index_weight,
                            left_over,
                            len(kill_house_requests) if kill_house_requests else 0,
                            quantity_of_car,
                            weight_of_car,
                            all_quantity_qarantineh if all_quantity_qarantineh else '-',
                            all_quantity_vet_kill if all_quantity_vet_kill else '-',
                            all_weight_vet_kill if all_weight_vet_kill else '-',
                            all_real_quantity_assigment if all_real_quantity_assigment > 0 else '-',
                            all_net_weight if all_net_weight > 0 else '-',
                            kill.total_killed_quantity,
                            kill.total_killed_weight,
                            len(ware_house_bars),
                            ware_house_bars_quantity,
                            ware_house_bars_weight,
                            str(round(ware_house_bars_weight_lose / len(
                                ware_house_bars), 2) if ware_house_bars else 0)

                        ]
                        for item in range(len(list1)):
                            cell = worksheet.cell(row=l + 1, column=item + 11, value=list1[item])
                            value = list1[item]
                            # Check if the value is a number before formatting
                            if isinstance(value, (int, float)):
                                if value != 0:
                                    cell.number_format = '#,###'  # Apply general number format
                            else:
                                cell.value = value  # Keep as text for other values

                            cell.alignment = Alignment(horizontal='center', vertical='center')
                            cell.border = openpyxl.styles.Border(
                                left=openpyxl.styles.Side(style='thin'),
                                right=openpyxl.styles.Side(style='thin'),
                                top=openpyxl.styles.Side(style='thin'),
                                bottom=openpyxl.styles.Side(style='thin')
                            )
                            # worksheet.column_dimensions[get_column_letter(item + 11)].width = 17.01
                            # worksheet.column_dimensions[get_column_letter(item + 11)].height = 20.01
                            if m % 2 == 0:
                                cell.fill = PatternFill(start_color="DAE1F6", fill_type="solid")
                        l += 1

                        sum_net_weight += all_net_weight
                        sum_real_quantity_assigment += all_real_quantity_assigment
                else:
                    if poultry_request.out == True:
                        left_over = (quantity - killed)
                        list1 = [
                            'خارج از استان',
                            poultry_request.buyer_fullname,
                            poultry_request.buyer_mobile,
                            poultry_request.quantity,
                            int(poultry_request.Index_weight),
                            left_over,
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            poultry_request.quantity,
                            int(poultry_request.quantity * poultry_request.Index_weight),
                            '-',
                            '-',
                            '-',
                            '-',

                        ]
                        for item in range(len(list1)):
                            cell = worksheet.cell(row=l + 1, column=item + 11, value=list1[item])
                            value = list1[item]
                            # Check if the value is a number before formatting
                            if isinstance(value, (int, float)):
                                if value != 0:
                                    cell.number_format = '#,###'  # Apply general number format
                            else:
                                cell.value = value  # Keep as text for other values

                            cell.alignment = Alignment(horizontal='center', vertical='center')
                            cell.border = openpyxl.styles.Border(
                                left=openpyxl.styles.Side(style='thin'),
                                right=openpyxl.styles.Side(style='thin'),
                                top=openpyxl.styles.Side(style='thin'),
                                bottom=openpyxl.styles.Side(style='thin')
                            )
                            # worksheet.column_dimensions[get_column_letter(item + 11)].width = 17.01
                            # worksheet.column_dimensions[get_column_letter(item + 11)].height = 20.01

                            if m % 2 == 0:
                                cell.fill = PatternFill(start_color="DAE1F6", fill_type="solid")
                        sum_accepted_real_weight += int(poultry_request.quantity * poultry_request.Index_weight)
                        sum_accepted_real_quantity += poultry_request.quantity
                    else:
                        list1 = [
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',
                            '-',

                        ]
                        for item in range(len(list1)):
                            cell = worksheet.cell(row=l + 1, column=item + 11, value=list1[item])
                            value = list1[item]
                            # Check if the value is a number before formatting
                            if isinstance(value, (int, float)):
                                if value != 0:
                                    cell.number_format = '#,###'  # Apply general number format
                            else:
                                cell.value = value  # Keep as text for other values

                            cell.alignment = Alignment(horizontal='center', vertical='center')
                            cell.border = openpyxl.styles.Border(
                                left=openpyxl.styles.Side(style='thin'),
                                right=openpyxl.styles.Side(style='thin'),
                                top=openpyxl.styles.Side(style='thin'),
                                bottom=openpyxl.styles.Side(style='thin')
                            )
                            # worksheet.column_dimensions[get_column_letter(item + 11)].width = 17.01
                            # worksheet.column_dimensions[get_column_letter(item + 11)].height = 20.01

                            if m % 2 == 0:
                                cell.fill = PatternFill(start_color="DAE1F6", fill_type="solid")
                    l += 1

            try:
                avrage_age1 = round((sum(average_age_list) / len(average_age_list)))
                rw = round(sum(request_weight) / len(request_weight))
                dd = round(sum(all_kill_province_request_poultry_request_Index_weight) / len(
                    all_kill_province_request_poultry_request_Index_weight))
            except:
                avrage_age1 = 0
                rw = 0
                dd = 0
            kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                                  province_request__poultry_request__in=poultry_requests)
            ware_house_bars = kill_house_requests.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
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                f'',
                '',
                '',
                int(all_province_quantity),
                '',
                int(sum(all_request_weight)),
                # int(all_free_sale_in_province_true),
                '',
                '',
                '',
                int(all_main_quantity),
                int(dd),
                f'',
                '',

                int(all_quantity_of_car),
                int(all_weight_of_car),
                int(sum_quantity_qarantineh),
                int(sum_all_quantity_vet_kill),
                int(sum_all_wight_vet_kill),
                int(sum_real_quantity_assigment),
                int(sum_net_weight),
                int(sum_accepted_real_quantity),
                int(sum_accepted_real_weight),
                len(ware_house_bars),
                ware_house_bars_quantity,
                ware_house_bars_weight,
                str(round(ware_house_bars_weight_lose / len(
                    ware_house_bars), 2) if ware_house_bars else 0),

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
            try:
                all_car = round((all_quantity_of_car * 100) / hatching.killed_quantity)
            except:
                all_car = 0
            try:
                all_car_vet = round((all_quantity_of_car_vet_state_accepted * 100) / all_quantity_of_car)
            except:
                all_car_vet = 0

            value_header_list = [
                hatching.poultry.unit_name,
                hatching.poultry.user.fullname,
                str(hatch_date),
                quantity,
                ninety_percent,
                sum_accepted_real_quantity,
                sum_accepted_real_weight,
                all_loses,
                hatching.left_over,
                avrage_age1,
                len(poultry_requests),
                all_quantity_of_request,
                hatching.out_province_killed_quantity,
                hatching.out_province_killed_weight,
                all_main_quantity,
                sum(all_weight),
                round((hatching.killed_quantity * 100) / quantity),
                all_quantity_of_car,
                all_weight_of_car,
                sum_all_quantity_vet_kill,
                sum_all_wight_vet_kill,
                sum_real_quantity_assigment,
                sum_net_weight,
                len(ware_house_bars),
                ware_house_bars_quantity,
                ware_house_bars_weight,
                str(round(ware_house_bars_weight_lose / len(
                    ware_house_bars), 2) if ware_house_bars else 0),
                hatching.chain_killed_quantity,
                hatching.chain_killed_weight,
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=4, column=item + 2, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
        else:
            filterset_class = ChainAllocationFilterSet
            filterset_fields = [
                'poultry_hatching__poultry__breeding_unique_id',
                'poultry_hatching__poultry__user__mobile',
                'poultry_hatching__poultry__user__fullname',
                'poultry_hatching__poultry__user__first_name',
                'poultry_hatching__poultry__user__last_name',
                'poultry_hatching__poultry__unit_name',
                'chain_company__name',

            ]
            chain_allocations = ChainAllocation.objects.filter(state='accepted',poultry_hatching=hatching
                                                               ).order_by('id')

            state1 = 'تایید شده'

            if 'search' in request.GET:
                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=chain_allocations
                            )
                            ).filter():
                                ps = filterset_class(data=query, queryset=chain_allocations)
                                chain_allocations = ps.filter()

            excel_options = [
                'ردیف',
                'وضعیت',
                ' تاریخ سفارش',
                'نوع فروش',
                'ثبت کننده سفارش',
                'تلفن ثبت کننده سفارش',
                'خریدار',
                'تلفن خریدار',
                'مرغداری',
                'تلفن مرغداری',
                'شرکت زنجیره',
                ' تلفن شرکت زنجیره',
                'کد بهداشتی',
                'کد قرنطینه',
                'راننده ',
                'تلفن راننده ',
                'خودرو',
                'پلاک',
                'حجم',
                'میانگین وزن',
                'وزن',
                'حذف/رد کننده',
                'تلفن حذف/رد کننده',
            ]




            blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
            cell = worksheet.cell(row=1, column=1)
            cell.alignment = Alignment(horizontal='center', vertical='center')
            red_font = Font(color="C00000", bold=True)
            if state1 == 'تایید شده':
                for col_num, option in enumerate(excel_options[:21], 1):
                    col_letter = get_column_letter(col_num)
                    cell = worksheet.cell(row=6, column=col_num, value=option)
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.fill = blue_fill
                    cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                    if len(option) > worksheet.column_dimensions[col_letter].width:
                        worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            else:
                for col_num, option in enumerate(excel_options, 1):
                    col_letter = get_column_letter(col_num)
                    cell = worksheet.cell(row=6, column=col_num, value=option)
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.fill = blue_fill
                    cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                    if len(option) > worksheet.column_dimensions[col_letter].width:
                        worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارها',
                'مجموع تعداد قطعه بارها',
                'مجموع وزن بارها',
                'کمترین سن مرغ',
                'بیشترین سن مرغ',
                'تعداد بارهای دارای کد قرنطینه',

            ]
            for col_num, option in enumerate(header_list, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8

            worksheet['B1'] = f'گزارش بارهای {state1} شرکت زنجیره'
            if chain_allocations.exists():
                name = chain_allocations.first().poultry_hatching.poultry.user.province.name
                worksheet['B2'] = f'استان {name}'


            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

            l = 6
            m = 1

            all_age = []

            all_quantity = chain_allocations.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            all_weighte = chain_allocations.aggregate(
                total=Sum('weight'))[
                              'total'] or 0
            has_code = 0
            if chain_allocations:
                for chain_allocation in chain_allocations:
                    age = (chain_allocation.poultry_hatching.chicken_age)
                    all_age.append(age)
                    chain_date = jdatetime.date.fromgregorian(
                        day=chain_allocation.date.day,
                        month=chain_allocation.date.month,
                        year=chain_allocation.date.year
                    )

                    if chain_allocation.quarantine_code:
                        has_code += 1

                    remover_fullname = '-'
                    remover_mobile = '-'
                    if chain_allocation.state == 'accepted':
                        state = 'تایید شده'
                    elif chain_allocation.state == 'rejected':
                        state = 'رد شده'
                        remover_fullname = chain_allocation.seconder['fullname'] if chain_allocation.seconder else None
                        remover_mobile = chain_allocation.seconder['mobile'] if chain_allocation.seconder else None
                    elif chain_allocation.state == 'pending':
                        state = 'در انتظار تایید'
                    else:
                        state = 'حذف شده'
                        remover_fullname = chain_allocation.remover['fullname'] if chain_allocation.remover else None
                        remover_mobile = chain_allocation.remover['mobile'] if chain_allocation.remover else None
                    out_province = 'خارج استان' if chain_allocation.out_province == True else 'داخل استان'

                    full_name_registerer = chain_allocation.registerer[
                        'fullname'] if chain_allocation.registerer else '-'
                    mobile_registerer = chain_allocation.registerer['mobile'] if chain_allocation.registerer else '-'

                    if chain_allocation.kill_house is not None:
                        buyer_fullname = chain_allocation.kill_house.name
                        buyer_mobile = chain_allocation.kill_house.kill_house_operator.user.mobile
                    else:
                        buyer_fullname = chain_allocation.buyer_name
                        buyer_mobile = chain_allocation.buyer_mobile

                    list1 = [
                        m,
                        state,
                        str(chain_date),
                        out_province,
                        full_name_registerer,
                        mobile_registerer,
                        buyer_fullname,
                        buyer_mobile,
                        chain_allocation.poultry_hatching.poultry.unit_name,
                        chain_allocation.poultry_hatching.poultry.user.mobile,
                        chain_allocation.company_name,
                        chain_allocation.company_user_mobile,
                        chain_allocation.health_code if chain_allocation.health_code else '-',
                        chain_allocation.quarantine_code if chain_allocation.quarantine_code else '-',
                        chain_allocation.driver_name if chain_allocation.driver_name else '-',
                        chain_allocation.driver_mobile if chain_allocation.driver_mobile else '-',
                        chain_allocation.type_car if chain_allocation.type_car else '-',
                        chain_allocation.pelak if chain_allocation.pelak else '-',
                        chain_allocation.quantity,
                        chain_allocation.index_weight,
                        chain_allocation.weight,
                        remover_fullname,
                        remover_mobile,
                    ]
                    m += 1
                    if state1 == 'تایید شده':
                        for item in range(len(list1) - 2):
                            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                            value = list1[item]
                            # Check if the value is a number before formatting
                            if isinstance(value, (int, float)):
                                if value != 0:
                                    cell.number_format = '#,###'  # Apply general number format
                            else:
                                cell.value = value  # Keep as text for other values

                            worksheet.row_dimensions[l + 1].height = 20
                            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    else:
                        for item in range(len(list1)):
                            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                            value = list1[item]
                            # Check if the value is a number before formatting
                            if isinstance(value, (int, float)):
                                if value != 0:
                                    cell.number_format = '#,###'  # Apply general number format
                            else:
                                cell.value = value  # Keep as text for other values

                            worksheet.row_dimensions[l + 1].height = 20
                            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    l += 1

            # last_age=sorted(reversed(all_age))
            all_age = sorted(all_age)
            value_header_list2 = [
                len(chain_allocations),
                all_quantity,
                all_weighte,
                all_age[0] if len(all_age) > 0 else None,
                all_age[len(all_age) - 1] if len(all_age) > 0 else None,
                has_code,

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_quantity,
                '',
                all_weighte,
                '',
                '',

            ]
            if state1 == 'تایید شده':
                for item in range(len(list2) - 2):
                    cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                    value = list2[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center')
                    cell.font = Font(size=10, bold=True)
                    cell.font = Font(bold=True)
                    cell.fill = PatternFill(start_color="00B050", fill_type="solid")
            else:
                for item in range(len(list2)):
                    cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                    value = list2[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center')
                    cell.font = Font(size=10, bold=True)
                    cell.font = Font(bold=True)
                    cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="پایش اطلاعاتی مرغدار {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def process_for_all_hatching(request):
    hatchings = PoultryHatching.objects.filter(trash=False, allow_hatching='pending', archive=False)
    name = hatchings.first().poultry.unit_name
    province_name = hatchings.first().poultry.address.province.name
    now = datetime.datetime.now().date()
    now_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(now_date.split("-"))
    separate = "-"
    date_now = separate.join(reversed_date)

    excel_options = [
        'نام واحد',
        'نام مالک',
        'تاریخ جوجه ریزی',
        'تعداد جوجه ریزی',
        'نود درصد جوجه ریزی',
        'مانده در سالن',
        'متوسط سن کشتار',
        'تعداد ثبت سفارش',
        'تعداد درخواست کشتار (قطعه)',
        'تعداد تخصیصی استان به خریدار(قطعه)',
        'وزن تخصیصی استان به خریدار(کیلوگرم)',
        'درصد کشتار نسبت به نود درصد',
        'مجموع تخصیصی به ماشین(قطعه)',
        'درصد تخصیصی به ماشین نسبت به تخصیص استان به خریدار',
        'درصد تخلیه شده نسبت به تخصیص به ماشین',
        'تعداد تخلیه شده در کشتارگاه',
        'کد سفارش',
        'تاریخ کشتار',
        'سن کشتار',
        'نوع درخواست',
        'فروش',
        'تعداد درخواست کشتار دولتی',
        'میانگین وزنی درخواست',
        'وزن کل درخواست ',
        'تعداد درخواست کشتار آزاد',
        'تعداد تخصیصی استان به خریدار(قطعه)',
        'وزن تخصیصی استان به خریدار',
        'مانده در سالن',
        'ماهیت خریدار',
        'خریدار',
        'تخصیصی خریدار به ماشین',
        'وزن تخصیصی خریدار به ماشین',
        'تلفات غیرعادی گله',
        'تعداد تخلیه شده در کشتار گاه',
        'وزن تخلیه شده در کشتارگاه',
        'درصد  تخلیه شده به تخصیص به ماشین',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    red_font = Font(color="C00000", bold=True)

    worksheet['F1'] = f'گزارش پایش اطلاعاتی مرغداری {name} سامانه رصدیار استان {province_name} در تاریخ {date_now}'
    worksheet['A2'] = f'اطلاعات کلی'

    worksheet['F1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['C2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'F1:K1'

    worksheet.merge_cells(merge_range1)
    worksheet['F1'].font = red_font

    # برای کل
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=3, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')

        worksheet.column_dimensions[col_letter].width = 14

        worksheet.row_dimensions[3].height = 36

        worksheet.freeze_panes = worksheet['A4']
        max_col = worksheet.max_column
        range_str = f'A3:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    final_left_over = []
    all_quantity_of_car = 0
    all_percent = 0
    all_weight = []
    all_quantity_of_car_vet_state_accepted = 0
    request_weight = []
    average_age_list = []
    all_request_weight = []
    all_free_sale_in_province_true = 0
    all_kill_province_request_poultry_request_Index_weight = []
    all_weight_of_car = 0
    all_weight_of_car_vet_state_accepted = 0
    for hatching in hatchings:
        l = 2

        hatch_date = jdatetime.date.fromgregorian(
            day=hatching.date.day,
            month=hatching.date.month,
            year=hatching.date.year
        )
        quantity = hatching.quantity
        ninety_percent = (quantity * 90) / 100
        killed = 0

        poultry_requests = PoultryRequest.objects.filter(trash=False, hatching=hatching, archive=False).order_by('-id')
        all_quantity_of_request = poultry_requests.aggregate(total_quantity=Sum('quantity')).get(
            'total_quantity', 0)
        for poultry_request in poultry_requests:

            kill_request = ProvinceKillRequest.objects.filter(province_request__poultry_request=poultry_request,
                                                              trash=False).select_related(
                'killhouse_user', 'province_request__poultry_request').order_by('-create_date')

            car_date = jdatetime.date.fromgregorian(
                day=poultry_request.send_date.day,
                month=poultry_request.send_date.month,
                year=poultry_request.send_date.year
            )
            average_age = (poultry_request.send_date.date() - hatching.date.date()).days + 1
            average_age_list.append(average_age)
            if poultry_request.union == True:
                type = 'خارج از استان'
            elif poultry_request.direct_buying == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            free_sale_in_province_false = 0
            Index_weight_sale_in_province_false = 0
            free_sale_in_province_true = 0

            if poultry_request.free_sale_in_province == False:
                free_sale_in_province_false = poultry_request.quantity
                Index_weight_sale_in_province_false = poultry_request.Index_weight
                sale_type = 'دولتی'
            else:
                free_sale_in_province_true = poultry_request.quantity
                sale_type = 'آزاد'

            all_free_sale_in_province_true += free_sale_in_province_true

            all_request_weight.append(Index_weight_sale_in_province_false * free_sale_in_province_false)
            try:
                avrage_age1 = round((sum(average_age_list) / len(average_age_list)))
                rw = round(sum(request_weight) / len(request_weight))
                dd = round(sum(all_kill_province_request_poultry_request_Index_weight) / len(
                    all_kill_province_request_poultry_request_Index_weight))
            except:
                avrage_age1 = 0
                rw = 0
                dd = 0
            try:
                all_car = round((all_quantity_of_car * 100) / hatching.killed_quantity)
            except:
                all_car = 0
            try:
                all_car_vet = round((all_quantity_of_car_vet_state_accepted * 100) / all_quantity_of_car)
            except:
                all_car_vet = 0

            if kill_request:
                for kill in kill_request:
                    quantity_of_car_vet_state_accepted = 0
                    weight_of_car_vet_state_accepted = 0
                    quantity_of_car = 0
                    weight_of_car = 0

                    kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                                          province_kill_request=kill).order_by(
                        'id').only('create_date', 'vet_state')
                    if kill_house_requests:

                        for kill_house_request in kill_house_requests:
                            quantity_of_car += kill_house_request.quantity
                            all_quantity_of_car += kill_house_request.quantity
                            weight_of_car += kill_house_request.accepted_real_weight

                            if kill_house_request.vet_state == 'accepted':
                                quantity_of_car_vet_state_accepted += kill_house_request.quantity
                                weight_of_car_vet_state_accepted += kill_house_request.accepted_real_weight
                                all_quantity_of_car_vet_state_accepted += kill_house_request.quantity
                    killed += kill.main_quantity

                    left_over = (quantity - killed)
                    final_left_over.append(left_over)
                    percent_after_assigment = (quantity_of_car_vet_state_accepted * 100) / quantity
                    all_percent += percent_after_assigment

                    all_weight.append(kill.main_quantity * kill.province_request.poultry_request.Index_weight)
                    killer = 'کشتارکن' if kill.killhouse_user.killer == True else 'کشتارگاه'

                    request_weight.append(Index_weight_sale_in_province_false)
                    all_kill_province_request_poultry_request_Index_weight.append(
                        kill.province_request.poultry_request.Index_weight)
                    all_weight_of_car_vet_state_accepted += weight_of_car_vet_state_accepted
                    all_weight_of_car += weight_of_car
                    list1 = [
                        hatching.poultry.unit_name,
                        hatching.poultry.user.fullname,
                        str(hatch_date),
                        quantity,
                        ninety_percent,
                        hatching.left_over,
                        avrage_age1,
                        len(poultry_requests),
                        all_quantity_of_request,
                        hatching.killed_quantity,
                        sum(all_weight),
                        round((hatching.killed_quantity * 100) / ninety_percent),
                        all_quantity_of_car,
                        all_car,
                        all_car_vet,
                        all_quantity_of_car_vet_state_accepted,
                        poultry_request.order_code,
                        str(car_date),
                        average_age,
                        type,
                        sale_type,
                        free_sale_in_province_false,
                        Index_weight_sale_in_province_false,
                        round(free_sale_in_province_false * Index_weight_sale_in_province_false, 2),
                        free_sale_in_province_true,
                        kill.main_quantity,
                        kill.province_request.poultry_request.Index_weight,
                        left_over,
                        killer,
                        kill.killhouse_user.name,
                        quantity_of_car,
                        weight_of_car,
                        '0',
                        quantity_of_car_vet_state_accepted,
                        weight_of_car_vet_state_accepted,
                        round(percent_after_assigment),

                    ]
                    l += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

            else:
                list1 = [
                    hatching.poultry.unit_name,
                    hatching.poultry.user.fullname,
                    str(hatch_date),
                    quantity,
                    ninety_percent,
                    hatching.left_over,
                    avrage_age1,
                    len(poultry_requests),
                    all_quantity_of_request,
                    hatching.killed_quantity,
                    sum(all_weight),
                    round((hatching.killed_quantity * 100) / ninety_percent),
                    all_quantity_of_car,
                    all_car,
                    all_car_vet,
                    all_quantity_of_car_vet_state_accepted,
                    poultry_request.order_code,
                    str(car_date),
                    average_age,
                    type,
                    sale_type,
                    free_sale_in_province_false,
                    Index_weight_sale_in_province_false,
                    round(free_sale_in_province_false * Index_weight_sale_in_province_false, 2),
                    free_sale_in_province_true,
                    '-',
                    '-',
                    '-',
                    '-',
                    '-',
                    '-',
                    '-',
                    '0',
                    '-',
                    '-',
                    '-',

                ]
                l += 1

                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')
        r = l + 1

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="پایش اطلاعاتی مرغدار {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def bar_management_kill_house_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    user = SystemUserProfile.objects.get(key=request.GET['key'])
    try:
        operator = KillHouseOperator.objects.get(user=user, trash=False)
        kill_house = KillHouse.objects.filter(trash=False, kill_house_operator=operator)
    except:
        kill_house = KillHouse.objects.filter(trash=False)
    kill_house_assignments_list = KillHouseAssignmentInformation.objects.filter(
        kill_house_request__killhouse_user__in=kill_house,
        trash=False,
        unusual_casualties=False,
        kill_house_request__kill_request__recive_date__date__gte=date1,
        kill_house_request__kill_request__recive_date__date__lte=date2)

    excel_options = [
        'ردیف',
        'کد بار',
        'کد سفارش',
        'خریدار',
        'کشتارکن اختصاصی',
        'تلفن کشتارکن اختصاصی',
        'راننده',
        'موبایل راننده',
        'ماشین',
        'پلاک',
        'تاریخ کشتار',
        'مرغدار',
        'تلفن مرغدار',
        'شهر',
        'استان',
        'تعداد تخصیصی بار(قطعه)',
        'وزن(کیلوگرم)',
        'وزن کل(کیلوگرم)',
        'تعداد واقعی تحویلی(قطعه)',
        'وزن واقعی تحویلی(کیلوگرم)',
        'وزن وارد شده ماشین بدون بار باسکول(کیلوگرم)',
        'وزن وارد شده ماشین با بار باسکول(کیلوگرم)',
        'وزن بدست آمده از بار باسکول(کیلوگرم)',
        'لاشه استحصالی(قطعه)',
        'وضعیت بار',

    ]

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    header_list = [
        'تعداد بارهای دارای کشتارکن اختصاصی',
        'مجموع تعداد تخصیصی',
        'مجموع تعداد واقعی تحویلی',
        'مجموع وزن واقعی تحویلی',
    ]
    # برای بالای هدر
    for col_num, option in enumerate(header_list, 4):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 17

    worksheet['A1'] = f' مدیریت بارهای تکمیل شده '
    worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[4].height = 28
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 3
    m = 1
    kill_kill_house_request_quantity_all = 0
    kill_kill_house_request_accepted_real_quantity_all = 0
    kill_kill_house_request_accepted_real_weight_all = 0
    killer_exclusive = 0
    for kill in kill_house_assignments_list:
        kill_kill_house_request_quantity_all += kill.kill_house_request.quantity
        kill_kill_house_request_accepted_real_quantity_all += kill.kill_house_request.accepted_real_quantity
        kill_kill_house_request_accepted_real_weight_all += kill.kill_house_request.accepted_real_weight

        kill_date = jdatetime.date.fromgregorian(
            year=kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.send_date.year,
            month=kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.send_date.month,
            day=kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.send_date.day
        )
        final_state = 'در انتظار تایید' if kill.state == 'pending' else 'تایید شده'
        name_killer_exclusive = '-'
        mobile_killer_exclusive = '-'
        if kill.kill_house_request.killer != None:
            name_killer_exclusive = kill.kill_house_request.killer.name
            mobile_killer_exclusive = str(kill.kill_house_request.killhouse_user.kill_house_operator.user.mobile)
            killer_exclusive += 1
        list1 = [
            m,
            str(kill.kill_house_request.bar_code),
            str(kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.order_code),
            kill.kill_house_request.killhouse_user.name,
            name_killer_exclusive,
            mobile_killer_exclusive,
            kill.kill_house_request.add_car.driver.driver_name,
            kill.kill_house_request.add_car.driver.driver_mobile,
            kill.kill_house_request.add_car.driver.type_car,
            kill.kill_house_request.add_car.driver.pelak,
            str(kill_date),
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.poultry.user.fullname,
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.poultry.user.mobile,
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.poultry.user.city.name,
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.poultry.user.province.name,
            kill.kill_house_request.quantity,
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.Index_weight,
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.Index_weight * kill.kill_house_request.quantity,
            kill.kill_house_request.accepted_real_quantity,
            kill.kill_house_request.accepted_real_weight,
            kill.car_weight_without_load,
            kill.car_weight_with_load,
            kill.net_weight,
            kill.kill_house_request.province_kill_request.province_request.city_request_Poultry.poultry_request.hatching.losses,
            final_state,
        ]
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            value = list1[item]
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'
            else:
                cell.value = value
        m += 1

    value_header_list = [
        killer_exclusive,
        kill_kill_house_request_quantity_all,
        kill_kill_house_request_accepted_real_quantity_all,
        kill_kill_house_request_accepted_real_weight_all

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=value_header_list[item])
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.font = Font(size=10, bold=True)
        value = value_header_list[item]
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'
        else:
            cell.value = value

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تکمیل شده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def all_inventory_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(request.GET['date1'],
                                       '%Y-%m-%d').date() if 'date1' in request.GET else now
    date2 = datetime.datetime.strptime(request.GET['date2'],
                                       '%Y-%m-%d').date() if 'date2' in request.GET else now
    names_list = ['اطلاعات کلی']

    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)
    for kill in kill_house_ware_houses:
        if kill.kill_house.name not in names_list:
            names_list.append(kill.kill_house.name)
    # names_list= kill_house_ware_houses.values('kill_house__name')
    # print(names_list)

    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']
    abc_list = ['A', 'B', 'C', 'D', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S', 'T']

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    now_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(now_date.split("-"))
    separate = "-"
    now_date_1 = separate.join(reversed_date)
    kill_houses = KillHouse.objects.filter(
        pk__in=kill_house_ware_houses.values('kill_house')
    )

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    for name in names_list:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

        if sheet_name == 'اطلاعات کلی':
            worksheet.row_dimensions[2].height = 24
            worksheet.row_dimensions[3].height = 30
            worksheet.row_dimensions[5].height = 19.04
            worksheet.row_dimensions[8].height = 32

            worksheet['A2'] = f'این گزارش در مورخ {now_date_1} صادر شده است.'
            worksheet['G2'] = f'اطلاعات کلی توزیع و پخش مرغ گرم از تاریخ {from_date_1} تا {to_date_1}'

            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['G2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range122 = 'A2:D2'
            merge_range123 = 'G2:N2'
            worksheet.merge_cells(merge_range122)
            worksheet.merge_cells(merge_range123)

            worksheet['G2'].font = Font(size=12, color='FF0000')

            for abc in abc_list:
                worksheet[f'{abc}8'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            for abc in abc_list[1:]:
                worksheet[f'{abc}3'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            withe_font = Font(size=10, color='D9FFFFFF')
            blue = PatternFill(start_color="4472C4", fill_type="solid")
            green = PatternFill(start_color="00B050", fill_type="solid")
            worksheet['B3'] = f'تعداد خریداران'
            worksheet['C3'] = f'ورودی از سردخانه'
            worksheet['E3'] = f'پیش سرد'
            worksheet['G3'] = f'خرید خارج از استان'
            worksheet['I3'] = f'بارهای روزانه'
            worksheet['K3'] = f'جمع کل انبار'
            worksheet['M3'] = f'توزیع شده'
            worksheet['O3'] = f'توزیع / تحویل شده'
            worksheet['Q3'] = f'مانده انبار'
            worksheet['S3'] = f'تعداد مباشر تخصیص داده شده'
            worksheet['T3'] = f'تعداد صنف تخصیص داده شده'

            worksheet['C3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['I3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['K3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['M3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['O3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['Q3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['S3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['T3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            merge_range1 = 'C3:D4'
            merge_range2 = 'E3:F4'
            merge_range3 = 'G3:H4'
            merge_range4 = 'I3:J4'
            merge_range5 = 'K3:L4'
            merge_range6 = 'M3:N4'
            merge_range7 = 'O3:P4'
            merge_range8 = 'Q3:R4'
            merge_range9 = 'B3:B5'
            merge_range10 = 'S3:S5'
            merge_range11 = 'T3:T5'

            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)
            worksheet.merge_cells(merge_range10)
            worksheet.merge_cells(merge_range11)

            worksheet['C3'].font = withe_font
            worksheet['B3'].font = withe_font
            worksheet['E3'].font = withe_font
            worksheet['G3'].font = withe_font
            worksheet['I3'].font = withe_font
            worksheet['K3'].font = withe_font
            worksheet['M3'].font = withe_font
            worksheet['O3'].font = withe_font
            worksheet['Q3'].font = withe_font
            worksheet['S3'].font = withe_font
            worksheet['T3'].font = withe_font

            worksheet['B3'].fill = blue
            worksheet['C3'].fill = blue
            worksheet['E3'].fill = blue
            worksheet['G3'].fill = blue
            worksheet['I3'].fill = blue
            worksheet['K3'].fill = blue
            worksheet['M3'].fill = blue
            worksheet['O3'].fill = blue
            worksheet['Q3'].fill = blue
            worksheet['S3'].fill = blue
            worksheet['T3'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

            for item in range(len(list1)):
                cell = worksheet.cell(row=5, column=item + 3, value=list1[item])
                worksheet.row_dimensions[5].height = 19

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            worksheet['A8'] = f'ردیف'
            worksheet['B8'] = f'خریدار'
            worksheet['C8'] = f'شهرستان'
            worksheet['D8'] = f'تعداد مباشر/صنف تخصیصی'
            worksheet['E8'] = f'ورودی از سردخانه'
            worksheet['G8'] = f'پیش سرد'
            worksheet['I8'] = f'خرید خارج از استان'
            worksheet['K8'] = f'بارهای روزانه'
            worksheet['M8'] = f'جمع کل انبار'
            worksheet['O8'] = f'توزیع شده'
            worksheet['Q8'] = f'توزیع / تحویل شده'
            worksheet['S8'] = f'مانده انبار'

            worksheet['A8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['C8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['D8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['E8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['G8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['I8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['K8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['M8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['O8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['Q8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['S8'].alignment = Alignment(horizontal='center', vertical='center')

            merge_range11 = 'A8:A10'
            merge_range12 = 'B8:B10'
            merge_range13 = 'C8:C10'
            merge_range14 = 'D8:D10'
            merge_range1 = 'E8:F9'
            merge_range2 = 'G8:H9'
            merge_range3 = 'I8:J9'
            merge_range4 = 'K8:L9'
            merge_range5 = 'M8:N9'
            merge_range6 = 'O8:P9'
            merge_range7 = 'Q8:R9'
            merge_range8 = 'S8:T9'

            worksheet.merge_cells(merge_range11)
            worksheet.merge_cells(merge_range12)
            worksheet.merge_cells(merge_range13)
            worksheet.merge_cells(merge_range14)
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)

            worksheet['A8'].font = withe_font
            worksheet['B8'].font = withe_font
            worksheet['C8'].font = withe_font
            worksheet['D8'].font = withe_font
            worksheet['E8'].font = withe_font
            worksheet['G8'].font = withe_font
            worksheet['I8'].font = withe_font
            worksheet['K8'].font = withe_font
            worksheet['M8'].font = withe_font
            worksheet['O8'].font = withe_font
            worksheet['Q8'].font = withe_font
            worksheet['S8'].font = withe_font

            worksheet['A8'].fill = green
            worksheet['B8'].fill = green
            worksheet['C8'].fill = green
            worksheet['D8'].fill = green
            worksheet['E8'].fill = blue
            worksheet['G8'].fill = blue
            worksheet['I8'].fill = blue
            worksheet['K8'].fill = blue
            worksheet['M8'].fill = blue
            worksheet['O8'].fill = blue
            worksheet['Q8'].fill = blue
            worksheet['S8'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']
            for item in range(len(list1)):
                cell = worksheet.cell(row=10, column=item + 5, value=list1[item])
                worksheet.row_dimensions[5].height = 28

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            head_list1 = [len(names_list) - 1
                , 0,
                          0,
                          total_pre_cold_quantity if total_pre_cold_quantity != None else 0,
                          total_pre_cold_weight if total_pre_cold_weight != None else 0,
                          total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                          total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                          total_number_of_carcasses if total_number_of_carcasses != None else 0,
                          total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                          final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                          final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                          total_allocated_quantity if total_allocated_quantity != None else 0,
                          total_allocated_weight if total_allocated_weight != None else 0,
                          total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                          total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                          total_remain_quantity if total_remain_quantity != None else 0,
                          total_remain_weight if total_remain_weight != None else 0,
                          number_of_steward,
                          number_of_guild,

                          ]
            for item in range(len(head_list1)):
                cell = worksheet.cell(row=6, column=item + 2, value=head_list1[item])
                worksheet.row_dimensions[6].height = 12
                value = head_list1[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            l = 11
            m = 1
            for kill_house in kill_houses:
                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, 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')

                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']

                if kill_house.killer == True:
                    kill_house_name = 'کشتارکن' + '(' + kill_house.name + ')'
                else:
                    kill_house_name = 'کشتارگاه' + '(' + kill_house.name + ')'

                list2 = [
                    m,
                    kill_house_name,
                    kill_house.kill_house_operator.user.city.name,
                    number_of_guild + number_of_steward,
                    0,
                    0,
                    total_pre_cold_quantity if total_pre_cold_quantity != None else 0,
                    total_pre_cold_weight if total_pre_cold_weight != None else 0,
                    total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                    total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                    total_number_of_carcasses if total_number_of_carcasses != None else 0,
                    total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                    final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                    final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                    total_allocated_quantity if total_allocated_quantity != None else 0,
                    total_allocated_weight if total_allocated_weight != None else 0,
                    total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                    total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                    total_remain_quantity if total_remain_quantity != None else 0,
                    total_remain_weight if total_remain_weight != None else 0,

                ]
                for item in range(len(list2)):
                    cell = worksheet.cell(row=l, column=item + 1, value=list2[item])
                    value = list2[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values
                    cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.font = Font(size=10, bold=True)
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='medium'),
                        right=openpyxl.styles.Side(style='medium'),
                        top=openpyxl.styles.Side(style='medium'),
                        bottom=openpyxl.styles.Side(style='medium')
                    )
                l += 1
                m += 1
        else:
            worksheet['F2'] = f'اطلاعات کلی توزیع و پخش مرغ گرم از تاریخ {from_date_1} تا {to_date_1}'

            worksheet['F2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range122 = 'F2:N2'
            worksheet.merge_cells(merge_range122)

            worksheet['F2'].font = Font(size=10)

            for abc in abc_list[2:]:
                worksheet[f'{abc}3'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            withe_font = Font(size=12, bold=True, color='D9FFFFFF')
            withe_font1 = Font(size=10, color='D9FFFFFF')
            blue = PatternFill(start_color="4472C4", fill_type="solid")
            worksheet['C3'] = f'ورودی از سردخانه'
            worksheet['E3'] = f'پیش سرد'
            worksheet['G3'] = f'خرید خارج از استان'
            worksheet['I3'] = f'مجموع بارها'
            worksheet['K3'] = f'جمع کل انبار'
            worksheet['M3'] = f'توزیع شده'
            worksheet['O3'] = f'توزیع / تحویل شده'
            worksheet['Q3'] = f'مانده انبار'
            worksheet['S3'] = f'تعداد مباشر تخصیص داده شده'
            worksheet['T3'] = f'تعداد صنف تخصیص داده شده'

            worksheet['C3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['I3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['K3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['M3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['O3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['Q3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['S3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['T3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            merge_range1 = 'C3:D4'
            merge_range2 = 'E3:F4'
            merge_range3 = 'G3:H4'
            merge_range4 = 'I3:J4'
            merge_range5 = 'K3:L4'
            merge_range6 = 'M3:N4'
            merge_range7 = 'O3:P4'
            merge_range8 = 'Q3:R4'
            merge_range9 = 'S3:S5'
            merge_range10 = 'T3:T5'

            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)
            worksheet.merge_cells(merge_range10)

            worksheet['C3'].font = withe_font
            worksheet['E3'].font = withe_font
            worksheet['G3'].font = withe_font
            worksheet['I3'].font = withe_font
            worksheet['K3'].font = withe_font
            worksheet['M3'].font = withe_font
            worksheet['O3'].font = withe_font
            worksheet['Q3'].font = withe_font
            worksheet['S3'].font = withe_font1
            worksheet['T3'].font = withe_font1

            worksheet['C3'].fill = blue
            worksheet['E3'].fill = blue
            worksheet['G3'].fill = blue
            worksheet['I3'].fill = blue
            worksheet['K3'].fill = blue
            worksheet['M3'].fill = blue
            worksheet['O3'].fill = blue
            worksheet['Q3'].fill = blue
            worksheet['S3'].fill = blue
            worksheet['T3'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

            for item in range(len(list1)):
                cell = worksheet.cell(row=5, column=item + 3, value=list1[item])
                worksheet.row_dimensions[5].height = 19

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            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, kill_house__name=sheet_name, 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')

            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']

            list2 = [

                0,
                0,
                total_pre_cold_quantity if total_pre_cold_quantity != None else 0,
                total_pre_cold_weight if total_pre_cold_weight != None else 0,
                total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                total_number_of_carcasses if total_number_of_carcasses != None else 0,
                total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                total_allocated_quantity if total_allocated_quantity != None else 0,
                total_allocated_weight if total_allocated_weight != None else 0,
                total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                total_remain_quantity if total_remain_quantity != None else 0,
                total_remain_weight if total_remain_weight != None else 0,
                number_of_steward,
                number_of_guild,

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=6, column=item + 3, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            excel_options = [
                'ردیف',
                'شناسه صنف',
                'تاریخ ثبت',
                'ماهیت',
                'نوع تخصیص',
                'نام واحد صنفی',
                'نام شخص',
                'کد ملی',
                'موبایل',
                'نوع فعالیت',
                'حوزه فعالیت',
                'شماره مجوز',
                'شهرستان',
                'تعداد لاشه تخصیص',
                'وزن لاشه تخصیصی',
                'تعداد لاشه تحویلی',
                'وزن لاشه تحویلی',
                'وضعیت',
                'کد احراز',
            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=9, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[9].height = 26
                worksheet.freeze_panes = worksheet['A10']
                max_col = worksheet.max_column - 1
                range_str = f'A9:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            m = 1
            l = 10

            stewards = (StewardAllocation.objects.filter(trash=False, ware_house__kill_house__name=sheet_name,
                                                         date__date__gte=date1, date__date__lte=date2)
                .select_related('guilds',
                                'guilds__user',
                                'guilds__address__city',
                                'kill_house',
                                'kill_house__kill_house_operator').order_by(
                'id'))

            if stewards.exists():
                for steward_allocation in stewards:
                    create_date = jdatetime.date.fromgregorian(
                        day=steward_allocation.create_date.day,
                        month=steward_allocation.create_date.month,
                        year=steward_allocation.create_date.year
                    )
                    steward = 'مباشر' if steward_allocation.seller_type == 'steward' else 'صنف'
                    sell_type = 'اختصاصی' if steward_allocation.sell_type == 'exclusive' else 'آزاد'
                    type = 'دستی' if steward_allocation.type == 'manual' else 'اتوماتیک'
                    try:
                        guilds_name = steward_allocation.steward.guilds.guilds_name
                        guilds_id = steward_allocation.steward.guilds.guilds_id
                        fullname = steward_allocation.steward.guilds.user.fullname
                        national_id = steward_allocation.steward.guilds.user.national_id
                        mobile = steward_allocation.steward.guilds.user.mobile
                        type_activity = steward_allocation.steward.guilds.type_activity
                        area_activity = steward_allocation.steward.guilds.area_activity
                        license_number = steward_allocation.steward.guilds.license_number
                        city_name = steward_allocation.steward.guilds.address.city.name
                    except:
                        guilds_name = steward_allocation.guilds.guilds_name
                        guilds_id = steward_allocation.guilds.guilds_id
                        fullname = steward_allocation.guilds.user.fullname
                        national_id = steward_allocation.guilds.user.national_id
                        mobile = steward_allocation.guilds.user.mobile
                        type_activity = steward_allocation.guilds.type_activity
                        area_activity = steward_allocation.guilds.area_activity
                        license_number = steward_allocation.guilds.license_number
                        city_name = steward_allocation.guilds.address.city.name
                    if steward_allocation.receiver_state == 'pending':
                        reciver_type = 'در انتظار تحویل'
                        register = '-'
                    elif steward_allocation.receiver_state == 'accepted':
                        reciver_type = 'تحویل گرفته شد'
                        register = steward_allocation.logged_registration_code if steward_allocation.logged_registration_code else 'وارد نشده'

                    else:
                        reciver_type = 'رد شده'
                        register = '-'

                    list2 = [
                        m,
                        guilds_id,
                        str(create_date),
                        steward,
                        f'{sell_type}({type})',
                        guilds_name,
                        fullname,
                        national_id,
                        mobile,
                        type_activity,
                        area_activity,
                        license_number,
                        city_name,
                        steward_allocation.number_of_carcasses,
                        steward_allocation.weight_of_carcasses,
                        steward_allocation.receiver_real_number_of_carcasses,
                        steward_allocation.receiver_real_weight_of_carcasses,
                        reciver_type,
                        register,

                    ]
                    for item in range(len(list2)):
                        cell = worksheet.cell(row=l, column=item + 1, value=list2[item])
                        value = list2[item]
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,##0'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

                    m += 1
                    l += 1
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش پخش لاشه مرغ گرم.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def daily_process_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(str(request.GET['date']), '%Y-%m-%d').date() if 'date' in request.GET else now
    date_one_day_ago = date1 - timedelta(days=1)

    # user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    poultry_requests = PoultryRequest.objects.filter(
        state_process__in=('pending', 'accepted'),
        province_state__in=('pending', 'accepted'),
        final_state='pending',
        trash=False, out=False,
        send_date__date=date_one_day_ago).select_related('poultry',
                                                         'poultry__user',
                                                         'poultry__address__province').order_by(
        '-send_date')
    if poultry_requests:
        province_name = poultry_requests.first().poultry.user.province.name
    else:
        province_name = ''
    excel_options = {
        'درخواست کشتار مرغداران': [
            'ردیف',
            'کد سفارش',
            'تاریخ ثبت درخواست',
            'تاریخ کشتار',
            'نام و نام خانوادگی مرغدار',
            'نام فارم',
            'موبایل',
            'کشتارگاه های پیشنهادی',
            'آدرس',
            'سن مرغ',
            'تعداد درخواست کشتار',
            'مانده در سالن',
            'تایید شده',
        ],
        'تخصیص به خریداران توسط اتحادیه': [
            'ردیف',
            'کد سفارش',
            'نوع درخواست',
            'نام فارم',
            'نام و نام خانوادگی مرغدار',
            'موبایل',
            'شهر',
            'تاریخ کشتار',
            'تعداد کشتار',
            'زمان تخصیص',
            'نوع تخصیص',
            'خریدار',
            'تعداد تخصیص داده شده',
            ' تلفن خریدار',
            ' آدرس خریدار',
            'تایید تخصیص',
            'تخصیص ماشین',

        ],
        'ثبت ماشین(ایجاد بار)': [
            'ردیف',
            'کد بار',
            'مرغدار',
            'تلفن مرغدار',
            'کدسفارش مرغدار',
            ' شهر مرغدار',
            ' تاریخ کشتار',
            ' نژاد',
            'دامپزشک فارم',
            'تلفن دامپزشک فارم',
            'خریدار',
            ' تلفن خریدار',
            ' ماهیت خریدار',
            ' آدرس ',
            ' محل کشتار ',
            'دامپزشک کشتارگاه ',
            ' تلفن دامپزشک کشتارگاه ',
            'راننده',
            'موبایل راننده',
            'نوع خودرو',
            'کد بهداشتی حمل و نقل',
            'کد رهگیری سامانه قرنطینه',
            'تعداد تخصیصی',
            'تعداد تخلیه شده',
            'وزن بار',
            'تاریخ تخلیه (کشتارگاه)',
            'مبلغ فاکتور',
            'تاریخ پرداخت فاکتور',

        ],
        'اطلاعات انبار خریداران': [
            'ردیف',
            'خریدار',
            'شناسه صنف',
            'تاریخ ثبت',
            'ماهیت',
            'نوع تخصیص',
            'نام واحد صنفی',
            'نام شخص',
            'کد ملی',
            'موبایل',
            'نوع فعالیت',
            'حوزه فعالیت',
            'شماره مجوز',
            'شهرستان',
            'تعداد لاشه',
            'وزن لاشه',
            'کد احراز',

        ]

    }

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    fro_date = jdatetime.date.fromgregorian(
        year=date_one_day_ago.year,
        month=date_one_day_ago.month,
        day=date_one_day_ago.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(fro_date.split("-"))
    separate = "-"
    from_date_2 = separate.join(reversed_date)
    output = BytesIO()
    workbook = Workbook()
    # worksheet = workbook.active

    for name, options in excel_options.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000", bold=True)

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=4, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            if len(option) > worksheet.column_dimensions[col_letter].width:
                worksheet.column_dimensions[col_letter].width = len(option)

                # تنظیم ارتفاع سطر
                # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.column_dimensions[col_letter].height = len(option)
            worksheet.freeze_panes = worksheet['A5']
            max_col = worksheet.max_column
            range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        l = 3
        if sheet_name == 'درخواست کشتار مرغداران':
            m = 1
            worksheet['A1'] = f'درخواست کشتار مرغداران استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_2})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)

            if poultry_requests:
                for filtered_poultry_kill_request in poultry_requests:
                    date_of_create = jdatetime.date.fromgregorian(
                        day=filtered_poultry_kill_request.create_date.day,
                        month=filtered_poultry_kill_request.create_date.month,
                        year=filtered_poultry_kill_request.create_date.year
                    )
                    date_of_kill = jdatetime.date.fromgregorian(
                        day=filtered_poultry_kill_request.send_date.day,
                        month=filtered_poultry_kill_request.send_date.month,
                        year=filtered_poultry_kill_request.send_date.year
                    )
                    state = 'تایید شده'
                    if filtered_poultry_kill_request.state == 'pending':
                        state = 'در انتظار تایید'
                    kill_house = '-'
                    if filtered_poultry_kill_request.kill_house_list is not None:
                        for name in filtered_poultry_kill_request.kill_house_list:
                            kill_house += name + '/'
                    age = (
                                  filtered_poultry_kill_request.send_date.date() - filtered_poultry_kill_request.hatching.date.date()).days + 1

                    list1 = [
                        m,
                        filtered_poultry_kill_request.order_code,
                        str(date_of_create),
                        str(date_of_kill),
                        filtered_poultry_kill_request.poultry.user.fullname,
                        filtered_poultry_kill_request.poultry.unit_name,
                        filtered_poultry_kill_request.poultry.user.mobile,
                        kill_house,
                        filtered_poultry_kill_request.poultry.address.city.name,
                        str(age),
                        filtered_poultry_kill_request.quantity,
                        filtered_poultry_kill_request.hatching.left_over,
                        state
                    ]
                    m += 1
                    l += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'تخصیص به خریداران توسط اتحادیه':
            m = 1
            worksheet['A1'] = f'تخصیص به خریداران توسط اتحادیه استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_2})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            prvince_kill_requests = ProvinceKillRequest.objects.filter(
                trash=False,
                province_request__poultry_request__in=poultry_requests).order_by('-create_date')
            for filtered_province_kill_req in prvince_kill_requests:
                car = 'دارد' if KillHouseRequest.objects.filter(province_kill_request=filtered_province_kill_req,
                                                                trash=False).exists() else '-'

                l += 1
                date_of_kill = jdatetime.date.fromgregorian(
                    day=filtered_province_kill_req.province_request.poultry_request.send_date.day,
                    month=filtered_province_kill_req.province_request.poultry_request.send_date.month,
                    year=filtered_province_kill_req.province_request.poultry_request.send_date.year
                )
                date_of_allocation = jdatetime.date.fromgregorian(
                    day=filtered_province_kill_req.create_date.day,
                    month=filtered_province_kill_req.create_date.month,
                    year=filtered_province_kill_req.create_date.year
                )
                if filtered_province_kill_req.state == "accepted":
                    state = 'تایید شده'
                elif filtered_province_kill_req.state == "pending":
                    state = 'در انتظار تایید'
                else:
                    state = 'رد شده'

                automatic = 'خودکار' if filtered_province_kill_req.automatic else 'دستی'
                if filtered_province_kill_req.province_request.poultry_request.union == True:
                    type = 'فروش آزاد'
                elif filtered_province_kill_req.province_request.poultry_request.direct_buying == True:
                    type = 'خرید مستقیم'
                else:
                    type = 'اتحادیه'
                list1 = [
                    m,
                    filtered_province_kill_req.province_request.poultry_request.order_code,
                    type,
                    filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
                    filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
                    filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
                    filtered_province_kill_req.province_request.poultry_request.poultry.address.city.name,
                    str(date_of_kill),
                    filtered_province_kill_req.province_request.poultry_request.quantity,
                    str(date_of_allocation),
                    automatic,
                    filtered_province_kill_req.killhouse_user.name,
                    filtered_province_kill_req.main_quantity,
                    filtered_province_kill_req.killhouse_user.kill_house_operator.user.mobile,
                    # filtered_province_kill_req.killhouse_user.kill_house_operator.address.city.name,
                    filtered_province_kill_req.kill_request.kill_house.system_address.city.name,
                    state,
                    car

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'ثبت ماشین(ایجاد بار)':
            m = 1
            worksheet['A1'] = f'ثبت ماشین توسط خریدار(ایجاد بار) استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_2})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            filtered_kill_reqs = KillHouseRequest.objects.filter(
                kill_request__recive_date__date=date_one_day_ago,
                trash=False).order_by(
                '-create_date').select_related(
                'killhouse_user', 'province_request__poultry_request__poultry__user',
                'province_request__poultry_request',
                'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
                'kill_request__slaughter_house').only('killhouse_user',
                                                      'killhouse_user__name',
                                                      'killhouse_user__kill_house_operator__user__mobile',
                                                      'killhouse_user__system_address__city__name',
                                                      'killhouse_user__killer',
                                                      'kill_request__slaughter_house',
                                                      'kill_request__slaughter_house__name',
                                                      'province_request__poultry_request__poultry',
                                                      'province_request__poultry_request__order_code',
                                                      'province_request__poultry_request__chicken_breed',
                                                      'province_request__poultry_request__poultry__user__city__name',
                                                      'province_request__poultry_request__poultry__unit_name',
                                                      'province_request__poultry_request__poultry__user__mobile',
                                                      'province_request__poultry_request__send_date',
                                                      'add_car__driver__driver_name',
                                                      'add_car__driver__driver_mobile',
                                                      'add_car__driver__type_car',
                                                      'add_car__driver__health_code',
                                                      'key',
                                                      'clearance_code',
                                                      'quantity',
                                                      'bar_code').values(
                'killhouse_user',
                'killhouse_user__name',
                'killhouse_user__kill_house_operator__user__mobile',
                'killhouse_user__system_address__city__name',
                'killhouse_user__killer',
                'kill_request__slaughter_house',
                'kill_request__slaughter_house__name',
                'province_request__poultry_request__poultry',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__chicken_breed',
                'province_request__poultry_request__poultry__user__city__name',
                'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__send_date',
                'add_car__driver__driver_name',
                'add_car__driver__driver_mobile',
                'add_car__driver__type_car',
                'add_car__driver__health_code',
                'key',
                'clearance_code',
                'quantity',
                'bar_code',
            )
            if filtered_kill_reqs:
                for kill in filtered_kill_reqs:
                    l += 1
                    date_of_inner_bar = '-'
                    date_factor = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    factor = ProvinceFactorToKillHouse.objects.filter(
                        province_check_info__kill_house_assignment__kill_house_request__key=kill.get('key')).only(
                        'total_price').values(
                        'total_price').first()
                    factor_amount = factor.get('total_price') if factor else '-'
                    factor_payment = KillHouseFactorToProvince.objects.filter(
                        province_factor__province_check_info__kill_house_assignment__kill_house_request__key=kill.get(
                            'key')).only('create_date').values(
                        'create_date').first()
                    if factor_payment:
                        factor_date = factor_payment.get('create_date')
                        date_factor = jdatetime.date.fromgregorian(
                            day=factor_date.day,
                            month=factor_date.month,
                            year=factor_date.year
                        ) if factor_payment else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight') if assignment else '-'
                        real_quantity = assignment.get('real_quantity')
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = jdatetime.date.fromgregorian(
                            day=vet_check_date.day,
                            month=vet_check_date.month,
                            year=vet_check_date.year
                        ) if vet_checks else '-'
                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__order_code'),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        str(date_of_poultry_request),
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        killers,
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        kill.get('add_car__driver__health_code'),
                        code,
                        quantity,
                        real_quantity,
                        net_weighte,
                        str(date_of_inner_bar),
                        factor_amount,
                        str(date_factor)
                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'اطلاعات انبار خریداران':
            m = 1
            worksheet['A1'] = f' اطلاعات انبار خریداران استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_1})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'

            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            province_kill_requests = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                                        kill_request__recive_date__date=date_one_day_ago).select_related(
                'killhouse_user')
            kill_house_list = KillHouse.objects.filter(
                pk__in=province_kill_requests.values('killhouse_user')

            ).select_related('kill_house_operator', 'kill_house_operator__user', 'kill_house_operator__address__city')
            # برای بالای هدر
            kill_house_ware_houses = KillHouseWareHouse.objects.filter(kill_house__in=kill_house_list, date__date=date1)
            steward_allocations = StewardAllocation.objects.filter(
                system_registration_code=True,
                ware_house__in=kill_house_ware_houses, trash=False,
                date__date=date1).select_related('guilds', 'guilds__user', 'guilds__address__city', 'kill_house',
                                                 'kill_house__kill_house_operator').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']

            header_list = [
                'تعداد خریداران',
                'تعداد مباشرین',
                'تعداد لاشه ها',
                'وزن لاشه ها (کیلوگرم)',
                'تعداد لاشه تخصیص داده شده',
                'وزن تخصیص داده شده (کیلوگرم)',
                'تعداد لاشه قابل تخصیص',
                'وزن قابل تخصیص (کیلوگرم)',

            ]
            for col_num, option in enumerate(header_list, 3):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 17
                worksheet.column_dimensions[col_letter].width = 21.01

                # worksheet.row_dimensions[2].width = 21
            value_header_list = [
                len(kill_house_ware_houses),
                len(steward_allocations),
                total_number_of_carcasses if total_number_of_carcasses != None else 0,
                total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                allocated_total_number_of_carcasses if allocated_total_number_of_carcasses != None else 0,
                allocated_total_weight_of_carcasses if allocated_total_weight_of_carcasses != None else 0,
                remain_total_number_of_carcasses if remain_total_number_of_carcasses != None else 0,
                remain_total_weight_of_carcasses if remain_total_weight_of_carcasses != None else 0,
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 3, value=value_header_list[item])
                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=11)

            for steward_allocation in steward_allocations:
                killer = 'کشتارکن' if steward_allocation.kill_house.killer == True else 'کشتارگاه'
                kill_house_name = steward_allocation.kill_house.name

                date = jdatetime.date.fromgregorian(
                    year=steward_allocation.date.year,
                    month=steward_allocation.date.month,
                    day=steward_allocation.date.day
                )
                steward = 'مباشر' if steward_allocation.seller_type == 'steward' else 'صنف'
                sell_type = 'اختصاصی' if steward_allocation.sell_type == 'exclusive' else 'آزاد'
                type = 'دستی' if steward_allocation.type == 'manual' else 'اتوماتیک'
                try:
                    guilds_name = steward_allocation.steward.guilds.guilds_name
                    guilds_id = steward_allocation.steward.guilds.guilds_id
                    fullname = steward_allocation.steward.guilds.user.fullname
                    national_id = steward_allocation.steward.guilds.user.national_id
                    mobile = steward_allocation.steward.guilds.user.mobile
                    type_activity = steward_allocation.steward.guilds.type_activity
                    area_activity = steward_allocation.steward.guilds.area_activity
                    license_number = steward_allocation.steward.guilds.license_number
                    city_name = steward_allocation.steward.guilds.address.city.name
                except:
                    guilds_name = steward_allocation.guilds.guilds_name
                    guilds_id = steward_allocation.guilds.guilds_id
                    fullname = steward_allocation.guilds.user.fullname
                    national_id = steward_allocation.guilds.user.national_id
                    mobile = steward_allocation.guilds.user.mobile
                    type_activity = steward_allocation.guilds.type_activity
                    area_activity = steward_allocation.guilds.area_activity
                    license_number = steward_allocation.guilds.license_number
                    city_name = steward_allocation.guilds.address.city.name
                register = steward_allocation.logged_registration_code if steward_allocation.logged_registration_code else '-'
                list1 = [
                    m,
                    f'{killer} {kill_house_name}({steward_allocation.kill_house.kill_house_operator.user.fullname})',
                    guilds_id,
                    str(date),
                    steward,
                    f'{sell_type}({type})',
                    guilds_name,
                    fullname,
                    national_id,
                    mobile,
                    type_activity,
                    area_activity,
                    license_number,
                    city_name,
                    steward_allocation.number_of_carcasses,
                    steward_allocation.weight_of_carcasses,
                    register,
                ]
                l += 1
                m += 1
                for col_num, option in enumerate(list1, 1):
                    col_letter = get_column_letter(col_num)
                    cell = worksheet.cell(row=l + 1, column=col_num, value=option)
                    cell.alignment = Alignment(horizontal='center', vertical='center')

                    worksheet.row_dimensions[4].height = 19
                    worksheet.column_dimensions[col_letter].width = 21.01

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش پخش روزانه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    user = get_object_or_404(SystemUserProfile, key=request.GET['key'])
    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=date1).select_related('poultry',
                                                                                           'poultry__user',
                                                                                           'poultry__address__province').order_by(
        '-send_date')
    province_name = user.province.name

    excel_options = {
        'درخواست کشتار مرغداران': [
            'ردیف',
            'کد سفارش',
            'تاریخ ثبت درخواست',
            'تاریخ کشتار',
            'نام و نام خانوادگی مرغدار',
            'نام فارم',
            'موبایل',
            'کشتارگاه های پیشنهادی',
            'آدرس',
            'سن مرغ',
            'تعداد درخواست کشتار',
            'مانده در سالن',
            'تایید شده',
        ],
        'تخصیص به خریداران توسط اتحادیه': [
            'ردیف',
            'کد سفارش',
            'نوع درخواست',
            'نام فارم',
            'نام و نام خانوادگی مرغدار',
            'موبایل',
            'شهر',
            'تاریخ کشتار',
            'تعداد کشتار',
            'زمان تخصیص',
            'نوع تخصیص',
            'خریدار',
            'تعداد تخصیص داده شده',
            ' تلفن خریدار',
            ' آدرس خریدار',
            'تایید تخصیص',
            'تخصیص ماشین',

        ],
        'ثبت ماشین(ایجاد بار)': [
            'ردیف',
            'کد بار',
            'مرغدار',
            'تلفن مرغدار',
            'کدسفارش مرغدار',
            ' شهر مرغدار',
            ' تاریخ کشتار',
            ' نژاد',
            'دامپزشک فارم',
            'تلفن دامپزشک فارم',
            'خریدار',
            ' تلفن خریدار',
            ' ماهیت خریدار',
            ' آدرس ',
            ' محل کشتار ',
            'دامپزشک کشتارگاه ',
            ' تلفن دامپزشک کشتارگاه ',
            'راننده',
            'موبایل راننده',
            'نوع خودرو',
            'کد بهداشتی حمل و نقل',
            'کد رهگیری سامانه قرنطینه',
            'تعداد تخصیصی',
            'تعداد تخلیه شده',
            'وزن بار',
            'تاریخ تخلیه (کشتارگاه)',
            'مبلغ فاکتور',
            'تاریخ پرداخت فاکتور',

        ]
    }

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    # worksheet = workbook.active

    for name, options in excel_options.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000", bold=True)

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=4, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            if len(option) > worksheet.column_dimensions[col_letter].width:
                worksheet.column_dimensions[col_letter].width = len(option)

                # تنظیم ارتفاع سطر
                # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.column_dimensions[col_letter].height = len(option)
            worksheet.freeze_panes = worksheet['A5']
            max_col = worksheet.max_column
            range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        l = 3
        if sheet_name == 'درخواست کشتار مرغداران':
            m = 1
            worksheet['A1'] = f'درخواست کشتار مرغداران استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_1})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)

            if poultry_requests:
                for filtered_poultry_kill_request in poultry_requests:
                    date_of_create = jdatetime.date.fromgregorian(
                        day=filtered_poultry_kill_request.create_date.day,
                        month=filtered_poultry_kill_request.create_date.month,
                        year=filtered_poultry_kill_request.create_date.year
                    )
                    date_of_kill = jdatetime.date.fromgregorian(
                        day=filtered_poultry_kill_request.send_date.day,
                        month=filtered_poultry_kill_request.send_date.month,
                        year=filtered_poultry_kill_request.send_date.year
                    )
                    state = 'تایید شده'
                    if filtered_poultry_kill_request.state == 'pending':
                        state = 'در انتظار تایید'
                    kill_house = '-'
                    if filtered_poultry_kill_request.kill_house_list is not None:
                        for name in filtered_poultry_kill_request.kill_house_list:
                            kill_house += name + '/'
                    age = (
                                  filtered_poultry_kill_request.send_date.date() - filtered_poultry_kill_request.hatching.date.date()).days + 1

                    list1 = [
                        m,
                        filtered_poultry_kill_request.order_code,
                        str(date_of_create),
                        str(date_of_kill),
                        filtered_poultry_kill_request.poultry.user.fullname,
                        filtered_poultry_kill_request.poultry.unit_name,
                        filtered_poultry_kill_request.poultry.user.mobile,
                        kill_house,
                        filtered_poultry_kill_request.poultry.address.city.name,
                        str(age),
                        filtered_poultry_kill_request.quantity,
                        filtered_poultry_kill_request.hatching.left_over,
                        state
                    ]
                    m += 1
                    l += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'تخصیص به خریداران توسط اتحادیه':
            m = 1
            worksheet['A1'] = f'تخصیص به خریداران توسط اتحادیه استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_1})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            prvince_kill_requests = ProvinceKillRequest.objects.filter(
                trash=False,
                province_request__poultry_request__in=poultry_requests).order_by('-create_date')
            for filtered_province_kill_req in prvince_kill_requests:
                car = 'دارد' if KillHouseRequest.objects.filter(province_kill_request=filtered_province_kill_req,
                                                                trash=False).exists() else '-'

                l += 1
                date_of_kill = jdatetime.date.fromgregorian(
                    day=filtered_province_kill_req.province_request.poultry_request.send_date.day,
                    month=filtered_province_kill_req.province_request.poultry_request.send_date.month,
                    year=filtered_province_kill_req.province_request.poultry_request.send_date.year
                )
                date_of_allocation = jdatetime.date.fromgregorian(
                    day=filtered_province_kill_req.create_date.day,
                    month=filtered_province_kill_req.create_date.month,
                    year=filtered_province_kill_req.create_date.year
                )
                if filtered_province_kill_req.state == "accepted":
                    state = 'تایید شده'
                elif filtered_province_kill_req.state == "pending":
                    state = 'در انتظار تایید'
                else:
                    state = 'رد شده'

                automatic = 'خودکار' if filtered_province_kill_req.automatic else 'دستی'
                if filtered_province_kill_req.province_request.poultry_request.union == True:
                    type = 'فروش آزاد'
                elif filtered_province_kill_req.province_request.poultry_request.direct_buying == True:
                    type = 'خرید مستقیم'
                else:
                    type = 'اتحادیه'
                list1 = [
                    m,
                    filtered_province_kill_req.province_request.poultry_request.order_code,
                    type,
                    filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
                    filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
                    filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
                    filtered_province_kill_req.province_request.poultry_request.poultry.address.city.name,
                    str(date_of_kill),
                    filtered_province_kill_req.province_request.poultry_request.quantity,
                    str(date_of_allocation),
                    automatic,
                    filtered_province_kill_req.killhouse_user.name,
                    filtered_province_kill_req.main_quantity,
                    filtered_province_kill_req.killhouse_user.kill_house_operator.user.mobile,
                    # filtered_province_kill_req.killhouse_user.kill_house_operator.address.city.name,
                    filtered_province_kill_req.kill_request.kill_house.system_address.city.name,
                    state,
                    car

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'ثبت ماشین(ایجاد بار)':
            m = 1
            worksheet['A1'] = f'ثبت ماشین توسط خریدار(ایجاد بار) استان {province_name}'
            worksheet['A3'] = f'در تاریخ:({from_date_1})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            # worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            filtered_kill_reqs = KillHouseRequest.objects.filter(
                province_request__poultry_request__poultry__address__province=user.province,
                kill_request__recive_date__date=date1,

                trash=False).order_by(
                '-create_date').select_related(
                'killhouse_user', 'province_request__poultry_request__poultry__user',
                'province_request__poultry_request',
                'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
                'kill_request__slaughter_house').only('killhouse_user',
                                                      'killhouse_user__name',
                                                      'killhouse_user__kill_house_operator__user__mobile',
                                                      'killhouse_user__system_address__city__name',
                                                      'killhouse_user__killer',
                                                      'kill_request__slaughter_house',
                                                      'kill_request__slaughter_house__name',
                                                      'province_request__poultry_request__poultry',
                                                      'province_request__poultry_request__order_code',
                                                      'province_request__poultry_request__chicken_breed',
                                                      'province_request__poultry_request__poultry__user__city__name',
                                                      'province_request__poultry_request__poultry__unit_name',
                                                      'province_request__poultry_request__poultry__user__mobile',
                                                      'province_request__poultry_request__send_date',
                                                      'add_car__driver__driver_name',
                                                      'add_car__driver__driver_mobile',
                                                      'add_car__driver__type_car',
                                                      'add_car__driver__health_code',
                                                      'key',
                                                      'clearance_code',
                                                      'quantity',
                                                      'bar_code').values(
                'killhouse_user',
                'killhouse_user__name',
                'killhouse_user__kill_house_operator__user__mobile',
                'killhouse_user__system_address__city__name',
                'killhouse_user__killer',
                'kill_request__slaughter_house',
                'kill_request__slaughter_house__name',
                'province_request__poultry_request__poultry',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__chicken_breed',
                'province_request__poultry_request__poultry__user__city__name',
                'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__send_date',
                'add_car__driver__driver_name',
                'add_car__driver__driver_mobile',
                'add_car__driver__type_car',
                'add_car__driver__health_code',
                'key',
                'clearance_code',
                'quantity',
                'bar_code',
            )
            if filtered_kill_reqs:
                for kill in filtered_kill_reqs:
                    l += 1
                    date_of_inner_bar = '-'
                    date_factor = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    factor = ProvinceFactorToKillHouse.objects.filter(
                        province_check_info__kill_house_assignment__kill_house_request__key=kill.get('key')).only(
                        'total_price').values(
                        'total_price').first()
                    factor_amount = factor.get('total_price') if factor else '-'
                    factor_payment = KillHouseFactorToProvince.objects.filter(
                        province_factor__province_check_info__kill_house_assignment__kill_house_request__key=kill.get(
                            'key')).only('create_date').values(
                        'create_date').first()
                    if factor_payment:
                        factor_date = factor_payment.get('create_date')
                        date_factor = jdatetime.date.fromgregorian(
                            day=factor_date.day,
                            month=factor_date.month,
                            year=factor_date.year
                        ) if factor_payment else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight') if assignment else '-'
                        real_quantity = assignment.get('real_quantity')
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = jdatetime.date.fromgregorian(
                            day=vet_check_date.day,
                            month=vet_check_date.month,
                            year=vet_check_date.year
                        ) if vet_checks else '-'
                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__order_code'),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        str(date_of_poultry_request),
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        killers,
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        kill.get('add_car__driver__health_code'),
                        code,
                        quantity,
                        real_quantity,
                        net_weighte,
                        str(date_of_inner_bar),
                        factor_amount,
                        str(date_factor)
                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش کشتار روزانه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def killing_process_from_date_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    day_before_date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date() - timedelta(days=1)
    day_before_date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date() - timedelta(days=1)
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()

    excel_options = {
        'درخواست کشتار': [
            'ردیف',
            'کد سفارش',
            'تاریخ ثبت درخواست',
            'تاریخ کشتار',
            'نام و نام خانوادگی مرغدار',
            'نام فارم',
            'موبایل',
            'کشتارگاه های پیشنهادی',
            'آدرس',
            'سن مرغ',
            'تعداد درخواست کشتار',
            'مانده در سالن',
            'تایید شده',
        ],
        'تخصیصات': [
            'ردیف',
            'کد سفارش',
            'نوع درخواست',
            'نام فارم',
            'نام و نام خانوادگی مرغدار',
            'موبایل',
            'شهر',
            'تاریخ کشتار',
            'تعداد کشتار',
            'زمان تخصیص',
            'نوع تخصیص',
            'خریدار',
            'تعداد تخصیص داده شده',
            ' تلفن خریدار',
            ' آدرس خریدار',
            'تایید تخصیص',
            'تخصیص ماشین',

        ],
        'مسئول فنی مزرعه': [
            'ردیف',
            'کد بار',
            'مرغدار',
            'تلفن مرغدار',
            'کدسفارش مرغدار',
            ' شهر مرغدار',
            ' تاریخ کشتار',
            ' نژاد',
            'دامپزشک فارم',
            'تلفن دامپزشک فارم',
            'خریدار',
            ' تلفن خریدار',
            ' ماهیت خریدار',
            ' آدرس ',
            ' محل کشتار ',
            'دامپزشک کشتارگاه ',
            ' تلفن دامپزشک کشتارگاه ',
            'کد رهگیری سامانه قرنطینه',
            'تعداد تخصیصی',
            'تعداد تخلیه شده',
            'وزن بار',
            'تاریخ تخلیه (کشتارگاه)'],

        'دامپزشک کشتارگاه': [
            'ردیف',
            'کد بار',
            ' تاریخ کشتار',
            'کدسفارش مرغدار',
            'مرغدار',
            'تلفن مرغدار',
            ' شهر مرغدار',
            ' نژاد',
            'دامپزشک فارم',
            'تلفن دامپزشک فارم',
            ' ماهیت خریدار',
            'خریدار',
            ' تلفن خریدار',
            ' آدرس ',
            ' محل کشتار ',
            'دامپزشک کشتارگاه ',
            ' تلفن دامپزشک کشتارگاه ',
            'راننده',
            'موبایل راننده',
            'نوع خودرو',
            'کد بهداشتی حمل و نقل',
            'کد رهگیری سامانه قرنطینه',
            'تعداد تخصیصی',
            'وزن تخصیصی',
            'تاریخ تخلیه (کشتارگاه)',
            'تعداد تخلیه شده',
            'وزن بار تخلیه شده(کیلوگرم)',

        ]
        ,
        'اطلاعات کلی پخش به مباشر': [
            'ردیف',
            ' ماهیت خریدار',
            'خریدار',
            'تاریخ پخش',
            'موبایل خریدار',
            'شهر',
            'تعداد لاشه ها',
            'وزن لاشه ها(کیلوگرم)',
            'تعداد لاشه تخصیص داده شده',
            'وزن تخصیص داده شده(کیلوگرم)',
            'مانده لاشه قابل تخصیص(قطعه)',
            ' مانده وزن قابل تخصیص(کیلوگرم)',

        ],
        'جزئیات پخش به مباشر': [
            'ردیف',
            'خریدار',
            'شناسه صنف',
            'تاریخ ثبت',
            'ماهیت',
            'نوع تخصیص',
            'نام واحد صنفی',
            'نام شخص',
            'کد ملی',
            'موبایل',
            'نوع فعالیت',
            'حوزه فعالیت',
            'شماره مجوز',
            'شهرستان',
            'تعداد لاشه',
            'وزن لاشه',
            'کد احراز',

        ],
    }

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    # date_one_day_ago = date - timedelta(days=1)

    province_kill_requests = ProvinceKillRequest.objects.filter(state__in=('pending', 'accepted'),
                                                                kill_request__recive_date__date__gte=day_before_date1,
                                                                kill_request__recive_date__date__lte=day_before_date2).select_related(
        'killhouse_user')
    kill_house_list = KillHouse.objects.filter(
        pk__in=province_kill_requests.values('killhouse_user')

    ).select_related('kill_house_operator', 'kill_house_operator__user', 'kill_house_operator__address__city')

    kill_house_ware_houses = KillHouseWareHouse.objects.filter(kill_house__in=kill_house_list, date__date__gte=date1,
                                                               date__date__lte=date2).order_by('id')
    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__gte=date1, date__date__lte=date2).select_related('guilds', 'guilds__user', 'guilds__address__city',
                                                                     'kill_house',
                                                                     'kill_house__kill_house_operator').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']

    filtered_kill_reqs = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                         kill_request__recive_date__date__lte=date2,
                                                         trash=False).order_by('-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry')
    output = BytesIO()
    workbook = Workbook()

    for name, options in excel_options.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000", bold=True)

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=4, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            if len(option) > worksheet.column_dimensions[col_letter].width:
                worksheet.column_dimensions[col_letter].width = len(option)
                worksheet.column_dimensions[col_letter].height = len(option)
            worksheet.freeze_panes = worksheet['A5']
            max_col = worksheet.max_column
            range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        l = 3
        m = 1
        if sheet_name == 'درخواست کشتار':
            worksheet['A1'] = f'درخواست کشتار'
            worksheet['A3'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:C2'
            merge_range = 'A3:C3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            filtered_province_kill_reqs = PoultryRequest.objects.filter(send_date__date__gte=date1,
                                                                        send_date__date__lte=date2,
                                                                        trash=False).select_related('poultry',
                                                                                                    'poultry__user',
                                                                                                    'poultry__address__province').order_by(
                '-send_date')
            if filtered_province_kill_reqs:
                province = filtered_province_kill_reqs.first().poultry.address.province.name
                worksheet['A2'] = f'استان {province}'
                for filtered_poultry_kill_request in filtered_province_kill_reqs:
                    l += 1
                    date_of_create = jdatetime.date.fromgregorian(
                        day=filtered_poultry_kill_request.create_date.day,
                        month=filtered_poultry_kill_request.create_date.month,
                        year=filtered_poultry_kill_request.create_date.year
                    )
                    date_of_kill = jdatetime.date.fromgregorian(
                        day=filtered_poultry_kill_request.send_date.day,
                        month=filtered_poultry_kill_request.send_date.month,
                        year=filtered_poultry_kill_request.send_date.year
                    )
                    state = 'تایید شده'
                    if filtered_poultry_kill_request.state == 'pending':
                        state = 'در انتظار تایید'
                    kill_house = '-'
                    if filtered_poultry_kill_request.kill_house_list is not None:
                        for name in filtered_poultry_kill_request.kill_house_list:
                            kill_house += name + '/'
                    age = (
                                  filtered_poultry_kill_request.send_date.date() - filtered_poultry_kill_request.hatching.date.date()).days + 1

                    list1 = [
                        m,
                        filtered_poultry_kill_request.order_code,
                        str(date_of_create),
                        str(date_of_kill),
                        filtered_poultry_kill_request.poultry.user.fullname,
                        filtered_poultry_kill_request.poultry.unit_name,
                        filtered_poultry_kill_request.poultry.user.mobile,
                        kill_house,
                        filtered_poultry_kill_request.poultry.address.city.name,
                        str(age),
                        filtered_poultry_kill_request.quantity,
                        filtered_poultry_kill_request.hatching.left_over,
                        state
                    ]
                    m += 1

                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'تخصیصات':
            filtered_province_kill_reqs = ProvinceKillRequest.objects.filter(
                province_request__poultry_request__send_date__date__gte=date1,
                province_request__poultry_request__send_date__date__lte=date2, trash=False).select_related(
                'province_request__poultry_request', 'province_request__poultry_request__poultry',
                'province_request__poultry_request__poultry__user',
                'province_request__poultry_request__poultry__address').order_by('-create_date')

            worksheet['A1'] = f' مدیریت تخصیصات'
            worksheet['A3'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'

            if filtered_province_kill_reqs.exists():
                province = filtered_province_kill_reqs.first().province_request.poultry_request.poultry.address.province.name
                worksheet['A2'] = f'استان {province}'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:C2'
            merge_range = 'A3:C3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)

            for filtered_province_kill_req in filtered_province_kill_reqs:
                car = 'دارد' if KillHouseRequest.objects.filter(province_kill_request=filtered_province_kill_req,
                                                                trash=False).exists() else '-'

                l += 1
                date_of_kill = jdatetime.date.fromgregorian(
                    day=filtered_province_kill_req.province_request.poultry_request.send_date.day,
                    month=filtered_province_kill_req.province_request.poultry_request.send_date.month,
                    year=filtered_province_kill_req.province_request.poultry_request.send_date.year
                )
                date_of_allocation = jdatetime.date.fromgregorian(
                    day=filtered_province_kill_req.create_date.day,
                    month=filtered_province_kill_req.create_date.month,
                    year=filtered_province_kill_req.create_date.year
                )
                if filtered_province_kill_req.state == "accepted":
                    state = 'تایید شده'
                elif filtered_province_kill_req.state == "pending":
                    state = 'در انتظار تایید'
                else:
                    state = 'رد شده'

                automatic = 'خودکار' if filtered_province_kill_req.automatic else 'دستی'
                if filtered_province_kill_req.province_request.poultry_request.union == True:
                    type = 'فروش آزاد'
                elif filtered_province_kill_req.province_request.poultry_request.direct_buying == True:
                    type = 'خرید مستقیم'
                else:
                    type = 'اتحادیه'
                list1 = [
                    m,
                    filtered_province_kill_req.province_request.poultry_request.order_code,
                    type,
                    filtered_province_kill_req.province_request.poultry_request.poultry.unit_name,
                    filtered_province_kill_req.province_request.poultry_request.poultry.user.fullname,
                    filtered_province_kill_req.province_request.poultry_request.poultry.user.mobile,
                    filtered_province_kill_req.province_request.poultry_request.poultry.address.city.name,
                    str(date_of_kill),
                    filtered_province_kill_req.province_request.poultry_request.quantity,
                    str(date_of_allocation),
                    automatic,
                    filtered_province_kill_req.killhouse_user.name,
                    filtered_province_kill_req.main_quantity,
                    filtered_province_kill_req.killhouse_user.kill_house_operator.user.mobile,
                    # filtered_province_kill_req.killhouse_user.kill_house_operator.address.city.name,
                    filtered_province_kill_req.kill_request.kill_house.system_address.city.name,
                    state,
                    car

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'مسئول فنی مزرعه':
            worksheet['A1'] = f' مسئول فنی مزرعه'
            worksheet['A3'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:C2'
            merge_range = 'A3:C3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            # filtered_kill_reqs = KillHouseRequest.objects.filter(kill_request__recive_date__date__gte=date1,kill_request__recive_date__date__lte=date2,
            #                                                      trash=False).order_by(
            #     '-create_date').select_related(
            #     'killhouse_user', 'province_request__poultry_request__poultry')
            if filtered_kill_reqs.exists():
                province = filtered_kill_reqs.first().province_request.poultry_request.poultry.address.province.name
                worksheet['A2'] = f'استان {province}'
            if filtered_kill_reqs:
                for kill in filtered_kill_reqs:
                    vet_farm = VetFarm.objects.filter(poultry=kill.province_request.poultry_request.poultry,
                                                      trash=False).last()
                    vet_farm_name = vet_farm.vet.user.fullname if vet_farm else '-'
                    vet_farm_mobile = vet_farm.vet.user.mobile if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.killhouse_user).last()
                    vet_checks = VetCheckRequest.objects.filter(kill_house_request=kill).only('create_date').last()
                    kill_house_vet_name = kil_house_vet.vet.user.fullname if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.vet.user.mobile if kil_house_vet else '-'

                    code = kill.clearance_code if kill.clearance_code else '-'
                    quantity = kill.quantity if kill.quantity else '-'
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=kill.province_request.poultry_request.send_date.day,
                        month=kill.province_request.poultry_request.send_date.month,
                        year=kill.province_request.poultry_request.send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.killhouse_user.killer == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request=kill, trash=False).last()
                    net_weighte = assignment.net_weight if assignment else '-'
                    real_quantity = assignment.real_quantity if assignment else '-'
                    date_of_inner_bar = jdatetime.date.fromgregorian(
                        day=vet_checks.create_date.day,
                        month=vet_checks.create_date.month,
                        year=vet_checks.create_date.year
                    ) if vet_checks else '-'
                    if kill.kill_request.slaughter_house != None:
                        kill_place = kill.kill_request.slaughter_house.name
                    else:
                        kill_place = kill.killhouse_user.name
                    if kill.clearance_code:
                        l += 1
                        list1 = [
                            m,
                            str(kill.bar_code),
                            kill.province_request.poultry_request.poultry.unit_name,
                            str(kill.province_request.poultry_request.poultry.user.mobile),
                            kill.province_request.poultry_request.order_code,
                            kill.province_request.poultry_request.poultry.user.city.name,
                            str(date_of_poultry_request),
                            kill.province_request.poultry_request.chicken_breed,
                            vet_farm_name,
                            vet_farm_mobile,
                            kill.kill_request.kill_house.name,
                            kill.killhouse_user.phone,
                            killers,
                            kill.killhouse_user.system_address.city.name,
                            kill_place,
                            kill_house_vet_name,
                            kill_house_vet_mobile,
                            code,
                            quantity,
                            real_quantity,
                            net_weighte,
                            str(date_of_inner_bar),

                        ]
                        m += 1
                        for item in range(len(list1)):
                            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                            cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'دامپزشک کشتارگاه':

            worksheet['A1'] = f'دامپزشک کشتارگاه'
            worksheet['A3'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:C1'
            merge_range2 = 'A2:C2'
            merge_range = 'A3:C3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)

            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__poultry__user',
                'province_request__poultry_request',
                'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
                'kill_request__slaughter_house').only('killhouse_user',
                                                      'killhouse_user__name',
                                                      'killhouse_user__kill_house_operator__user__mobile',
                                                      'killhouse_user__system_address__city__name',
                                                      'killhouse_user__killer',
                                                      'kill_request__slaughter_house',
                                                      'kill_request__slaughter_house__name',
                                                      'province_request__poultry_request__poultry',
                                                      'province_request__poultry_request__order_code',
                                                      'province_request__poultry_request__chicken_breed',
                                                      'province_request__poultry_request__poultry__user__city__name',
                                                      'province_request__poultry_request__poultry__unit_name',
                                                      'province_request__poultry_request__poultry__user__mobile',
                                                      'province_request__poultry_request__send_date',
                                                      'province_kill_request__province_request__poultry_request__Index_weight',
                                                      'add_car__driver__driver_name',
                                                      'add_car__driver__driver_mobile',
                                                      'add_car__driver__type_car',
                                                      'add_car__driver__health_code',
                                                      'key',
                                                      'clearance_code',
                                                      'quantity',
                                                      'bar_code',
                                                      'accepted_real_weight',
                                                      'vet_state').values(
                'killhouse_user',
                'killhouse_user__name',
                'killhouse_user__kill_house_operator__user__mobile',
                'killhouse_user__system_address__city__name',
                'killhouse_user__killer',
                'kill_request__slaughter_house',
                'kill_request__slaughter_house__name',
                'province_request__poultry_request__poultry',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__chicken_breed',
                'province_request__poultry_request__poultry__user__city__name',
                'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__send_date',
                'add_car__driver__driver_name',
                'add_car__driver__driver_mobile',
                'add_car__driver__type_car',
                'add_car__driver__health_code',
                'key',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'bar_code',
                'accepted_real_weight',
                'vet_state',
            )
            header_list = [
                'تعداد بارایجاد شده',
                'مجموع تعداد قطعه تخصیصی',
                'مجموع وزن بار تخصیصی',
                'تعداد بار تخلیه شده',
                'مجموع تعداد قطعه تخلیه شده',
                'مجموع وزن بار تخلیه شده',
            ]
            for col_num, option in enumerate(header_list, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8

            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_assigment = 0
            if filtered_kill_reqs:
                for kill in filtered_kill_reqs:
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        all_assigment += len(assignment)
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = jdatetime.date.fromgregorian(
                            day=vet_check_date.day,
                            month=vet_check_date.month,
                            year=vet_check_date.year
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')

                        date_of_inner_bar = jdatetime.date.fromgregorian(
                            day=vet_check_date.day,
                            month=vet_check_date.month,
                            year=vet_check_date.year
                        )
                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    if kill.get('vet_state') == 'pending':
                        weight = kill.get('quantity') * kill.get(
                            'province_kill_request__province_request__poultry_request__Index_weight')
                        all_weighte += weight
                    else:

                        weight = kill.get('accepted_real_weight')
                        all_weighte += weight
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        kill.get('province_request__poultry_request__order_code'),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        kill.get('add_car__driver__health_code'),
                        code,
                        quantity,
                        weight,
                        str(date_of_inner_bar),
                        real_quantity,
                        net_weighte,

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')
            value_header_list = [
                len(filtered_kill_reqs),
                all_quantity,
                all_weighte,
                all_assigment,
                all_real_quantity,
                all_net_weighte

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list[item])
                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

        elif sheet_name == 'اطلاعات کلی پخش به مباشر':
            header_list = [
                'تعداد خریداران',
                'تعداد مباشرین',
                'تعداد لاشه ها',
                'وزن لاشه ها (کیلوگرم)',
                'تعداد لاشه تخصیص داده شده',
                'وزن تخصیص داده شده (کیلوگرم)',
                'تعداد لاشه قابل تخصیص',
                'وزن قابل تخصیص (کیلوگرم)',

            ]
            for col_num, option in enumerate(header_list, 3):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 17
                worksheet.column_dimensions[col_letter].width = 21.01

            value_header_list = [
                len(kill_house_ware_houses),
                len(steward_allocations),
                total_number_of_carcasses if total_number_of_carcasses != None else 0,
                total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                allocated_total_number_of_carcasses if allocated_total_number_of_carcasses != None else 0,
                allocated_total_weight_of_carcasses if allocated_total_weight_of_carcasses != None else 0,
                remain_total_number_of_carcasses if remain_total_number_of_carcasses != None else 0,
                remain_total_weight_of_carcasses if remain_total_weight_of_carcasses != None else 0,
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 3, value=value_header_list[item])
                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=11)
            m = 1

            for kill_house in kill_house_list:
                kill_house_ware_house = KillHouseWareHouse.objects.filter(kill_house=kill_house,
                                                                          date__date__gte=date1,
                                                                          date__date__lte=date2)
                for kill_house_ware in kill_house_ware_house:
                    total_number_of_carcasses_temp = kill_house_ware.update_total_number_of_carcasses if kill_house_ware.update_total_number_of_carcasses > 0 else kill_house_ware.total_number_of_carcasses
                    total_weight_of_carcasses_temp = kill_house_ware.update_total_weight_of_carcasses if kill_house_ware.update_total_weight_of_carcasses > 0 else kill_house_ware.total_weight_of_carcasses

                    date_of_create = jdatetime.date.fromgregorian(
                        day=kill_house_ware.date.day,
                        month=kill_house_ware.date.month,
                        year=kill_house_ware.date.year
                    )
                    list1 = [
                        m,
                        'کشتار کن' if kill_house.killer == True else 'کشتارگاه',
                        f'{kill_house.name} ({kill_house.kill_house_operator.user.fullname})',
                        str(date_of_create),
                        kill_house.kill_house_operator.user.mobile,
                        kill_house.kill_house_operator.address.city.name,
                        total_number_of_carcasses_temp,
                        total_weight_of_carcasses_temp,
                        kill_house_ware.allocated_total_number_of_carcasses,
                        kill_house_ware.allocated_total_weight_of_carcasses,
                        kill_house_ware.remain_total_number_of_carcasses,
                        kill_house_ware.remain_total_weight_of_carcasses

                    ]
                    m += 1
                    l += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        cell.alignment = Alignment(horizontal='center')

        elif sheet_name == 'جزئیات پخش به مباشر':
            for steward_allocation in steward_allocations:
                killer = 'کشتارکن' if steward_allocation.kill_house.killer == True else 'کشتارگاه'
                kill_house_name = steward_allocation.kill_house.name

                date = jdatetime.date.fromgregorian(
                    year=steward_allocation.date.year,
                    month=steward_allocation.date.month,
                    day=steward_allocation.date.day
                )
                steward = 'مباشر' if steward_allocation.seller_type == 'steward' else 'صنف'
                sell_type = 'اختصاصی' if steward_allocation.sell_type == 'exclusive' else 'آزاد'
                type = 'دستی' if steward_allocation.type == 'manual' else 'اتوماتیک'
                try:
                    guilds_name = steward_allocation.steward.guilds.guilds_name
                    guilds_id = steward_allocation.steward.guilds.guilds_id
                    fullname = steward_allocation.steward.guilds.user.fullname
                    national_id = steward_allocation.steward.guilds.user.national_id
                    mobile = steward_allocation.steward.guilds.user.mobile
                    type_activity = steward_allocation.steward.guilds.type_activity
                    area_activity = steward_allocation.steward.guilds.area_activity
                    license_number = steward_allocation.steward.guilds.license_number
                    city_name = steward_allocation.steward.guilds.address.city.name
                except:
                    guilds_name = steward_allocation.guilds.guilds_name
                    guilds_id = steward_allocation.guilds.guilds_id
                    fullname = steward_allocation.guilds.user.fullname
                    national_id = steward_allocation.guilds.user.national_id
                    mobile = steward_allocation.guilds.user.mobile
                    type_activity = steward_allocation.guilds.type_activity
                    area_activity = steward_allocation.guilds.area_activity
                    license_number = steward_allocation.guilds.license_number
                    city_name = steward_allocation.guilds.address.city.name
                register = steward_allocation.logged_registration_code if steward_allocation.logged_registration_code else '-'
                list1 = [
                    m,
                    f'{killer} {kill_house_name}({steward_allocation.kill_house.kill_house_operator.user.fullname})',
                    guilds_id,
                    str(date),
                    steward,
                    f'{sell_type}({type})',
                    guilds_name,
                    fullname,
                    national_id,
                    mobile,
                    type_activity,
                    area_activity,
                    license_number,
                    city_name,
                    steward_allocation.number_of_carcasses,
                    steward_allocation.weight_of_carcasses,
                    register,
                ]
                l += 1
                m += 1
                for col_num, option in enumerate(list1, 1):
                    col_letter = get_column_letter(col_num)
                    cell = worksheet.cell(row=l + 1, column=col_num, value=option)
                    cell.alignment = Alignment(horizontal='center', vertical='center')

                    worksheet.row_dimensions[4].height = 19
                    worksheet.column_dimensions[col_letter].width = 21.01

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="روند کشتار بر اساس بازه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    poultry_reqs = PoultryRequest.objects.filter(
        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')),

    )
    if request.GET['role'] == 'CityOperator':
        city_operator = CityOperator.objects.get(trash=False, user=user)
        poultry_requests = poultry_reqs.filter(poultry__city_operator=city_operator.unit_name)
    elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
        poultry_requests = poultry_reqs.filter(poultry__user__city=user.city)
    else:
        poultry_requests = poultry_reqs
    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_operator = ProvinceOperator.objects.filter(
        user=SystemUserProfile.objects.get(role__name='ProvinceOperator', province=user.province),
        trash=False).select_related(
        'user').first()

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    excel_options = {
        'مغایرت در تخصیص و ایجاد بار': [
            'ردیف',
            'خریدار',
            'تلفن',
            'تاریخ کشتار',
            'فروشنده',
            'تلفن فروشنده',
            'سهم کشتار(قطعه)',
            'سهم کشتار(وزن)',
            'تعداد ماشین'
            , 'تخصیص به ماشین(قطعه)'
            , 'تخصیص به ماشین(وزن)'
            , 'مانده قطعه قابل تخصیصی'
            , 'مانده وزن قابل تخصیصی(کیلوگرم)'
            , 'اپراتور'
            , 'موبایل اپراتور'
        ],

        'بار های فاقد کد قرنطینه': ['ردیف',
                                    'کدبار',
                                    'خریدار',
                                    'تلفن خریدار',
                                    'فروشنده',
                                    'تلفن فروشنده',
                                    'تاریخ کشتار',
                                    'ماشین',
                                    'راننده',
                                    'نژاد',
                                    'تعداد(قطعه)',
                                    'وزن بار(کیلوگرم)',
                                    'میانگین وزن(کیلوگرم)',
                                    'محل کشتار',
                                    'دامپزشک',
                                    'موبایل دامپزشک'],
        'بارهای تخلیه نشده': [
            'ردیف',
            'کد بار',
            'خریدار',
            ' تلفن خریدار',
            'فروشنده',
            ' تلفن فروشنده',
            'تاریخ کشتار',
            'ماشین',
            'راننده',
            'نژاد',
            'تعداد(قطعه)',
            'وزن بار(کیلوگرم)',
            'میانگین وزن(کیلوگرم)',
            'کد قرنطینه',
            'دامپزشک',
            'تلفن دامپزشک',
        ],
        'بارهای تکمیل نشده': [
            'ردیف',
            'کدبار',
            'خریدار',
            ' تلفن خریدار',
            'فروشنده',
            ' تلفن فروشنده',
            'تاریخ کشتار',
            'ماشین',
            'راننده',
            'نژاد',
            'تعداد(قطعه)',
            'وزن بار(کیلوگرم)',
            'میانگین وزن(کیلوگرم)',
            'کد قرنطینه',
            'تعداد تخلیه شده(دامپزشک)',
            'وزن تخلیه شده(دامپزشک)',
            'کاربر',
            'تلفن کاربر',
        ],
        'مغایرت در اطلاعات بار': [
            'ردیف',
            'کدبار',
            'خریدار',
            ' تلفن خریدار',
            'فروشنده',
            ' تلفن فروشنده',
            'تاریخ کشتار',
            'ماشین',
            'راننده',
            'کد قرنطینه',
            'تعداد اولیه(قطعه)',
            'وزن بار اولیه (کیلوگرم)',
            'تعداد تخلیه شده(دامپزشک)',
            'وزن تخلیه شده(دامپزشک)',
            'اطلاعات بار کشتارگاه(تعداد)',
            'اطلاعات بار کشتارگاه(وزن)',

        ]

    }
    kill_house = KillHouseRequest.objects.filter(
        province_kill_request__in=province_kill_requests,
        trash=False)
    output = BytesIO()
    workbook = Workbook()
    for name, options in excel_options.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        red_font = Font(color="C00000", bold=True)

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=5, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            if len(option) > worksheet.column_dimensions[col_letter].width:
                worksheet.column_dimensions[col_letter].width = len(option)
                # worksheet.column_dimensions[col_letter].height = len(option)
            worksheet.row_dimensions[5].height = 20

            worksheet.freeze_panes = worksheet['A6']
            max_col = worksheet.max_column
            range_str = f'A5:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        l = 4
        m = 1
        if sheet_name == 'مغایرت در تخصیص و ایجاد بار':
            worksheet['A4'] = f'مغایرت درتعداد تخصیصی به خریدار و ایجاد بار'
            worksheet['A2'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['D1'] = f'مغایرت در درخواست کشتار و تخصیص'
            worksheet['A4'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['D1'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            merge_range1 = 'A2:C2'
            merge_range2 = 'D1:E1'
            merge_range = 'A4:C4'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A4'].fill = PatternFill(start_color="C5D9F1", fill_type="solid")
            worksheet['D1'].fill = PatternFill(start_color="C5D9F1", fill_type="solid")
            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).select_related('killhouse_user',
                                                                                  'killhouse_user__kill_house_operator__user',
                                                                                  'province_request__poultry_request').only(
                'key', 'killhouse_user__name', 'killhouse_user__kill_house_operator__user__mobile', 'main_quantity',
                'province_request__poultry_request__Index_weight', 'quantity',
                'killhouse_user__kill_house_operator__user__fullname',
                'killhouse_user__kill_house_operator__user__mobile', 'province_request__poultry_request__key')
                                                     .values('province_request__poultry_request__poultry__user__mobile',
                                                             'province_request__poultry_request__poultry__unit_name',
                                                             'key', 'killhouse_user__name',
                                                             'killhouse_user__kill_house_operator__user__mobile',
                                                             'main_quantity',
                                                             'province_request__poultry_request__Index_weight',
                                                             'quantity',
                                                             'killhouse_user__kill_house_operator__user__fullname'
                                                             , 'killhouse_user__kill_house_operator__user__mobile',
                                                             'province_request__poultry_request__key',
                                                             'province_request__poultry_request__poultry__unit_name',
                                                             'province_request__poultry_request__poultry__user__mobile'))

            poultry_request_total_quantity = poultry_requests.aggregate(total=Sum('total_quantity'))['total']
            poultry_request_total_weight = poultry_requests.aggregate(total=Sum('total_weight'))['total']
            province_kill_requests_total_weight = province_kill_requests.aggregate(total=Sum('total_weight'))['total']
            province_kill_requests_total_quantity = province_kill_requests.aggregate(total=Sum('total_quantity'))[
                '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']

            for province in province_kill_requests_with_left_over:
                poultry_request = PoultryRequest.objects.get(
                    key=province['province_request__poultry_request__key'])
                date_of_kill = jdatetime.date.fromgregorian(
                    day=poultry_request.send_date.day,
                    month=poultry_request.send_date.month,
                    year=poultry_request.send_date.year
                )
                kill_house_requests = kill_house.filter(province_kill_request__key=province[
                    'key']).annotate(
                    total_quantity=Sum('accepted_real_quantity'),
                    total_weight=Sum('accepted_real_weight'),

                )
                kill_house_request_quantity = kill_house_requests.aggregate(total=Sum('total_quantity'))['total']
                kill_house_request_weight = kill_house_requests.aggregate(total=Sum('total_weight'))['total']
                list1 = [
                    m,
                    province['killhouse_user__name'],
                    province['killhouse_user__kill_house_operator__user__mobile'],
                    str(date_of_kill),
                    province['province_request__poultry_request__poultry__unit_name'],
                    province['province_request__poultry_request__poultry__user__mobile'],
                    province['main_quantity'],
                    int(province['main_quantity'] * province['province_request__poultry_request__Index_weight']),
                    kill_house_requests.count(),
                    kill_house_request_quantity if kill_house_request_quantity != None else 0,
                    kill_house_request_weight if kill_house_request_weight != None else 0,
                    province['quantity'],
                    int(province['quantity'] * province['province_request__poultry_request__Index_weight']),
                    province['killhouse_user__kill_house_operator__user__fullname'],
                    province['killhouse_user__kill_house_operator__user__mobile'],
                ]
                m += 1
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    blue = Font(color="0070C0")
                    red = Font(color="C00000")
                    green = Font(color="00863D")

                    if cell.column in [7, 8]:
                        cell.font = blue

                    elif cell.column in [10, 11]:
                        cell.font = green
                    else:
                        if cell.column in [12, 13]:
                            cell.font = red
                    value = list1[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'
                    else:
                        cell.value = value
            header_list = [
                'تعداد درخواست',
                'مجموع درخواست کشتار (قطعه)',
                'مجموع درخواست کشتار (وزن)',
                'تعداد تخصیص به خریدار(قطعه)',
                'وزن تخصیص به خریدار(کیلوگرم)',
                'مانده قطعه قابل تخصیص',
                'وزن قابل تخصیص(کیلوگرم)',
                'اپراتور',
                ' موبایل اپراتور',
            ]
            for col_num, option in enumerate(header_list, 4):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 17
                worksheet.column_dimensions[col_letter].width = 21.01

            value_header_list = [
                poultry_requests.count(),
                poultry_request_total_quantity if poultry_request_total_quantity != None else 0,
                poultry_request_total_weight if poultry_request_total_weight != None else 0,
                province_kill_requests_total_quantity if province_kill_requests_total_quantity != None else 0,
                province_kill_requests_total_weight if province_kill_requests_total_weight != None else 0,
                poultry_request_total_remain_quantity if poultry_request_total_remain_quantity != None else 0,
                poultry_request_remain_weight if poultry_request_remain_weight != None else 0,
                province_operator.user.fullname,
                province_operator.user.mobile,

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 4, value=value_header_list[item])
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=11)
                worksheet['G3'].font = Font(color="0070C0", bold=True)
                worksheet['H3'].font = Font(color="0070C0", bold=True)
                worksheet['I3'].font = red_font
                worksheet['J3'].font = red_font
                value = value_header_list[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'
                else:
                    cell.value = value

        elif sheet_name == 'بار های فاقد کد قرنطینه':
            worksheet['A2'] = f'بار های فاقد کد قرنطینه'
            worksheet['A4'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['A4'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            merge_range1 = 'A2:C2'
            merge_range = 'A4:C4'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet['A2'].fill = PatternFill(start_color="92CDDC", fill_type="solid")

            kill_house_request_without_clearance_code = (kill_house.filter(
                clearance_code__isnull=True,
            ).select_related('add_car__driver',
                             'province_kill_request__province_request__poultry_request',
                             'province_kill_request__province_request__poultry_request__poultry',
                             'killhouse_user__kill_house_operator__user', 'kill_request')
                .only(
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'killhouse_user__name',
                'kill_request__kill_house__name')
                .values(
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name',
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'killhouse_user__name',
                'kill_request__kill_house__name', 'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile'))

            for kill in kill_house_request_without_clearance_code:

                fullname = '-',
                mobile = '-',
                poultry_request = PoultryRequest.objects.get(
                    key=kill['province_kill_request__province_request__poultry_request__key'])
                date_of_kill = jdatetime.date.fromgregorian(
                    day=poultry_request.send_date.day,
                    month=poultry_request.send_date.month,
                    year=poultry_request.send_date.year
                )
                vet_farm = (VetFarm.objects.filter(
                    poultry=kill['province_kill_request__province_request__poultry_request__poultry'])
                            .select_related('vet__user').only('vet__user__fullname', 'vet__user__mobile').last())
                if vet_farm:
                    fullname = vet_farm.vet.user.fullname
                    mobile = vet_farm.vet.user.mobile
                else:
                    fullname = '-'
                    mobile = '-'

                list1 = [
                    m,
                    str(kill['bar_code']),
                    kill['killhouse_user__name'],
                    kill['killhouse_user__kill_house_operator__user__mobile'],
                    kill['province_request__poultry_request__poultry__unit_name'],
                    kill['province_request__poultry_request__poultry__user__mobile'],
                    str(date_of_kill),
                    kill['add_car__driver__type_car'],
                    kill['add_car__driver__driver_name'],
                    poultry_request.chicken_breed,
                    kill['quantity'],
                    kill['accepted_real_weight'],
                    round(kill['accepted_real_weight'] / kill['accepted_real_quantity'], 1),
                    kill['kill_request__slaughter_house__name'] if kill['kill_request__slaughter_house'] != None else
                    kill['kill_request__kill_house__name'],
                    fullname,
                    mobile,
                ]
                m += 1
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    value = list1[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'
                    else:
                        cell.value = value
        elif sheet_name == 'بارهای تخلیه نشده':
            worksheet['A2'] = f'بارهای تخلیه نشده'
            worksheet['A4'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['A4'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            merge_range1 = 'A2:C2'
            merge_range = 'A4:C4'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet['A2'].fill = PatternFill(start_color="E26B0A", fill_type="solid")

            kill_house_request_without_vet_check = kill_house.filter(vet_state='pending').select_related(
                'add_car__driver',
                'province_kill_request__province_request__poultry_request',
                'province_kill_request__province_request__poultry_request__poultry',
                'killhouse_user__kill_house_operator__user').only(
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name',
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'kill_request__key',
                'clearance_code', 'killhouse_user__name').values(
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'kill_request__key',
                'clearance_code', 'killhouse_user__name', 'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name')

            for kill in kill_house_request_without_vet_check:

                poultry_request = PoultryRequest.objects.get(
                    key=kill['province_kill_request__province_request__poultry_request__key'])
                date_of_kill = jdatetime.date.fromgregorian(
                    day=poultry_request.send_date.day,
                    month=poultry_request.send_date.month,
                    year=poultry_request.send_date.year
                )
                kill_request = KillRequest.objects.get(key=kill['kill_request__key'])
                if kill_request.slaughter_house != None:
                    kill_house_vet = KillHouseVet.objects.filter(
                        kill_house=kill_request.slaughter_house).select_related(
                        'vet__user').first()
                else:
                    kill_house_vet = KillHouseVet.objects.filter(kill_house=kill_request.kill_house).select_related(
                        'vet__user').first()
                if kill_house_vet:
                    fullname = kill_house_vet.vet.user.fullname
                    mobile = kill_house_vet.vet.user.mobile
                else:
                    fullname = '-'
                    mobile = '-'
                list1 = [
                    m,
                    str(kill['bar_code']),
                    kill['killhouse_user__name'],
                    kill['killhouse_user__kill_house_operator__user__mobile'],
                    kill['province_request__poultry_request__poultry__unit_name'],
                    kill['province_request__poultry_request__poultry__user__mobile'],
                    str(date_of_kill),
                    kill['add_car__driver__type_car'],
                    kill['add_car__driver__driver_name'],
                    poultry_request.chicken_breed,
                    kill['quantity'],
                    kill['accepted_real_weight'],
                    round(kill['accepted_real_weight'] / kill['accepted_real_quantity'], 1),
                    kill['clearance_code'] if kill['clearance_code'] else '-',
                    fullname,
                    mobile,

                ]
                m += 1
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    value = list1[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'
                    else:
                        cell.value = value
        elif sheet_name == 'بارهای تکمیل نشده':
            worksheet['A2'] = f'بارهای تکمیل نشده(بارگزاری سند باسکول و مستندات وزنی)'
            worksheet['A4'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['A4'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            merge_range1 = 'A2:E2'
            merge_range = 'A4:C4'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet['A2'].fill = PatternFill(start_color="FFFF00", fill_type="solid")

            kill_house_request_without_bar_info = kill_house.filter(
                vet_state='accepted',
                assignment_state_archive='pending',
            ).select_related('add_car__driver',
                             'province_kill_request__province_request__poultry_request',
                             'province_kill_request__province_request__poultry_request__poultry',
                             'killhouse_user__kill_house_operator__user', 'kill_request').only(
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'kill_request__key',
                'clearance_code', 'killhouse_user__name', 'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name').values(
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'kill_request__key',
                'clearance_code', 'killhouse_user__name', 'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name')

            for kill in kill_house_request_without_bar_info:
                poultry_request = PoultryRequest.objects.get(
                    key=kill['province_kill_request__province_request__poultry_request__key'])
                date_of_kill = jdatetime.date.fromgregorian(
                    day=poultry_request.send_date.day,
                    month=poultry_request.send_date.month,
                    year=poultry_request.send_date.year
                )
                kill_request = KillRequest.objects.get(key=kill['kill_request__key'])
                if kill_request.slaughter_house != None:
                    kill_house_vet = KillHouseVet.objects.filter(
                        kill_house=kill_request.slaughter_house).select_related(
                        'vet__user').first()
                else:
                    kill_house_vet = KillHouseVet.objects.filter(kill_house=kill_request.kill_house).select_related(
                        'vet__user').first()
                if kill_house_vet:
                    fullname = kill_house_vet.vet.user.fullname
                    mobile = kill_house_vet.vet.user.mobile
                else:
                    fullname = '-'
                    mobile = '-'
                list1 = [
                    m,
                    str(kill['bar_code']),
                    kill['killhouse_user__name'],
                    kill['killhouse_user__kill_house_operator__user__mobile'],
                    kill['province_request__poultry_request__poultry__unit_name'],
                    kill['province_request__poultry_request__poultry__user__mobile'],
                    str(date_of_kill),
                    kill['add_car__driver__type_car'],
                    kill['add_car__driver__driver_name'],
                    poultry_request.chicken_breed,
                    kill['quantity'],
                    kill['accepted_real_weight'],
                    round(kill['accepted_real_weight'] / kill['accepted_real_quantity'], 1),
                    kill['clearance_code'] if kill['clearance_code'] else '-',
                    kill['accepted_real_quantity'],
                    kill['accepted_real_weight'],
                    fullname,
                    mobile

                ]

                m += 1
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    blue = Font(color="0070C0")
                    red = Font(color="C00000")
                    if cell.column in [11, 12]:
                        cell.font = blue
                    else:
                        if cell.column in [15, 16]:
                            cell.font = red
                    value = list1[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'
                    else:
                        cell.value = value
        elif sheet_name == 'مغایرت در اطلاعات بار':
            worksheet['A2'] = f'بارهای تکمیل نشده(بارگزاری سند باسکول و مستندات وزنی)'
            worksheet['A4'] = f'در تاریخ:({from_date_1}) تا تاریخ:({to_date_1})'
            worksheet['A4'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            merge_range1 = 'A2:E2'
            merge_range = 'A4:C4'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet['A2'].fill = PatternFill(start_color="92D050", fill_type="solid")

            kill_house_request_diffrent_bar_info = kill_house.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')),
                vet_state='accepted', assignment_state_archive='True',
            ).select_related('add_car__driver',
                             'province_kill_request__province_request__poultry_request',
                             'province_kill_request__province_request__poultry_request__poultry',
                             'killhouse_user__kill_house_operator__user', 'kill_request').only(
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'kill_request__key',
                'clearance_code', 'killhouse_user__name', 'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name', 'vet_accepted_real_quantity',
                'vet_accepted_real_weight').values(
                'key',
                'province_request__poultry_request__Index_weight',
                'province_kill_request__province_request__poultry_request__key',
                'province_kill_request__province_request__poultry_request__poultry',
                'bar_code', 'killhouse_user__kill_house_operator__user__mobile',
                'add_car__driver__type_car',
                'add_car__driver__driver_name', 'quantity', 'accepted_real_quantity', 'accepted_real_weight',
                'kill_request__slaughter_house__name', 'kill_request__slaughter_house', 'kill_request__key',
                'clearance_code', 'killhouse_user__name', 'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__poultry__unit_name', 'vet_accepted_real_quantity',
                'vet_accepted_real_weight')

            for kill in kill_house_request_diffrent_bar_info:
                assignment_info = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request__key=kill['key']).first()
                if assignment_info:
                    assingment_quantity = assignment_info.real_quantity
                    assingment_weight = assignment_info.net_weight
                else:
                    assingment_quantity = 0
                    assingment_weight = 0
                kill_house_vet_quantity = kill['vet_accepted_real_quantity']
                kill_house_vet_weight = kill['vet_accepted_real_weight']
                quantity = kill['quantity']
                weight = int(kill['quantity'] * kill['province_request__poultry_request__Index_weight'])

                poultry_request = PoultryRequest.objects.get(
                    key=kill['province_kill_request__province_request__poultry_request__key'])
                date_of_kill = jdatetime.date.fromgregorian(
                    day=poultry_request.send_date.day,
                    month=poultry_request.send_date.month,
                    year=poultry_request.send_date.year
                )
                list1 = [
                    m,
                    str(kill['bar_code']),
                    kill['killhouse_user__name'],
                    kill['killhouse_user__kill_house_operator__user__mobile'],
                    kill['province_request__poultry_request__poultry__unit_name'],
                    kill['province_request__poultry_request__poultry__user__mobile'],
                    str(date_of_kill),
                    kill['add_car__driver__type_car'],
                    kill['add_car__driver__driver_name'],
                    kill['clearance_code'] if kill['clearance_code'] else '-',
                    quantity,
                    weight,
                    kill_house_vet_quantity,
                    int(kill_house_vet_weight),
                    assingment_quantity,
                    assingment_weight
                ]

                m += 1
                l += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    blue = Font(color="0070C0")
                    red = Font(color="C00000")
                    orange = Font(color="F47914")

                    if cell.column in [11, 12]:
                        cell.font = blue

                    elif cell.column in [13, 14]:
                        cell.font = orange
                    else:
                        if cell.column in [15, 16]:
                            cell.font = red
                    value = list1[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'
                    else:
                        cell.value = value

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش مغایرت اطلاعات کشتار و عدم فعالیت نقش ها.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def bar_for_each_persion_excel(request):
    # date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    # date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()

    kill = KillHouseRequest.objects.filter(trash=False, bar_code=request.GET['code']).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('killhouse_user',
                                              'killhouse_user__name',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity').values(
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
    ).first()

    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد وارد شده در قرنطینه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد (کشتارگاه)',
        'وزن بار (کشتارگاه)',

    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=4, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[4].height = 19
        worksheet.freeze_panes = worksheet['A5']
        max_col = worksheet.max_column
        range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    name = kill['killhouse_user__name']
    worksheet['B1'] = f'مدیریت بارهای کشتارگاه {name}'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)

    l = 4
    m = 1

    date_of_inner_bar = '-'
    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                      trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                    'vet__user__mobile').values(
        'vet__user__fullname',
        'vet__user__mobile').first()
    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
        'vet__user').only('vet__user__fullname',
                          'vet__user__mobile').values('vet__user__fullname',
                                                      'vet__user__mobile').first()
    vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
        'create_date').values(
        'create_date').first()
    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
    if kill.get('quantity'):
        quantity = kill.get('quantity')

    else:
        quantity = '-'
    send_date = kill.get('province_request__poultry_request__send_date')
    date_of_poultry_request = jdatetime.date.fromgregorian(
        day=send_date.day,
        month=send_date.month,
        year=send_date.year
    )
    killers = 'کشتارکن'
    if kill.get('killhouse_user__killer') == False:
        killers = 'کشتارگاه'
    assignment = KillHouseAssignmentInformation.objects.filter(
        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                   'real_quantity').values(
        'net_weight', 'real_quantity', 'create_date').first()
    if assignment:
        net_weighte = assignment.get('net_weight')

        real_quantity = assignment.get('real_quantity')

        vet_check_date = assignment.get('create_date')
        date_of_inner_bar = convert_to_shamsi(
            datetime=vet_check_date
        )
    else:
        net_weighte = '-'
        real_quantity = '-'
    if vet_checks:
        vet_check_date = vet_checks.get('create_date')
        date_of_inner_bar = convert_to_shamsi(
            datetime=vet_check_date
        )

    if kill.get('kill_request__slaughter_house') is not None:
        kill_place = kill.get('kill_request__slaughter_house__name')
    else:
        kill_place = '-'

    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

    weight = kill.get('quantity') * kill.get(
        'province_kill_request__province_request__poultry_request__Index_weight')
    quarantine_quantity = kill['quarantine_quantity'] if kill['quarantine_quantity'] != None else '-'
    list1 = [
        '1',
        str(kill.get('bar_code')),
        str(date_of_poultry_request),
        str(kill.get('province_request__poultry_request__order_code')),
        kill.get('province_request__poultry_request__poultry__unit_name'),
        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
        kill.get('province_request__poultry_request__poultry__user__city__name'),
        kill.get('province_request__poultry_request__chicken_breed'),
        vet_farm_name,
        vet_farm_mobile,
        killers,
        kill.get('killhouse_user__name'),
        kill.get('killhouse_user__kill_house_operator__user__mobile'),
        kill.get('killhouse_user__system_address__city__name'),
        kill_place,
        kill_house_vet_name,
        kill_house_vet_mobile,
        kill.get('add_car__driver__driver_name'),
        kill.get('add_car__driver__driver_mobile'),
        kill.get('add_car__driver__type_car'),
        str(kill.get('add_car__driver__health_code')),
        quantity,
        weight,
        code,
        quarantine_quantity,
        str(date_of_inner_bar),
        vet_quantity,
        vet_wight,
        real_quantity,
        net_weighte,

    ]
    m += 1
    for item in range(len(list1)):
        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
        value = list1[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای کشتارگاه {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def poultry_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    filtered_poultry_reqs = PoultryRequest.objects.filter(
        trash=False,
        send_date__date__gte=date1,
        send_date__date__lte=date2
    ).select_related('poultry', 'poultry__user', 'hatching', 'poultry__user__city').only('remain_quantity', 'amount',
                                                                                         'key', 'poultry',
                                                                                         'send_date',
                                                                                         'hatching__date',
                                                                                         'create_date', 'order_code',
                                                                                         'poultry__unit_name',
                                                                                         'poultry__user__fullname',
                                                                                         'poultry__user__mobile',
                                                                                         'poultry__user__city__name',
                                                                                         'hatching__quantity',
                                                                                         'quantity',
                                                                                         'hatching__left_over',
                                                                                         'hatching__chicken_breed',
                                                                                         'poultry__address__province__name',
                                                                                         'Index_weight',
                                                                                         'hatching__quantity').values(
        'key', 'poultry', 'remain_quantity',
        'send_date',
        'hatching__date',
        'create_date', 'order_code',
        'poultry__unit_name',
        'poultry__user__fullname',
        'poultry__user__mobile',
        'poultry__user__city__name',
        'hatching__quantity',
        'quantity',
        'hatching__left_over',
        'hatching__chicken_breed', 'poultry__address__province__name', 'Index_weight', 'amount',
        'hatching__quantity').order_by(
        '-send_date')
    len_province_request = len(ProvinceKillRequest.objects.filter(
        province_request__poultry_request__key__in=filtered_poultry_reqs.values('key'), trash=False,
        state__in=('pending', 'accepted')))
    excel_options = [
        'ردیف',
        'کد سفارش',
        'نام واحد',
        'نام و نام خانوادگی مرغدار',
        'موبایل',
        'آدرس',
        'تاریخ جوجه ریزی',
        'تعداد کل جوجه ریزی',
        'سن مرغ',
        'تعداد درخواست کشتار',
        'وزن درخواست کشتار',
        'میانگین وزنی',
        'قیمت مرغ زنده',
        'تعداد تخصیصی به خریدار',
        'مانده قابل تخصیص',
        'تعداد قطعه باقی مانده در سالن',
        'نژاد',
        'تاریخ درخواست کشتار',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        'وضعیت درخواست',
        'خریدار',
        'تعداد تخصیصی قطعه',
        'وزن تخصیصی',
        'تاریخ تخصیص',
        'آدرس',
        'محل کشتار',
        'وضعییت تخصیص به خریدار',
        'تعداد بار ایجاد شده',
        'تعداد قطعه تخصیصی به بار',
        'وزن تخصیصی به بار',
        'مانده قطعه قابل تخصیص',
        'مانده وزن قابل تخصیص',
        'ماشین',
        'راننده',
        'تلفن',
        'کد بهداشتی حمل و نقل',
        'کد رهگیری سامانه قرنطینه',
        'تعداد ثبت شده در قرنطینه',
        'تعداد قطعه بار',
        'وزن بار',
        'وضعیت بار',
        'تعداد تخلیه',
        'وزن تخلیه',
        'تاریخ تخلیه کشتارگاه',
        'دامپزشک کشتارگاه',
        'تلفن دامپزشک کشتارگاه',
        'اطلاعات تکمیلی قطعه',
        'اطلاعات تکمیلی وزن',
        'کاربر کشتارگاه',
        'تلفن کاربرکشتارگاه',
    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    header_list = [
        'تعداد درخواست های  کشتار',
        'مجموع  قطعه درخواست های کشتار',
        'مجموع وزن درخواست های کشتار',
        'تعداد تخصیص به خریداران',
        'تعداد قطعه تخصیصی به خریداران',
        'وزن تخصیصی به خریداران',
        'مانده قابل تخصیص',
        'تعداد بار ایجاد شده',
        'تعداد قطعه بار های ایجاد شده',
        'وزن بارهای ایجاد شده',
        'تعداد قطعه قابل تخصیص به بار',
        'تعداد بارهای تخلیه شده',
        'تعداد قطعه بارهای تخلیه شده',
        'وزن بارهای  تخلیه شده',
        'تعداد بار های تکمیل شده',
        'تعداد قطعه بارهای تکمیل شده',
        'وزن بارهای تکمیل شده',

    ]
    all_quantity = 0
    all_main_quantity = 0
    all_assignment_quantity = 0
    all_wight = 0
    all_wight_killer = 0
    sum_all_quantity_of_bar = 0
    sum_all_weight_of_bar = 0
    sum_all_remain_quantity_of_bar = 0
    vet_state_accepted = 0
    all_vet_quantity = 0
    all_vet_wight = 0
    all_assigment = 0
    all_assignment_weight = 0
    all_hatching = 0
    all_poultry_request_weight = 0
    all_hatching_left_over = 0
    all_reamin_province = 0
    all_qarantine = 0
    all_poultry_request = filtered_poultry_reqs.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_remain_quantity = filtered_poultry_reqs.aggregate(
        total_quantity=Sum('remain_quantity')).get(
        'total_quantity', 0)
    sum_province_to_kill_house = all_poultry_request - all_remain_quantity
    # برای بالای هدر
    for col_num, option in enumerate(header_list, 4):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 17
    if filtered_poultry_reqs.exists():
        province = filtered_poultry_reqs.first()['poultry__address__province__name']
        worksheet['A2'] = f' استان {province}'

    worksheet['A1'] = f'گزارش روند پرونده های  کشتار مرغ گوشتی'
    worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'A1:B1'
    merge_range2 = 'A2:B2'
    merge_range = 'A3:B3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['A1'].font = red_font
    worksheet['A3'].font = Font(size=11)
    m = 1
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 21.01
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 7
    bar_list = 0
    bar_list2 = 0
    for filtered_poultry_req in filtered_poultry_reqs:
        # print(filtered_poultry_req.get('poultry__unit_name'))
        all_poultry_request_weight += int(
            filtered_poultry_req.get('quantity') * filtered_poultry_req.get('Index_weight'))
        all_hatching += filtered_poultry_req['hatching__quantity']
        all_hatching_left_over += filtered_poultry_req['hatching__left_over']
        state_p = 'در انتظار تخصیص استان'
        if filtered_poultry_req.get('quantity') != filtered_poultry_req.get('remain_quantity'):
            state_p = 'تخصیص داده شد'
        all_wight += int(filtered_poultry_req.get('quantity') * filtered_poultry_req.get('Index_weight'))
        all_quantity += filtered_poultry_req.get('quantity')
        try:
            vet_farm = VetFarm.objects.get(poultry=filtered_poultry_req.get('poultry'), trash=False)
            vet_farm_name = vet_farm.vet.user.fullname
            vet_farm_mobile = vet_farm.vet.user.mobile
        except:
            vet_farm_name = '-'
            vet_farm_mobile = '-'

        age = (filtered_poultry_req.get('send_date').date() - filtered_poultry_req.get(
            "hatching__date").date()).days + 1
        gregorian_date = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.get("hatching__date").day,
            month=filtered_poultry_req.get("hatching__date").month,
            year=filtered_poultry_req.get("hatching__date").year
        )
        date_of_kill = jdatetime.date.fromgregorian(
            day=filtered_poultry_req.get('create_date').day,
            month=filtered_poultry_req.get('create_date').month,
            year=filtered_poultry_req.get('create_date').year
        )

        province_kill_reqs = ProvinceKillRequest.objects.filter(
            province_request__poultry_request__key=filtered_poultry_req.get('key'),
            trash=False).select_related(
            'kill_request__kill_house', 'killhouse_user__kill_house_operator',
            'killhouse_user__kill_house_operator__user', 'killhouse_user__kill_house_operator__address',
            'killhouse_user').only('kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'state',
                                   'key', 'create_date',
                                   'kill_request__kill_house', 'main_quantity', 'killhouse_user__name',
                                   'killhouse_user__kill_house_operator__user__mobile',
                                   'killhouse_user__kill_house_operator__address__city__name', 'killhouse_user__killer',
                                   'province_request__poultry_request__Index_weight', 'quantity').values(
            'kill_request__slaughter_house', 'kill_request__slaughter_house__name', 'key', 'create_date',
            'kill_request__kill_house',
            'main_quantity',
            'killhouse_user__name',
            'killhouse_user__killer',
            'killhouse_user__kill_house_operator__user__mobile',
            'killhouse_user__kill_house_operator__address__city__name',
            'province_request__poultry_request__Index_weight',
            'state', 'quantity')

        list1 = [
            m,
            filtered_poultry_req.get('order_code'),
            filtered_poultry_req.get('poultry__unit_name'),
            filtered_poultry_req.get('poultry__user__fullname'),
            filtered_poultry_req.get('poultry__user__mobile'),
            filtered_poultry_req.get('poultry__user__city__name'),
            str(gregorian_date),
            filtered_poultry_req.get('hatching__quantity'),
            str(age),
            filtered_poultry_req.get('quantity'),
            int(filtered_poultry_req.get('quantity') * filtered_poultry_req.get('Index_weight')),
            filtered_poultry_req.get('Index_weight'),
            filtered_poultry_req.get('amount'),
            filtered_poultry_req.get('quantity') - filtered_poultry_req.get('remain_quantity'),
            filtered_poultry_req.get('remain_quantity'),
            filtered_poultry_req.get('hatching__left_over'),

            filtered_poultry_req.get('hatching__chicken_breed'),
            str(date_of_kill),
            vet_farm_name,
            vet_farm_mobile,
            state_p,

        ]

        for item in range(len(list1)):
            cell = worksheet.cell(row=l, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center', vertical='center')
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
            worksheet.row_dimensions[l + 1].height = 24

            if m % 2 == 0:
                cell.fill = PatternFill(start_color="D6F6FE", fill_type="solid")
        state_s = 'در انتظار تخصیص استان'
        m += 1

        if province_kill_reqs.exists():
            quantity_kill_house_request = KillHouseRequest.objects.filter(trash=False,
                                                                          province_request__poultry_request__key=
                                                                          filtered_poultry_req['key'])

            if len(province_kill_reqs) > 1:
                if len(quantity_kill_house_request) <= 1:
                    s = len(province_kill_reqs) - 1
                    for col in range(ord('A'), ord('U') + 1):
                        # rng = chr(col) + '7:{}'.format(r)
                        rng = f'{chr(col)}{l}:{chr(col)}{l + s}'
                        worksheet.merge_cells(rng)
                        worksheet[chr(col) + f'{l}'].alignment = Alignment(horizontal='center', vertical='center')
                # TODO : جایی که باید انجام بشه
            if quantity_kill_house_request.exists():
                if len(quantity_kill_house_request) > 1:
                    for col in range(ord('A'), ord('U') + 1):
                        # rng = chr(col) + '7:{}'.format(r)
                        s = len(quantity_kill_house_request) - 1
                        rng = f'{chr(col)}{l}:{chr(col)}{l + s}'
                        worksheet.merge_cells(rng)
                        worksheet[chr(col) + f'{l}'].alignment = Alignment(horizontal='center', vertical='center')

            for province_kill_req in province_kill_reqs:

                if province_kill_req['state'] == 'pending':
                    state_s = 'درانتظار تایید'

                elif province_kill_req['state'] == 'accepted':
                    state_s = ' تایید شده'
                elif province_kill_req['state'] == 'rejected':
                    state_s = 'رد شده'
                all_wight_killer += int(province_kill_req.get('main_quantity') * province_kill_req.get(
                    'province_request__poultry_request__Index_weight'))
                # o += 1
                all_main_quantity += province_kill_req.get('main_quantity')

                date_of_inner_bar = '-'

                code = '-'

                time = jdatetime.date.fromgregorian(
                    day=province_kill_req.get('create_date').day,
                    month=province_kill_req.get('create_date').month,
                    year=province_kill_req.get('create_date').year
                )
                assignment_quantity = '-'
                assignment_weight = '-'

                if province_kill_req.get('killhouse_user__killer') == False:
                    killers = 'کشتارگاه'
                else:
                    killers = 'کشتارکن'

                kill_house_requests = KillHouseRequest.objects.filter(
                    province_kill_request__key=province_kill_req['key'],
                    trash=False).select_related('add_car__driver',
                                                'killhouse_user').only(
                    'killhouse_user__kill_house_operator__user__mobile',
                    'killhouse_user__kill_house_operator__user__fullname', 'killhouse_user',
                    'province_kill_request__province_request__poultry_request__Index_weight', 'key',
                    'add_car__driver__driver_name',
                    'add_car__driver__driver_mobile',
                    'add_car__driver__type_car',
                    'traffic_code', 'create_date',
                    'clearance_code',
                    'killhouse_user__killer',
                    'accepted_real_quantity', 'accepted_real_weight',
                    'quantity', 'province_request__poultry_request__Index_weight', 'vet_state',
                    'assignment_state_archive', 'vet_accepted_real_weight', 'vet_accepted_real_quantity',
                    'vet_state').values('vet_state', 'vet_accepted_real_weight', 'vet_accepted_real_quantity',
                                        'quarantine_quantity', 'vet_state', 'assignment_state_archive',
                                        'province_kill_request__province_request__poultry_request__Index_weight',
                                        'key',
                                        'add_car__driver__driver_name',
                                        'add_car__driver__driver_mobile',
                                        'add_car__driver__type_car',
                                        'traffic_code',
                                        'create_date',
                                        'clearance_code',
                                        'killhouse_user__killer',
                                        'accepted_real_quantity',
                                        'killhouse_user__kill_house_operator__user__fullname',
                                        'killhouse_user',
                                        'accepted_real_weight',
                                        'killhouse_user__kill_house_operator__user__mobile',
                                        'quantity', 'quarantine_quantity',
                                        'province_request__poultry_request__Index_weight')
                bar_list += (len(kill_house_requests))
                all_quantity_of_bar = kill_house_requests.aggregate(
                    total_quantity=Sum('quantity')).get(
                    'total_quantity', 0)

                bar_weight = int(all_quantity_of_bar * province_kill_req[
                    'province_request__poultry_request__Index_weight']) if all_quantity_of_bar != None else 0
                remain_province = int(province_kill_req.get('quantity') * province_kill_req[
                    'province_request__poultry_request__Index_weight'])
                all_reamin_province += int(province_kill_req.get('quantity') * province_kill_req[
                    'province_request__poultry_request__Index_weight'])
                sum_all_quantity_of_bar += all_quantity_of_bar if all_quantity_of_bar != None else 0
                sum_all_weight_of_bar += bar_weight
                sum_all_remain_quantity_of_bar += province_kill_req.get('quantity')
                list1 = [
                    killers + '(' + province_kill_req.get('killhouse_user__name') + ')',
                    province_kill_req.get('main_quantity'),
                    int(province_kill_req.get('main_quantity') * province_kill_req.get(
                        'province_request__poultry_request__Index_weight')),
                    str(time),
                    province_kill_req.get('killhouse_user__kill_house_operator__address__city__name'),
                    province_kill_req.get('kill_request__slaughter_house__name') if province_kill_req.get(
                        'kill_request__slaughter_house') is not None else '-',
                    state_s,
                    len(kill_house_requests),
                    all_quantity_of_bar if all_quantity_of_bar != None else 0,
                    bar_weight,
                    province_kill_req.get('quantity'),
                    remain_province,
                ]
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l, column=item + 22, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center')
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                    if m % 2 != 0:
                        cell.fill = PatternFill(start_color="D6F6FE", fill_type="solid")
                    worksheet.row_dimensions[l + 1].height = 20

                if kill_house_requests.exists():
                    if len(kill_house_requests) > 1:
                        s = len(kill_house_requests) - 1

                        letters = ["V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG"]
                        for col in letters:
                            rng = f'{col}{l}:{col}{l + s}'
                            worksheet.merge_cells(rng)
                            worksheet[col + f'{l}'].alignment = Alignment(horizontal='center', vertical='center')

                    for kill_house_request in kill_house_requests:
                        all_qarantine += kill_house_request['quarantine_quantity'] if kill_house_request[
                            'quarantine_quantity'] else 0
                        if kill_house_request['vet_state'] == 'accepted':
                            vet_state_accepted += 1
                        bar_list2 += 1
                        kil_house_vet = KillHouseVet.objects.filter(
                            kill_house=kill_house_request.get('killhouse_user')).select_related(
                            'vet__user').only('vet__user__fullname',
                                              'vet__user__mobile').values('vet__user__fullname',
                                                                          'vet__user__mobile').first()
                        kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                        kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                        if (kill_house_request['assignment_state_archive'] == 'True' and kill_house_request[
                            'vet_state'] == 'pending') or kill_house_request[
                            'vet_state'] == 'accepted':
                            state = 'تخلیه شده'
                        else:
                            state = 'درانتظار تخلیه'
                        all_quantity_of_bar += kill_house_request['quantity']
                        vet_quantity = kill_house_request['vet_accepted_real_quantity']
                        vet_wight = kill_house_request['vet_accepted_real_weight']
                        all_vet_quantity += vet_quantity
                        all_vet_wight += vet_wight
                        kill_house_driver_name = kill_house_request.get('add_car__driver__driver_name')
                        kill_house_driver_mobile = kill_house_request.get('add_car__driver__driver_mobile')
                        kill_house_driver_type_car = kill_house_request.get('add_car__driver__type_car')
                        kill_house_traffic_code = kill_house_request.get('traffic_code')
                        vet_checks = VetCheckRequest.objects.filter(
                            kill_house_request__key=kill_house_request.get('key')).only(
                            'create_date').values('create_date').first()

                        if vet_checks:
                            vet_check_date = vet_checks.get('create_date')
                            date_of_inner_bar = convert_to_shamsi(
                                datetime=vet_check_date
                            )

                        assignment = KillHouseAssignmentInformation.objects.filter(
                            kill_house_request__key=kill_house_request.get('key')).only('real_quantity',
                                                                                        'net_weight',
                                                                                        'create_date').values(
                            'real_quantity', 'net_weight', 'create_date').first()
                        if assignment:
                            all_assigment += 1
                            all_assignment_quantity += assignment.get('real_quantity')
                            assignment_quantity = assignment.get('real_quantity')
                            assignment_weight = assignment.get("net_weight")
                            vet_check_date = assignment.get('create_date')
                            date_of_inner_bar = convert_to_shamsi(
                                datetime=vet_check_date
                            )
                            all_assignment_weight += assignment_weight
                        if kill_house_request.get('clearance_code'):
                            code = kill_house_request.get('clearance_code')

                        list1 = [
                            kill_house_driver_type_car,
                            kill_house_driver_name,
                            kill_house_driver_mobile,
                            kill_house_traffic_code,
                            code,
                            kill_house_request['quarantine_quantity'] if kill_house_request[
                                'quarantine_quantity'] else '-',
                            kill_house_request['quantity'],
                            int(kill_house_request['quantity'] * kill_house_request[
                                'province_request__poultry_request__Index_weight']),
                            state,
                            vet_quantity,
                            vet_wight,
                            str(date_of_inner_bar),
                            kill_house_vet_name,
                            kill_house_vet_mobile,
                            assignment_quantity,
                            assignment_weight,
                            kill_house_request['killhouse_user__kill_house_operator__user__fullname'],
                            kill_house_request['killhouse_user__kill_house_operator__user__mobile'],
                        ]

                        for item in range(len(list1)):
                            cell = worksheet.cell(row=l, column=item + 34, value=list1[item])

                            cell.alignment = Alignment(horizontal='center', vertical='center')
                            cell.border = openpyxl.styles.Border(
                                left=openpyxl.styles.Side(style='thin'),
                                right=openpyxl.styles.Side(style='thin'),
                                top=openpyxl.styles.Side(style='thin'),
                                bottom=openpyxl.styles.Side(style='thin')
                            )
                            if m % 2 != 0:
                                cell.fill = PatternFill(start_color="D6F6FE", fill_type="solid")
                            worksheet.row_dimensions[l + 1].height = 20

                        l += 1
                else:
                    list1 = [

                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',
                        '-',

                    ]
                    # m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l, column=item + 34, value=list1[item])
                        cell.alignment = Alignment(horizontal='center', vertical='center')
                        cell.border = openpyxl.styles.Border(
                            left=openpyxl.styles.Side(style='thin'),
                            right=openpyxl.styles.Side(style='thin'),
                            top=openpyxl.styles.Side(style='thin'),
                            bottom=openpyxl.styles.Side(style='thin')
                        )
                        if m % 2 != 0:
                            cell.fill = PatternFill(start_color="D6F6FE", fill_type="solid")
                if province_kill_req['state'] == 'pending' or province_kill_req['state'] == 'rejected':
                    l += 1


        else:
            list1 = [
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                state_s,
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',
                '-',

            ]
            # m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l, column=item + 22, value=list1[item])
                cell.alignment = Alignment(horizontal='center', vertical='center')
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
                if m % 2 != 0:
                    cell.fill = PatternFill(start_color="D6F6FE", fill_type="solid")
            l += 1
    print(vet_state_accepted)
    value_header_list = [
        len(filtered_poultry_reqs),
        all_quantity,
        all_wight,
        len_province_request,
        all_main_quantity,
        all_wight_killer,
        all_remain_quantity,
        bar_list,
        sum_all_quantity_of_bar,
        sum_all_weight_of_bar,
        sum_all_remain_quantity_of_bar,
        vet_state_accepted,
        all_vet_quantity,
        all_vet_wight,
        all_assigment,
        all_assignment_quantity,
        all_assignment_weight,

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=value_header_list[item])
        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        value = value_header_list[item]
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        all_hatching,
        '',
        all_poultry_request,
        all_poultry_request_weight,
        '',
        '',
        sum_province_to_kill_house,
        all_remain_quantity,
        all_hatching_left_over,
        '',
        '',
        '',
        '',
        '',
        '',
        all_main_quantity,
        all_wight_killer,
        '',
        '',
        '',
        '',
        '',
        sum_all_quantity_of_bar,
        sum_all_weight_of_bar,
        sum_all_remain_quantity_of_bar,
        all_reamin_province,
        '',
        '',
        '',
        '',
        '',
        all_qarantine,
        sum_all_quantity_of_bar,
        sum_all_weight_of_bar,
        '',
        all_vet_quantity,
        all_vet_wight,
        '',
        '',
        '',
        all_assignment_quantity,
        all_assignment_weight,
        '',
        '',

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="روند پرونده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')), trash=False,
        kill_request__recive_date__date__gte=date1,
        kill_request__recive_date__date__lte=date2, quarantine_quantity__isnull=False,

    ).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name', 'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity').values(
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'مجموع تعداد قطعه ثبت شده در قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    worksheet['B1'] = f'گزارش مغایرت در بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی'
    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if kill.get('quantity') != kill['quarantine_quantity']:
                if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                    'vet_state'] == 'accepted':
                    state = 'تخلیه شده'
                else:
                    state = 'درانتظار تخلیه'
                l += 1
                date_of_inner_bar = '-'
                vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                  trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                                'vet__user__mobile').values(
                    'vet__user__fullname',
                    'vet__user__mobile').first()
                vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                    'vet__user').only('vet__user__fullname',
                                      'vet__user__mobile').values('vet__user__fullname',
                                                                  'vet__user__mobile').first()
                vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                    'create_date').values(
                    'create_date').first()
                kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                if kill.get('quantity'):
                    quantity = kill.get('quantity')
                    all_quantity += quantity
                else:
                    quantity = '-'
                send_date = kill.get('province_request__poultry_request__send_date')
                date_of_poultry_request = jdatetime.date.fromgregorian(
                    day=send_date.day,
                    month=send_date.month,
                    year=send_date.year
                )
                killers = 'کشتارکن'
                if kill.get('killhouse_user__killer') == False:
                    killers = 'کشتارگاه'
                assignment = KillHouseAssignmentInformation.objects.filter(
                    kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                               'real_quantity').values(
                    'net_weight', 'real_quantity', 'create_date').first()
                if assignment:
                    net_weighte = assignment.get('net_weight')
                    all_net_weighte += net_weighte
                    real_quantity = assignment.get('real_quantity')
                    all_real_quantity += real_quantity
                    vet_check_date = assignment.get('create_date')
                    date_of_inner_bar = convert_to_shamsi(
                        datetime=vet_check_date
                    )
                else:
                    net_weighte = '-'
                    real_quantity = '-'
                if vet_checks:
                    vet_check_date = vet_checks.get('create_date')
                    date_of_inner_bar = convert_to_shamsi(
                        datetime=vet_check_date
                    )

                if kill.get('kill_request__slaughter_house') is not None:
                    kill_place = kill.get('kill_request__slaughter_house__name')
                else:
                    kill_place = '-'

                vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                weight = kill.get('quantity') * kill.get(
                    'province_kill_request__province_request__poultry_request__Index_weight')
                all_weighte += weight
                quarantine_quantity = kill['quarantine_quantity'] if kill['quarantine_quantity'] != None else '-'
                age = (kill['province_request__poultry_request__send_date'].date() - kill[
                    'province_request__poultry_request__hatching__date'].date()).days + 1
                list1 = [
                    m,
                    str(kill.get('bar_code')),
                    str(date_of_poultry_request),
                    str(kill.get('province_request__poultry_request__order_code')),
                    kill.get('province_request__poultry_request__poultry__unit_name'),
                    str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                    kill.get('province_request__poultry_request__poultry__user__city__name'),
                    age,
                    kill.get('province_request__poultry_request__amount') if kill.get(
                        'province_request__poultry_request__amount') else 0,
                    kill.get('province_request__poultry_request__chicken_breed'),
                    vet_farm_name,
                    vet_farm_mobile,
                    killers,
                    kill.get('killhouse_user__name'),
                    kill.get('killhouse_user__kill_house_operator__user__mobile'),
                    kill.get('killhouse_user__system_address__city__name'),
                    kill_place,
                    kill_house_vet_name,
                    kill_house_vet_mobile,
                    kill.get('add_car__driver__driver_name'),
                    kill.get('add_car__driver__driver_mobile'),
                    kill.get('add_car__driver__type_car'),
                    str(kill.get('traffic_code')),
                    quantity,
                    weight,
                    code,
                    quarantine_quantity,
                    state,
                    str(date_of_inner_bar),
                    vet_quantity,
                    vet_wight,
                    real_quantity,
                    net_weighte,
                    kill['accepted_real_quantity'],
                    kill['accepted_real_weight'],

                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    value = list1[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    worksheet.row_dimensions[l + 1].height = 20
                    cell.alignment = Alignment(horizontal='center', vertical='center')
            else:
                pass
    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مغایرت بار ها.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def detail_of_killing_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(request.GET['date1'],
                                       '%Y-%m-%d').date() if 'date1' in request.GET else now
    date2 = datetime.datetime.strptime(request.GET['date2'],
                                       '%Y-%m-%d').date() if 'date2' in request.GET else now
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    now_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(now_date.split("-"))
    separate = "-"
    now_date_1 = separate.join(reversed_date)

    if 'role' in request.GET:
        role = request.GET['role']
    else:
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        user_token = ReportsUsers.objects.filter(user_token=request.GET['key']).first()
        role = user_token.position

    if role == 'CityOperator':
        if 'role' in request.GET:
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            city_operator = CityOperator.objects.get(trash=False, user=user)
            filtered_poultry_hatch = PoultryHatching.objects.filter(archive=False,
                                                                    allow_hatching='pending',
                                                                    poultry__city_operator=city_operator.unit_name,
                                                                    trash=False, left_over__gt=0, chicken_age__gt=50)

            hatching_between_50_70 = PoultryHatching.objects.filter(trash=False,
                                                                    poultry__city_operator=city_operator.unit_name,
                                                                    left_over__gt=F('quantity') * percent_of_losses,
                                                                    chicken_age__range=(55, 90)).order_by('id')
            filtered_kill_reqs = KillHouseRequest.objects.filter(
                Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
                kill_request__recive_date__date__gte=date1,
                province_request__poultry_request__poultry__city_operator=city_operator.unit_name,
                kill_request__recive_date__date__lte=date2).order_by(
                '-create_date').select_related(
                'killhouse_user', 'province_request__poultry_request__poultry__user',
                'province_request__poultry_request',
                'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
                'kill_request__slaughter_house').only('killer', 'killer__kill_house_operator__user__mobile',
                                                      'killer__name', 'province_request__poultry_request__freezing',
                                                      'province_request',
                                                      'province_request__poultry_request',
                                                      'traffic_code',
                                                      'assignment_state_archive',
                                                      'province_request__poultry_request__hatching__chicken_age',
                                                      'killhouse_user__kill_house_operator__user__province__name',
                                                      'killhouse_user',
                                                      'killhouse_user__name',
                                                      'province_request__poultry_request__amount',
                                                      'killhouse_user__kill_house_operator__user__mobile',
                                                      'killhouse_user__system_address__city__name',
                                                      'killhouse_user__killer',
                                                      'kill_request__slaughter_house',
                                                      'kill_request__slaughter_house__name',
                                                      'province_request__poultry_request__poultry',
                                                      'province_request__poultry_request__order_code',
                                                      'province_request__poultry_request__chicken_breed',
                                                      'province_request__poultry_request__poultry__user__city__name',
                                                      'province_request__poultry_request__poultry__unit_name',
                                                      'province_request__poultry_request__poultry__user__mobile',
                                                      'province_request__poultry_request__send_date',
                                                      'province_kill_request__province_request__poultry_request__Index_weight',
                                                      'add_car__driver__driver_name',
                                                      'add_car__driver__driver_mobile',
                                                      'add_car__driver__type_car',
                                                      'add_car__driver__health_code',
                                                      'key',
                                                      'clearance_code',
                                                      'quantity',
                                                      'bar_code',
                                                      'accepted_real_weight',
                                                      'accepted_real_quantity',
                                                      'vet_state', 'vet_accepted_real_quantity',
                                                      'vet_accepted_real_weight', 'quarantine_quantity',
                                                      'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                                      'province_kill_request__province_request__poultry_request__union',
                                                      'province_kill_request__province_request__poultry_request__direct_buying',
                                                      'quarantine_code_state',
                                                      'province_request__poultry_request__hatching__date',
                                                      'province_request__poultry_request__send_date', 'message').values(
                'killer', 'killer__kill_house_operator__user__mobile', 'killer__name',
                'message',
                'province_request__poultry_request__freezing', 'province_request',
                'province_request__poultry_request',
                'killhouse_user',
                'killhouse_user__name',
                'killhouse_user__kill_house_operator__user__mobile',
                'killhouse_user__system_address__city__name',
                'killhouse_user__killer',
                'kill_request__slaughter_house',
                'kill_request__slaughter_house__name',
                'province_request__poultry_request__poultry',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__chicken_breed',
                'province_request__poultry_request__poultry__user__city__name',
                'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__send_date',
                'add_car__driver__driver_name',
                'add_car__driver__driver_mobile',
                'add_car__driver__type_car',
                'add_car__driver__health_code',
                'key',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'bar_code',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'killhouse_user__kill_house_operator__user__province__name',
                'province_request__poultry_request__hatching__chicken_age',
                'province_request__poultry_request__amount',
                'assignment_state_archive',
                'traffic_code',
                'province_kill_request__province_request__poultry_request__free_sale_in_province',
                'province_kill_request__province_request__poultry_request__union',
                'province_kill_request__province_request__poultry_request__direct_buying',
                'quarantine_code_state',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )

            poultry_request = (
                PoultryRequest.objects.filter(trash=False, poultry__city_operator=city_operator.unit_name,
                                              pk__in=filtered_kill_reqs.values(
                                                  'province_request__poultry_request'))
                    .only('quantity', 'Index_weight')).annotate(
                total_quantity=Sum('quantity'),
                total_weight=Sum(F('quantity') * F('Index_weight'))
            )
            out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                     poultry__city_operator=city_operator.unit_name,
                                                                     out_province_request_cancel=False,
                                                                     send_date__date__gte=date1,
                                                                     send_date__date__lte=date2,
                                                                     province_state__in=('pending', 'accepted'))
        else:
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            city = ReportsUsers.objects.get(user_token=request.GET['key'])
            filtered_poultry_hatch = PoultryHatching.objects.filter(archive=False,
                                                                    allow_hatching='pending',
                                                                    poultry__user__city__name=city.city,
                                                                    trash=False, left_over__gt=0, chicken_age__gt=50)

            hatching_between_50_70 = PoultryHatching.objects.filter(trash=False,
                                                                    poultry__user__city__name=city.city,
                                                                    left_over__gt=F('quantity') * percent_of_losses,
                                                                    chicken_age__range=(55, 90)).order_by('id')
            filtered_kill_reqs = KillHouseRequest.objects.filter(
                Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
                kill_request__recive_date__date__gte=date1,
                province_request__poultry_request__poultry__user__city__name=city.city,
                kill_request__recive_date__date__lte=date2).order_by(
                '-create_date').select_related(
                'killhouse_user', 'province_request__poultry_request__poultry__user',
                'province_request__poultry_request',
                'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
                'kill_request__slaughter_house').only('killer', 'killer__kill_house_operator__user__mobile',
                                                      'killer__name', 'province_request__poultry_request__freezing',
                                                      'province_request',
                                                      'province_request__poultry_request',
                                                      'traffic_code',
                                                      'assignment_state_archive',
                                                      'province_request__poultry_request__hatching__chicken_age',
                                                      'killhouse_user__kill_house_operator__user__province__name',
                                                      'killhouse_user',
                                                      'killhouse_user__name',
                                                      'province_request__poultry_request__amount',
                                                      'killhouse_user__kill_house_operator__user__mobile',
                                                      'killhouse_user__system_address__city__name',
                                                      'killhouse_user__killer',
                                                      'kill_request__slaughter_house',
                                                      'kill_request__slaughter_house__name',
                                                      'province_request__poultry_request__poultry',
                                                      'province_request__poultry_request__order_code',
                                                      'province_request__poultry_request__chicken_breed',
                                                      'province_request__poultry_request__poultry__user__city__name',
                                                      'province_request__poultry_request__poultry__unit_name',
                                                      'province_request__poultry_request__poultry__user__mobile',
                                                      'province_request__poultry_request__send_date',
                                                      'province_kill_request__province_request__poultry_request__Index_weight',
                                                      'add_car__driver__driver_name',
                                                      'add_car__driver__driver_mobile',
                                                      'add_car__driver__type_car',
                                                      'add_car__driver__health_code',
                                                      'key',
                                                      'clearance_code',
                                                      'quantity',
                                                      'bar_code',
                                                      'accepted_real_weight',
                                                      'accepted_real_quantity',
                                                      'vet_state', 'vet_accepted_real_quantity',
                                                      'vet_accepted_real_weight', 'quarantine_quantity',
                                                      'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                                      'province_kill_request__province_request__poultry_request__union',
                                                      'province_kill_request__province_request__poultry_request__direct_buying',
                                                      'quarantine_code_state',
                                                      'province_request__poultry_request__hatching__date',
                                                      'province_request__poultry_request__send_date', 'message').values(
                'killer', 'killer__kill_house_operator__user__mobile', 'killer__name',
                'message',
                'province_request__poultry_request__freezing', 'province_request',
                'province_request__poultry_request',
                'killhouse_user',
                'killhouse_user__name',
                'killhouse_user__kill_house_operator__user__mobile',
                'killhouse_user__system_address__city__name',
                'killhouse_user__killer',
                'kill_request__slaughter_house',
                'kill_request__slaughter_house__name',
                'province_request__poultry_request__poultry',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__chicken_breed',
                'province_request__poultry_request__poultry__user__city__name',
                'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__send_date',
                'add_car__driver__driver_name',
                'add_car__driver__driver_mobile',
                'add_car__driver__type_car',
                'add_car__driver__health_code',
                'key',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'bar_code',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'killhouse_user__kill_house_operator__user__province__name',
                'province_request__poultry_request__hatching__chicken_age',
                'province_request__poultry_request__amount',
                'assignment_state_archive',
                'traffic_code',
                'province_kill_request__province_request__poultry_request__free_sale_in_province',
                'province_kill_request__province_request__poultry_request__union',
                'province_kill_request__province_request__poultry_request__direct_buying',
                'quarantine_code_state',
                'province_request__poultry_request__hatching__date',
                'province_request__poultry_request__send_date'
            )

            poultry_request = (
                PoultryRequest.objects.filter(trash=False, poultry__user__city__name=city.city,
                                              pk__in=filtered_kill_reqs.values(
                                                  'province_request__poultry_request'))
                    .only('quantity', 'Index_weight')).annotate(
                total_quantity=Sum('quantity'),
                total_weight=Sum(F('quantity') * F('Index_weight'))
            )
            out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                     poultry__user__city__name=city.city,
                                                                     out_province_request_cancel=False,
                                                                     send_date__date__gte=date1,
                                                                     send_date__date__lte=date2,
                                                                     province_state__in=('pending', 'accepted'))
    elif role in ['CityJahad', 'CityPoultry']:
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        filtered_poultry_hatch = PoultryHatching.objects.filter(archive=False, poultry__address__city=user.city,
                                                                allow_hatching='pending',
                                                                trash=False, left_over__gt=0, chicken_age__gt=50)

        hatching_between_50_70 = PoultryHatching.objects.filter(trash=False, poultry__address__city=user.city,
                                                                left_over__gt=F('quantity') * percent_of_losses,
                                                                chicken_age__range=(55, 90)).order_by('id')
        filtered_kill_reqs = KillHouseRequest.objects.filter(
            Q(trash=False) | Q(trash=True, clearance_code__isnull=False),
            kill_request__recive_date__date__gte=date1,
            province_request__poultry_request__poultry__address__city=user.city,
            kill_request__recive_date__date__lte=date2).order_by(
            '-create_date').select_related(
            'killhouse_user', 'province_request__poultry_request__poultry__user',
            'province_request__poultry_request',
            'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
            'kill_request__slaughter_house').only('killer', 'killer__kill_house_operator__user__mobile',
                                                  'killer__name', 'province_request__poultry_request__freezing',
                                                  'province_request',
                                                  'province_request__poultry_request',
                                                  'traffic_code',
                                                  'assignment_state_archive',
                                                  'province_request__poultry_request__hatching__chicken_age',
                                                  'killhouse_user__kill_house_operator__user__province__name',
                                                  'killhouse_user',
                                                  'killhouse_user__name',
                                                  'province_request__poultry_request__amount',
                                                  'killhouse_user__kill_house_operator__user__mobile',
                                                  'killhouse_user__system_address__city__name',
                                                  'killhouse_user__killer',
                                                  'kill_request__slaughter_house',
                                                  'kill_request__slaughter_house__name',
                                                  'province_request__poultry_request__poultry',
                                                  'province_request__poultry_request__order_code',
                                                  'province_request__poultry_request__chicken_breed',
                                                  'province_request__poultry_request__poultry__user__city__name',
                                                  'province_request__poultry_request__poultry__unit_name',
                                                  'province_request__poultry_request__poultry__user__mobile',
                                                  'province_request__poultry_request__send_date',
                                                  'province_kill_request__province_request__poultry_request__Index_weight',
                                                  'add_car__driver__driver_name',
                                                  'add_car__driver__driver_mobile',
                                                  'add_car__driver__type_car',
                                                  'add_car__driver__health_code',
                                                  'key',
                                                  'clearance_code',
                                                  'quantity',
                                                  'bar_code',
                                                  'accepted_real_weight',
                                                  'accepted_real_quantity',
                                                  'vet_state', 'vet_accepted_real_quantity',
                                                  'vet_accepted_real_weight', 'quarantine_quantity',
                                                  'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                                  'province_kill_request__province_request__poultry_request__union',
                                                  'province_kill_request__province_request__poultry_request__direct_buying',
                                                  'quarantine_code_state',
                                                  'province_request__poultry_request__hatching__date',
                                                  'province_request__poultry_request__send_date', 'message').values(
            'killer', 'killer__kill_house_operator__user__mobile', 'killer__name',
            'message',
            'province_request__poultry_request__freezing', 'province_request',
            'province_request__poultry_request',
            'killhouse_user',
            'killhouse_user__name',
            'killhouse_user__kill_house_operator__user__mobile',
            'killhouse_user__system_address__city__name',
            'killhouse_user__killer',
            'kill_request__slaughter_house',
            'kill_request__slaughter_house__name',
            'province_request__poultry_request__poultry',
            'province_request__poultry_request__order_code',
            'province_request__poultry_request__chicken_breed',
            'province_request__poultry_request__poultry__user__city__name',
            'province_request__poultry_request__poultry__unit_name',
            'province_request__poultry_request__poultry__user__mobile',
            'province_request__poultry_request__send_date',
            'add_car__driver__driver_name',
            'add_car__driver__driver_mobile',
            'add_car__driver__type_car',
            'add_car__driver__health_code',
            'key',
            'province_kill_request__province_request__poultry_request__Index_weight',
            'clearance_code',
            'quantity',
            'bar_code',
            'accepted_real_weight',
            'accepted_real_quantity',
            'vet_state',
            'vet_accepted_real_quantity',
            'vet_accepted_real_weight',
            'quarantine_quantity',
            'killhouse_user__kill_house_operator__user__province__name',
            'province_request__poultry_request__hatching__chicken_age',
            'province_request__poultry_request__amount',
            'assignment_state_archive',
            'traffic_code',
            'province_kill_request__province_request__poultry_request__free_sale_in_province',
            'province_kill_request__province_request__poultry_request__union',
            'province_kill_request__province_request__poultry_request__direct_buying',
            'quarantine_code_state',
            'province_request__poultry_request__hatching__date',
            'province_request__poultry_request__send_date'
        )

        poultry_request = (PoultryRequest.objects.filter(trash=False, poultry__address__city=user.city,
                                                         pk__in=filtered_kill_reqs.values(
                                                             'province_request__poultry_request'))
                           .only('quantity', 'Index_weight')).annotate(
            total_quantity=Sum('quantity'),
            total_weight=Sum(F('quantity') * F('Index_weight'))
        )
        out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                 poultry__address__city=user.city,
                                                                 out_province_request_cancel=False,
                                                                 send_date__date__gte=date1,
                                                                 send_date__date__lte=date2,
                                                                 province_state__in=('pending', 'accepted'))

    else:
        filtered_poultry_hatch = PoultryHatching.objects.filter(archive=False,
                                                                allow_hatching='pending',
                                                                trash=False, left_over__gt=0, chicken_age__gt=50)

        hatching_between_50_70 = PoultryHatching.objects.filter(trash=False,
                                                                left_over__gt=F('quantity') * percent_of_losses,
                                                                chicken_age__range=(55, 90)).order_by('id')
        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(
            'killhouse_user', 'province_request__poultry_request__poultry__user',
            'province_request__poultry_request',
            'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
            'kill_request__slaughter_house').only('killer', 'killer__kill_house_operator__user__mobile',
                                                  'killer__name', 'province_request__poultry_request__freezing',
                                                  'province_request',
                                                  'province_request__poultry_request',
                                                  'traffic_code',
                                                  'assignment_state_archive',
                                                  'province_request__poultry_request__hatching__chicken_age',
                                                  'killhouse_user__kill_house_operator__user__province__name',
                                                  'killhouse_user',
                                                  'killhouse_user__name',
                                                  'province_request__poultry_request__amount',
                                                  'killhouse_user__kill_house_operator__user__mobile',
                                                  'killhouse_user__system_address__city__name',
                                                  'killhouse_user__killer',
                                                  'kill_request__slaughter_house',
                                                  'kill_request__slaughter_house__name',
                                                  'province_request__poultry_request__poultry',
                                                  'province_request__poultry_request__order_code',
                                                  'province_request__poultry_request__chicken_breed',
                                                  'province_request__poultry_request__poultry__user__city__name',
                                                  'province_request__poultry_request__poultry__unit_name',
                                                  'province_request__poultry_request__poultry__user__mobile',
                                                  'province_request__poultry_request__send_date',
                                                  'province_kill_request__province_request__poultry_request__Index_weight',
                                                  'add_car__driver__driver_name',
                                                  'add_car__driver__driver_mobile',
                                                  'add_car__driver__type_car',
                                                  'add_car__driver__health_code',
                                                  'key',
                                                  'clearance_code',
                                                  'quantity',
                                                  'bar_code',
                                                  'accepted_real_weight',
                                                  'accepted_real_quantity',
                                                  'vet_state', 'vet_accepted_real_quantity',
                                                  'vet_accepted_real_weight', 'quarantine_quantity',
                                                  'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                                  'province_kill_request__province_request__poultry_request__union',
                                                  'province_kill_request__province_request__poultry_request__direct_buying',
                                                  'quarantine_code_state',
                                                  'province_request__poultry_request__hatching__date',
                                                  'province_request__poultry_request__send_date', 'message').values(
            'killer', 'killer__kill_house_operator__user__mobile', 'killer__name',
            'message',
            'province_request__poultry_request__freezing', 'province_request',
            'province_request__poultry_request',
            'killhouse_user',
            'killhouse_user__name',
            'killhouse_user__kill_house_operator__user__mobile',
            'killhouse_user__system_address__city__name',
            'killhouse_user__killer',
            'kill_request__slaughter_house',
            'kill_request__slaughter_house__name',
            'province_request__poultry_request__poultry',
            'province_request__poultry_request__order_code',
            'province_request__poultry_request__chicken_breed',
            'province_request__poultry_request__poultry__user__city__name',
            'province_request__poultry_request__poultry__unit_name',
            'province_request__poultry_request__poultry__user__mobile',
            'province_request__poultry_request__send_date',
            'add_car__driver__driver_name',
            'add_car__driver__driver_mobile',
            'add_car__driver__type_car',
            'add_car__driver__health_code',
            'key',
            'province_kill_request__province_request__poultry_request__Index_weight',
            'clearance_code',
            'quantity',
            'bar_code',
            'accepted_real_weight',
            'accepted_real_quantity',
            'vet_state',
            'vet_accepted_real_quantity',
            'vet_accepted_real_weight',
            'quarantine_quantity',
            'killhouse_user__kill_house_operator__user__province__name',
            'province_request__poultry_request__hatching__chicken_age',
            'province_request__poultry_request__amount',
            'assignment_state_archive',
            'traffic_code',
            'province_kill_request__province_request__poultry_request__free_sale_in_province',
            'province_kill_request__province_request__poultry_request__union',
            'province_kill_request__province_request__poultry_request__direct_buying',
            'quarantine_code_state',
            'province_request__poultry_request__hatching__date',
            'province_request__poultry_request__send_date'
        )

        poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values(
            'province_request__poultry_request'))
                           .only('quantity', 'Index_weight')).annotate(
            total_quantity=Sum('quantity'),
            total_weight=Sum(F('quantity') * F('Index_weight'))
        )
        out_true_poultry_request = PoultryRequest.objects.filter(trash=False, out=True,
                                                                 out_province_request_cancel=False,
                                                                 send_date__date__gte=date1,
                                                                 send_date__date__lte=date2,
                                                                 province_state__in=('pending', 'accepted'))

    total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total']
    total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total']
    all_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity', 0)

    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)
    all_age = []

    excel_options = {
        'آمار کلی': [],
        'مدیریت بارها': [],
        'مانده در سالن بالای 50 روز': [],
        'بارهای احراز شده مغایرت دار': [],
        'بارهای فاقد قرنطینه تخلیه شده': [],
        'بارهای عدم احراز از قرنطینه': [],
        'بارهای تخلیه نشده با کد قرنطینه': [],
        'تخلیه نشده-تحویل گرفته شده': [],
        'تخلیه شده-عدم تکمیل': [],
        'بارهای تخلیه نشده-عدم تکمیل': [],
        'بارهای تخلیه شده- تکمیل شده': [],
    }
    output = BytesIO()
    workbook = Workbook()
    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            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)
    for name, options in excel_options.items():
        all_age1 = sorted(all_age)
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000", bold=True)

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=1, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')

            # worksheet.column_dimensions[col_letter].width = 20.01
            # worksheet.row_dimensions[1].height = 22

        if sheet_name == 'مدیریت بارها':

            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',
            ]
            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__poultry__user',
                'province_request__poultry_request',
                'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
                'kill_request__slaughter_house').only('province_kill_request__kill_house_price',
                                                      'kill_request__export_country',
                                                      'province_request__poultry_request__direct_buying',
                                                      'province_request__poultry_request__export',
                                                      'province_request__poultry_request__freezing', 'document_status',
                                                      'ware_house_accepted_real_quantity',
                                                      'ware_house_accepted_real_weight', 'weight_loss', 'message',
                                                      'province_request__poultry_request__freezing',
                                                      'province_request__poultry_request', 'traffic_code',
                                                      'assignment_state_archive',
                                                      'province_request__poultry_request__hatching__chicken_age',
                                                      'killhouse_user__kill_house_operator__user__province__name',
                                                      'killhouse_user',
                                                      'killhouse_user__name',
                                                      'province_request__poultry_request__amount',
                                                      'killhouse_user__kill_house_operator__user__mobile',
                                                      'killhouse_user__system_address__city__name',
                                                      'killhouse_user__killer',
                                                      'kill_request__slaughter_house',
                                                      'kill_request__slaughter_house__name',
                                                      'province_request__poultry_request__poultry',
                                                      'province_request__poultry_request__order_code',
                                                      'province_request__poultry_request__chicken_breed',
                                                      'province_request__poultry_request__poultry__user__city__name',
                                                      'province_request__poultry_request__poultry__unit_name',
                                                      'province_request__poultry_request__poultry__user__mobile',
                                                      'province_request__poultry_request__poultry__user__fullname',
                                                      'province_request__poultry_request__send_date',
                                                      'province_kill_request__province_request__poultry_request__Index_weight',
                                                      'add_car__driver__driver_name',
                                                      'add_car__driver__driver_mobile',
                                                      'add_car__driver__type_car',
                                                      'add_car__driver__health_code',
                                                      'key',
                                                      'clearance_code',
                                                      'quantity',
                                                      'bar_code',
                                                      'accepted_real_weight',
                                                      'accepted_real_quantity',
                                                      'vet_state', 'vet_accepted_real_quantity',
                                                      'vet_accepted_real_weight', 'quarantine_quantity',
                                                      'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                                      'province_kill_request__province_request__poultry_request__union',
                                                      'province_kill_request__province_request__poultry_request__direct_buying',
                                                      'quarantine_code_state',
                                                      'province_request__poultry_request__send_date',
                                                      'province_request__poultry_request__hatching__date',
                                                      'killer__kill_house_operator__user__mobile',
                                                      'province_kill_request__province_request__poultry_request__out',
                                                      'province_kill_request__kill_house_price',
                                                      'price',
                                                      'killer__name',
                                                      'killhouse_user__type', 'killer', 'bar_document_status',
                                                      'bar_document_status__title').values(
                'province_request__poultry_request__poultry__user__fullname', 'province_kill_request__kill_house_price',
                'kill_request__export_country',
                'province_request__poultry_request__direct_buying',
                'province_request__poultry_request__export',
                'province_request__poultry_request__freezing',
                'document_status',
                'ware_house_confirmation',
                'ware_house_accepted_real_quantity',
                'ware_house_accepted_real_weight',
                'weight_loss', 'message',
                'province_request__poultry_request__freezing',
                'province_request__poultry_request',
                'killhouse_user',
                'killhouse_user__name',
                'killhouse_user__kill_house_operator__user__mobile',
                'killhouse_user__system_address__city__name',
                'killhouse_user__killer',
                'kill_request__slaughter_house',
                'kill_request__slaughter_house__name',
                'province_request__poultry_request__poultry',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__chicken_breed',
                'province_request__poultry_request__poultry__user__city__name',
                'province_request__poultry_request__poultry__unit_name',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__send_date',
                'add_car__driver__driver_name',
                'add_car__driver__driver_mobile',
                'add_car__driver__type_car',
                'add_car__driver__health_code',
                'key',
                'province_kill_request__province_request__poultry_request__Index_weight',
                'clearance_code',
                'quantity',
                'bar_code',
                'accepted_real_weight',
                'accepted_real_quantity',
                'vet_state',
                'vet_accepted_real_quantity',
                'vet_accepted_real_weight',
                'quarantine_quantity',
                'killhouse_user__kill_house_operator__user__province__name',
                'province_request__poultry_request__hatching__chicken_age',
                'province_request__poultry_request__amount',
                'assignment_state_archive',
                'traffic_code',
                'province_kill_request__province_request__poultry_request__free_sale_in_province',
                'province_kill_request__province_request__poultry_request__union',
                'province_kill_request__province_request__poultry_request__direct_buying',
                'province_kill_request__province_request__poultry_request__out',
                'quarantine_code_state',
                'province_request__poultry_request__send_date',
                'province_request__poultry_request__hatching__date',
                'killer__kill_house_operator__user__mobile',
                'killer__name',
                'killhouse_user__type',
                'killer', 'bar_document_status',
                'province_kill_request__kill_house_price',
                'price',
                'bar_document_status__title'
            )

            if request.GET['role'] == 'CityOperator':
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                city_operator = CityOperator.objects.get(trash=False, user=user)
                filtered_kill_reqs = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                filtered_kill_reqs = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__address__city=user.city)
            elif request.GET['role'] == 'VetFarm':
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                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)
                filtered_kill_reqs = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__in=poultries)

            elif request.GET['role'] == 'KillHouse':
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                filtered_kill_reqs = filtered_kill_request.filter(killhouse_user__kill_house_operator__user=user)
            else:
                filtered_kill_reqs = filtered_kill_request

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

            elif request.GET['role'] == 'KillHouseVet':
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
                kill_house = kill_house_vets.values_list('kill_house', flat=True).distinct()

            else:
                kill_house = KillHouse.objects.filter(out_province=False, trash=False)

            if 'state' in request.GET:
                if request.GET['state'] == 'completed':
                    filtered_kill_reqs = filtered_kill_reqs.filter(assignment_state_archive='True')
                elif request.GET['state'] == 'bar_pending':
                    filtered_kill_reqs = filtered_kill_reqs.filter(
                        (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                            killer__in=kill_house)), assignment_state_archive='pending')
                else:
                    filtered_kill_reqs = filtered_kill_reqs
            else:
                filtered_kill_reqs = filtered_kill_reqs
            if 'search' in request.GET:
                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=filtered_kill_reqs

                            )
                            ).filter():
                                ps = filterset_class(data=query, queryset=filtered_kill_reqs)
                                filtered_kill_reqs = ps.filter()
            poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.values(
                'province_request__poultry_request'))
                               .only('quantity', 'Index_weight')).annotate(
                total_quantity=Sum('quantity'),
                total_weight=Sum(F('quantity') * F('Index_weight'))
            )

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'نوع کشتار',
                'کدسفارش مرغدار',
                'نام و نام خانوادگی مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'نام فارم',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                'قیمت پیشنهادی کشتارگاه(ریال)',
                'قیمت تعاونی(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'قیمت کشتارگاه(ریال)',
                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',
                'وضعیت',
                'وضعیت سند',
                'وضعیت ورود انبار',
                'تعداد لاشه',
                'وزن لاشه',
                'درصد افت در لحظه',
                'درصد افت ورود به انبار',
                'کشور مقصد',
                'اختلاف مجوز',

            ]

            from_date_1 = shamsi_date(date1)

            to_date_1 = shamsi_date(date2)

            output = BytesIO()
            workbook = Workbook()
            worksheet = workbook.active
            worksheet.sheet_view.rightToLeft = True
            worksheet.insert_rows(1)
            cell = worksheet.cell(row=1, column=1)

            header_list = [
                'تعداد بارهای ایجاد شده',
                'تعداد بارهای دارای کشتارکن اختصاصی',
                'حجم بارهای ایجاد شده',
                'وزن بارهای ایجاد شده',
                'میانگین وزن بارهای ایجاد شده',
                'کمترین سن',
                'بیشترین سن',
                'میانگین سنی',
                'تعداد بارهای دارای کد قرنطینه',
                'حجم بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد بار فاقد قرنطینه',
                'حجم بار فاقد قرنطینه',
                ' تعداد بارهایی که در قرنطینه و رصدیار اختلاف دارند',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',
                'حجم بارها',
                'وزن بارها',
                'تعداد بار های وارد شده در انبار',
                'مجموع تعداد لاشه',
                'مجموع وزن لاشه',
                'میانگین درصد افت لاشه ورود به انبار',

            ]

            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            header_list3 = [
                'درصد بارهای دارای کد قرنطینه',
                'درصد تعداد بارهای احراز شده از قرنطینه',
                'درصد تعداد بارهای تکمیل شده کشتارگاه',
                'درصد وزن نهایی در کشتارگاه نسبت به وزن کل',
                'درصد بارهای فاقد کد قرنطینه',
                'درصد بارهای اختلاف دار در قرنطینه و رصدیار',
                'درصد تعداد بارهای ورودی به انبار',
                'درصد وزن لاشه ها در انبار نسبت به وزن کل',
                'درصد وزن لاشه در انبار نسبت به وزن نهایی در کشتارگاه',

            ]
            create_header(worksheet, header_list, 9, 2, height=21.8)

            create_header(worksheet, header_list2, 6, 2, height=21.8, color='green')

            create_header(worksheet, header_list3, 6, 5, height=43, color='orange', text_color='0D0D0D')
            create_header_freez(worksheet, excel_options, 1, 8, 9, height=21, len_with=True)

            excel_description(worksheet, 'B1', 'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی', color='red',
                              row2='D1')

            kill_keys = [kill.get('key') for kill in filtered_kill_reqs]

            vet_checks = VetCheckRequest.objects.filter(
                trash=False, kill_house_request__key__in=kill_keys
            ).only('create_date', 'kill_house_request__key').values(
                'create_date', 'kill_house_request__key')

            assignments = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key__in=kill_keys, trash=False
            ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key')

            vet_check_mapping = {vc['kill_house_request__key']: vc['create_date'] for vc in vet_checks}
            assignment_mapping = {
                assignment.kill_house_request.key: (
                    int(assignment.net_weight), assignment.real_quantity, assignment.create_date)
                for assignment in assignments
            }
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'
                excel_description(worksheet, 'B2', f'استان {name}', color='red', row2='D2')
            excel_description(worksheet, 'B3', f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})', row2='D3')

            l = 8
            m = 1
            all_age = []

            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            poultry_ids = [req.get('province_request__poultry_request__poultry') for req in filtered_kill_reqs]
            vet_farms = VetFarm.objects.filter(poultry__in=poultry_ids, trash=False).select_related('vet__user')
            vet_farm_mapping = {
                vet_farm.poultry_id: (vet_farm.vet.user.fullname, vet_farm.vet.user.mobile)
                for vet_farm in vet_farms
            }
            if filtered_kill_reqs:
                for kill in filtered_kill_reqs:

                    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)

                    if (kill['assignment_state_archive']) == 'True' or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    vet_farm_id = kill.get('province_request__poultry_request__poultry')
                    vet_farm_name, vet_farm_mobile = vet_farm_mapping.get(vet_farm_id, ('-', '-'))
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                                trash=False).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()

                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')

                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = convert_to_shamsi(year=send_date.year, month=send_date.month,
                                                                day=send_date.day, )

                    killers = 'کشتارکن'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                    key = kill.get('key')
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    if kill['assignment_state_archive'] == 'True' or kill['ware_house_confirmation'] == True:
                        net_weighte = kill['accepted_real_weight']
                        real_quantity = kill['accepted_real_quantity']
                    else:
                        net_weighte = 0
                        real_quantity = 0
                    net_weighte2, real_quantity2, vet_check_date = assignment_mapping.get(key, ('-', '-', None))
                    all_real_quantity += real_quantity if real_quantity != '-' else 0
                    all_net_weighte += net_weighte if net_weighte != '-' else 0
                    vet_check_date = vet_check_mapping.get(key, vet_check_date)
                    date_of_inner_bar = convert_to_shamsi(datetime=vet_check_date) if vet_check_date else '-'

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = int(kill['vet_accepted_real_weight']) if kill['vet_accepted_real_weight'] else '-'

                    weight = int(kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight'))

                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'
                    export_country = '-'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__out'] == True:
                        type = 'خارج از استان'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    elif kill['province_request__poultry_request__freezing'] == True:
                        type = 'انجماد'
                    elif kill['province_request__poultry_request__export'] == True:
                        type = 'صادرات'
                        export_country = kill['kill_request__export_country']
                    else:
                        type = 'عادی'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1

                    if kill['message'] is not None:
                        state_delete = 'بار حذف شده'
                    else:
                        state_delete = 'فعال'
                        all_weighte += weight

                    ware_house_accepted_real_quantity = kill['ware_house_accepted_real_quantity']
                    ware_house_accepted_real_weight = kill['ware_house_accepted_real_weight']
                    weight_loss = round(kill['weight_loss'], 2) if kill['weight_loss'] > 0 else 0

                    if kill['ware_house_confirmation'] == True:
                        state_ware_house_confirmation = 'ورود به انبار'

                    else:
                        state_ware_house_confirmation = '-'

                    weight_loss1 = kill['accepted_real_weight'] - kill['ware_house_accepted_real_weight'] if kill[
                                                                                                                 'ware_house_accepted_real_weight'] > 0 else 0
                    if weight_loss1 < 0:
                        weight_loss1 = weight_loss1 * -1
                    total_weight_loss = (weight_loss1 / kill['accepted_real_weight']) * 100 if weight_loss1 != 0 else 0

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        type,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__user__fullname'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',

                        kill.get('province_kill_request__kill_house_price') if kill.get(
                            'province_kill_request__kill_house_price') else '-',

                        kill.get('price') if kill.get(
                            'price') else '-',

                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        kill.get('province_kill_request__kill_house_price'),
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        round(kill['accepted_real_weight'], 1),
                        state_delete,
                        kill['bar_document_status__title'] if kill['bar_document_status'] else '-',
                        state_ware_house_confirmation,
                        ware_house_accepted_real_quantity,
                        int(ware_house_accepted_real_weight),
                        f'%{round(total_weight_loss, 2)}',
                        f'%{weight_loss}',
                        export_country,
                        kill['accepted_real_quantity'] - quarantine_quantity if kill[
                                                                'quarantine_quantity'] != None else quarantine_quantity

                    ]
                    m += 1
                    create_value(worksheet, list1, l, 1, height=20, different_cell=40, different_value='بار حذف شده')
            killer_exclusive = len(filtered_kill_reqs.filter(killer__isnull=False))
            all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True))

            total_requests_quantity = poultry_request.aggregate(total=Sum('total_quantity'))['total'] or 0
            total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0

            aggregate_filtered_kill_reqs = filtered_kill_reqs.aggregate(
                total_accepted_real_quantity=Sum('accepted_real_quantity'),
                total_accepted_real_weight=Sum('accepted_real_weight'),
                total_quantity=Sum('quantity'),
                total_vet_accepted_real_quantity=Sum('vet_accepted_real_quantity'),
                total_vet_accepted_real_weight=Sum('vet_accepted_real_weight'),
                total_quarantine_quantity=Sum('quarantine_quantity'),
                total_ware_house_accepted_real_quantity=Sum('ware_house_accepted_real_quantity'),
                total_ware_house_accepted_real_weight=Sum('ware_house_accepted_real_weight'),
                total_weight_loss=Sum('weight_loss'),

            )
            all_vet_state_accepted = len(
                filtered_kill_reqs.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')

            accepted_real_quantity = aggregate_filtered_kill_reqs['total_accepted_real_quantity'] or 0

            accepted_real_wight = aggregate_filtered_kill_reqs['total_accepted_real_weight'] or 0
            all_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0
            all_quarantine_quantity = aggregate_filtered_kill_reqs['total_quarantine_quantity'] or 0
            all_vet_accepted_real_quantity = aggregate_filtered_kill_reqs['total_vet_accepted_real_quantity'] or 0
            all_vet_accepted_real_weight = aggregate_filtered_kill_reqs['total_vet_accepted_real_weight'] or 0
            has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))
            all_ware_house_accepted_real_quantity = aggregate_filtered_kill_reqs[
                                                        'total_ware_house_accepted_real_quantity'] or 0
            all_ware_house_accepted_real_weight = aggregate_filtered_kill_reqs[
                                                      'total_ware_house_accepted_real_weight'] or 0
            all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0
            has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False).aggregate(
                total_quantity=Sum('quantity'),
            )
            all_quarantine_quantity_has_code = has_code1['total_quantity'] or 0
            hasnt_code1 = filtered_kill_reqs.filter(clearance_code__isnull=True)
            hasnt_code = hasnt_code1.aggregate(
                total_quantity=Sum('quantity')
            )
            all_quarantine_quantity_hasnt_code = hasnt_code['total_quantity'] or 0
            difference_bar = len(filtered_kill_reqs.filter(
                Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity'))))
            all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation,
                                    2) if all_weight_loss > 0 else 0

            all_age1 = sorted(all_age)
            has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))

            province_kill_request = ProvinceKillRequest.objects.filter(
                pk__in=filtered_kill_reqs.values(
                    'province_kill_request')).aggregate(
                total_quantity_melak=Sum('total_killed_quantity'),
                total_weight_melak=Sum('total_killed_weight'),
            )

            # province_kill_request = filtered_kill_reqs.values_list(
            #         'province_kill_request',flat=True).distinct().aggregate(
            #     total_quantity_melak=Sum('total_killed_quantity'),
            #     total_weight_melak=Sum('total_killed_weight'),
            # )
            accepted_real_quantity_melak = province_kill_request['total_quantity_melak'] or 0

            accepted_real_wight_melak = province_kill_request['total_weight_melak'] or 0
            value_header_list = [
                len(poultry_request),
                total_requests_quantity,
                int(total_requests_weight),
                len(filtered_kill_reqs),
                killer_exclusive,
                all_kill_request_quantity,
                int(all_weighte),
                round(all_weighte / all_kill_request_quantity,
                      1) if all_weighte > 0 and all_kill_request_quantity > 0 else 0,
                all_age1[0] if len(all_age1) > 0 else '-',
                all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-',
                int((sum(all_age1)) / len(all_age1)) if len(all_age1) > 0 else '-',
                has_code,
                all_quarantine_quantity_has_code,
                has_qarantine,
                all_quarantine_quantity,
                len(hasnt_code1),
                all_quarantine_quantity_hasnt_code,
                difference_bar,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                int(all_vet_accepted_real_weight),
                len(bar_complete),
                all_real_quantity,
                int(all_net_weighte),
                accepted_real_quantity_melak,
                accepted_real_wight_melak,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                int(accepted_real_wight) if accepted_real_wight != None else 0,
                all_state_ware_house_confirmation,
                all_ware_house_accepted_real_quantity,
                int(all_ware_house_accepted_real_weight),
                f'%{all_weight_loss}'

            ]
            create_value(worksheet, value_header_list, 3, 6)
            value_header_list2 = [
                f'%{round((has_code * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}',
                f'%{round((has_qarantine * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}',
                f'%{round((len(bar_complete) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}',
                f'%{round((int(all_net_weighte) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}',
                f'%{round((len(hasnt_code1) * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}',
                f'%{round((difference_bar * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}',
                f'%{round((all_state_ware_house_confirmation * 100) / len(filtered_kill_reqs), 2) if len(filtered_kill_reqs) > 0 else 0}',
                f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_weighte), 2) if int(all_weighte) > 0 else 0}',
                f'%{round((int(all_ware_house_accepted_real_weight) * 100) / int(all_net_weighte), 2) if int(all_net_weighte) > 0 else 0}'
            ]
            create_value(worksheet, value_header_list2, 6, 6)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',

                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                int(all_weighte),
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                int(all_vet_accepted_real_weight),
                all_real_quantity,
                int(all_net_weighte),
                accepted_real_quantity if accepted_real_quantity != None else 0,
                int(accepted_real_wight) if accepted_real_wight != None else 0,
                '',
                '',
                '',
                all_ware_house_accepted_real_quantity,
                int(all_ware_house_accepted_real_weight),
                '',
                '',
                '',
                '',

            ]
            create_value(worksheet, list2, l + 3, 1, color='green')

        elif sheet_name == 'مانده در سالن بالای 50 روز':
            excel_options = [
                'ردیف',
                'نام و خانوادگی',
                'نام فارم',
                'موبایل',
                'کد یکتا',
                'کد سیستمی واحد',
                'سالن',
                ' دوره جوجه ریزی',
                'تاریخ ثبت جوجه ریزی',
                'تاریخ جوجه ریزی',
                'نژاد',
                'سن',
                'تعداد جوجه ریزی',
                'تلفات دوره',
                'تعداد کشتار شده(قطعه)',
                'وزن کل کشتارشده(کیلوگرم)',
                'مانده در سالن',
                'مانده در سالن از نود درصد',
                'وزن تعهد دولتی(کیلوگرم)',
                'تعداد کشتار دولتی(قطعه)',
                'وزن کشتار دولتی(کیلوگرم)',
                'تعداد کشتار آزاد(قطعه)',
                'وزن کشتار آزاد(کیلوگرم)',
                'میانگین وزن کشتار(کیلوگرم)',
                'سازنده جوجه ریزی',
                'کد اپیدمیولوژیک',
                'تعداد کشتار خارج از استان(قطعه)',
                'وزن کشتار خارج از استان(کیلوگرم)',
            ]
            date1 = datetime.datetime.now().date()
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            header_list = [
                'تعداد فارم فعال',
                'مجموع جوجه ریزی',
                'مجموع قطعه کشتار شده',
                'مجموع وزن کل کشتارشده',
                'مانده در سالن(قطعه)',
                'مانده در سالن از نود درصد(قطعه)',
                'کمترین سن',
                'بیشترین سن',
                'مجموع وزن تعهد دولتی',
                ' مجموع قطعه کشتار دولتی',
                ' مجموع وزن کشتار دولتی',
                ' مجموع قطعه کشتار آزاد',
                ' مجموع وزن کشتار آزاد',
                'مجموع تعداد کشتار خارج از استان',
                'مجموع وزن کشتار خارج از استان'

            ]

            for col_num, option in enumerate(header_list, 5):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20

            # worksheet['A1'] = f' وضعیت پرونده ها'
            worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B2:C3'
            # merge_range2 = 'B2:C2'

            worksheet.merge_cells(merge_range1)
            # worksheet.merge_cells(merge_range2)
            worksheet['B2'].font = red_font

            # cell = worksheet.cell(row=1, column=1)
            # cell.alignment = Alignment(horizontal='center', vertical='center')
            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 20.01
                worksheet.row_dimensions[6].height = 22
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            l = 5
            m = 1
            all_poultry_hatching_quantity = 0
            all_poultry_hatching_killed_quantity = 0
            all_poultry_hatching_left_over = 0
            min_list = []
            all_left_over_ninty_percent = 0
            for poultry_hatching in filtered_poultry_hatch:
                all_poultry_hatching_quantity += poultry_hatching.quantity
                all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity
                all_poultry_hatching_left_over += poultry_hatching.left_over
                if poultry_hatching.chicken_age not in min_list:
                    min_list.append(poultry_hatching.chicken_age)

                l += 1
                create_date = jdatetime.date.fromgregorian(
                    day=poultry_hatching.create_date.day,
                    month=poultry_hatching.create_date.month,
                    year=poultry_hatching.create_date.year
                )
                date = jdatetime.date.fromgregorian(
                    day=poultry_hatching.date.day,
                    month=poultry_hatching.date.month,
                    year=poultry_hatching.date.year
                )
                age = (datetime.datetime.now().date() - poultry_hatching.date.date()).days + 1

                creator = '-'
                if poultry_hatching.registrar:
                    if poultry_hatching.registrar['fullname'] != '':
                        creator = poultry_hatching.registrar['fullname']
                else:
                    creator = 'پنجره واحد'
                left_over_ninty_percent = ((poultry_hatching.quantity * 90) / 100) - poultry_hatching.killed_quantity
                all_left_over_ninty_percent += left_over_ninty_percent
                list1 = [
                    m,
                    poultry_hatching.poultry.user.fullname,
                    poultry_hatching.poultry.unit_name,
                    poultry_hatching.poultry.user.mobile,
                    poultry_hatching.poultry.breeding_unique_id,
                    poultry_hatching.poultry.system_code,
                    poultry_hatching.hall,
                    poultry_hatching.period,
                    str(create_date),
                    str(date),
                    poultry_hatching.chicken_breed,
                    age,
                    poultry_hatching.quantity,
                    poultry_hatching.losses,
                    poultry_hatching.killed_quantity,
                    poultry_hatching.total_killed_weight,
                    poultry_hatching.left_over,
                    left_over_ninty_percent,
                    poultry_hatching.total_commitment,
                    poultry_hatching.governmental_quantity,
                    poultry_hatching.governmental_killed_quantity,
                    poultry_hatching.free_quantity,
                    poultry_hatching.free_killed_quantity,
                    str(poultry_hatching.total_average_killed_weight),
                    creator,
                    poultry_hatching.poultry.epidemiological_code if poultry_hatching.poultry.epidemiological_code else '-',
                    poultry_hatching.out_province_killed_quantity if poultry_hatching.out_province_killed_quantity > 0 else '-',
                    poultry_hatching.out_province_killed_weight if poultry_hatching.out_province_killed_weight > 0 else '-',
                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    value = list1[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center')
            min_list = sorted(min_list)
            all_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('losses')).get(
                'total_quantity', 0)
            all_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get(
                'total_quantity', 0)
            all_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get(
                'total_quantity', 0)
            all_total_commitment = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight = filtered_poultry_hatch.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list = [
                len(filtered_poultry_hatch),
                all_poultry_hatching_quantity,
                all_poultry_hatching_killed_quantity,
                all_total_killed_weight,
                all_poultry_hatching_left_over,
                all_left_over_ninty_percent,
                min_list[0] if len(min_list) > 0 else '-',
                min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                all_out_province_killed_quantity,
                all_out_province_killed_weight
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_quantity,
                all_losses,
                all_killed_quantity,
                all_total_killed_weight,
                all_left_over,
                all_left_over_ninty_percent,
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                '',
                '',
                '',
                all_out_province_killed_quantity,
                all_out_province_killed_weight,

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'بارهای احراز شده مغایرت دار':
            filtered_kill_reqs_qarantine = filtered_kill_reqs.filter(
                Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity'))
                , quarantine_quantity__isnull=False)
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)
            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای احراز شده دارای مغایرت',
                'تعداد بارهای دارای کشتارکن اختصاصی',
                'مجموع تعداد قطعه بارهای احراز شده دارای مغایرت',
                'مجموع وزن بارهای احراز شده دارای مغایرت',
                'تعداد بارهای احراز شده دارای مغایرت دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای احراز شده دارای مغایرت در قرنطینه'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ ({from_date_1}) تا تاریخ ({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_qarantine.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_qarantine.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_qarantine.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_qarantine.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_qarantine.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_qarantine.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_qarantine.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_reqs_qarantine:
                for kill in filtered_kill_reqs_qarantine:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_qarantine.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_qarantine.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(filtered_kill_reqs_qarantine.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_qarantine),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'بارهای فاقد قرنطینه تخلیه شده':

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای فاقد قرنطینه تخلیه شده',
                'تعداد بارهای دارای کشتارکن اختصاصی',
                'مجموع تعداد قطعه بارهای فاقد قرنطینه تخلیه شده',
                'مجموع وزن بارهای فاقد قرنطینه تخلیه شده',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای فاقد قرنطینه تخلیه شده'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_code_but_have_assigment.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_code_but_have_assigment.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_reqs_not_code_but_have_assigment:
                for kill in filtered_kill_reqs_not_code_but_have_assigment:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_code_but_have_assigment.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_code_but_have_assigment.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_code_but_have_assigment),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'بارهای عدم احراز از قرنطینه':
            filtered_kill_reqs_havent_qarantine_quantity = filtered_kill_reqs.filter(quarantine_quantity__isnull=True,
                                                                                     clearance_code__isnull=False)

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای عدم احراز از قرنطینه',
                'تعداد بارهای دارای کشتارکن اختصاصی',

                'مجموع تعداد قطعه بارهای عدم احراز از قرنطینه',
                'مجموع وزن بارهای عدم احراز از قرنطینه',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای عدم احراز از قرنطینه'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_havent_qarantine_quantity.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_havent_qarantine_quantity.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_havent_qarantine_quantity.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_havent_qarantine_quantity.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_havent_qarantine_quantity.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_havent_qarantine_quantity.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_havent_qarantine_quantity.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_reqs_havent_qarantine_quantity:
                for kill in filtered_kill_reqs_havent_qarantine_quantity:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_havent_qarantine_quantity.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_havent_qarantine_quantity.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(filtered_kill_reqs_havent_qarantine_quantity.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_havent_qarantine_quantity),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'بارهای تخلیه نشده با کد قرنطینه':
            filtered_kill_reqs_not_assigment_but_have_code = filtered_kill_reqs.filter(
                Q(assignment_state_archive='pending')
                | Q(vet_state='pending'), clearance_code__isnull=False)

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای تخلیه نشده با کد قرنطینه',
                'تعداد بارهای دارای کشتارکن اختصاصی',

                'مجموع تعداد قطعه بارهای تخلیه نشده با کد قرنطینه',
                'مجموع وزن بارهای تخلیه نشده با کد قرنطینه',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای تخلیه نشده با کد قرنطینه'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_assigment_but_have_code.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_assigment_but_have_code.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_reqs_not_assigment_but_have_code:
                for kill in filtered_kill_reqs_not_assigment_but_have_code:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_assigment_but_have_code.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_assigment_but_have_code.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment_but_have_code),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'تخلیه نشده-تحویل گرفته شده':
            filtered_kill_reqs_not_assigment_but_have_code = filtered_kill_reqs.filter(
                vet_state='pending', assignment_state_archive='True')

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای تخلیه نشده با کد قرنطینه',
                'تعداد بارهای دارای کشتارکن اختصاصی',

                'مجموع تعداد قطعه بارهای تخلیه نشده با کد قرنطینه',
                'مجموع وزن بارهای تخلیه نشده با کد قرنطینه',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'تخلیه نشده/تحویل گرفته شده'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_assigment_but_have_code.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_assigment_but_have_code.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_reqs_not_assigment_but_have_code:
                for kill in filtered_kill_reqs_not_assigment_but_have_code:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_assigment_but_have_code.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_assigment_but_have_code.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment_but_have_code),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'تخلیه شده-عدم تکمیل':
            filtered_kill_reqs_not_assigment = filtered_kill_reqs.filter(vet_state='accepted',
                                                                         assignment_state_archive='pending')

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای تکمیل نشده توسط کشتارگاه',
                'تعداد بارهای دارای کشتارکن اختصاصی',
                'مجموع تعداد قطعه بارهای تکمیل نشده توسط کشتارگاه',
                'مجموع وزن بارهای تکمیل نشده توسط کشتارگاه',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'تخلیه شده/عدم تکمیل'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_assigment.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_assigment.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_assigment.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_reqs_not_assigment:
                for kill in filtered_kill_reqs_not_assigment:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'

                    net_weighte = '-'
                    real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_assigment.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_assigment.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(filtered_kill_reqs_not_assigment.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'بارهای تخلیه نشده-عدم تکمیل':
            filtered_kill_not_assigment = filtered_kill_reqs.filter(vet_state='pending',
                                                                    assignment_state_archive='pending')

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای تخلیه نشده',
                'تعداد بارهای دارای کشتارکن اختصاصی',
                'مجموع تعداد قطعه بارهای تخلیه نشده',
                'مجموع وزن بارهای تخلیه نشده',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای بارهای تخلیه نشده'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_not_assigment.filter(vet_state='accepted'))
            bar_complete = filtered_kill_not_assigment.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_not_assigment.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_not_assigment:
                for kill in filtered_kill_not_assigment:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'

                    net_weighte = '-'
                    real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_not_assigment.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(filtered_kill_not_assigment.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_not_assigment),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'بارهای تخلیه شده- تکمیل شده':
            filtered_kill_not_assigment = filtered_kill_reqs.filter(vet_state='accepted',
                                                                    assignment_state_archive='True')

            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                ' کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                'کشتارکن اختصاصی',
                'تلفن کشتارکن اختصاصی',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارهای تخلیه نشده',
                'تعداد بارهای دارای کشتارکن اختصاصی',

                'مجموع تعداد قطعه بارهای تخلیه نشده',
                'مجموع وزن بارهای تخلیه نشده',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای تخلیه شده/ تکمیل شده'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_not_assigment.filter(vet_state='accepted'))
            bar_complete = filtered_kill_not_assigment.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_not_assigment.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)
            killer_exclusive = 0
            if filtered_kill_not_assigment:
                for kill in filtered_kill_not_assigment:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'

                    net_weighte = '-'
                    real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill.get('province_request__poultry_request__send_date').date() -
                           kill.get('province_request__poultry_request__hatching__date').date()).days + 1
                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    name_killer_exclusive = '-'
                    mobile_killer_exclusive = '-'
                    if kill.get('killer') != None:
                        name_killer_exclusive = kill['killer__name']
                        mobile_killer_exclusive = str(kill['killer__kill_house_operator__user__mobile'])
                        killer_exclusive += 1
                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        freez_state,
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        name_killer_exclusive,
                        mobile_killer_exclusive,
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_not_assigment.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_not_assigment.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(filtered_kill_not_assigment.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_not_assigment),
                killer_exclusive,
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        else:
            worksheet[
                'E2'] = 'گزارش کلی فارم های فعال و بایگانی شده مرغ گوشتی دارای مانده در سالن بیشتر از 11 درصد بین بازه سنی 55 روز  تا  90 روز'

            worksheet['A2'] = f'این گزارش در مورخ {now_date_1} صادر شده است.'

            worksheet['E2'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'E2:K2'
            merge_range2 = 'A2:C2'
            # merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            # worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            # worksheet['B1'].font = red_font
            # worksheet['B3'].font = Font(size=11)
            worksheet['E2'].font = Font(size=10)
            worksheet['A2'].font = Font(size=10, color="C00000")

            header_list = [
                'تعداد فارم فعال',
                'تعداد فارم بایگانی شده',
                'مجموع جوجه ریزی',
                'مجموع قطعه کشتار شده',
                'مجموع وزن  کشتارشده',
                'جمع کل مانده در سالن(قطعه)',
                'جمع مانده در سال فارم فعال(قطعه)',
                'جمع مانده در سالن فارم بایگانی(قطعه)',
                'کمترین سن ',
                'بیشترین سن ',
                'مجموع وزن تعهد دولتی',
                ' مجموع قطعه کشتار دولتی',
                ' مجموع وزن کشتار دولتی',
                ' مجموع قطعه کشتار آزاد',
                ' مجموع وزن کشتار آزاد',
                'مجموع تعداد کشتار خارج از استان',
                'مجموع وزن کشتار خارج از استان'

            ]

            for col_num, option in enumerate(header_list, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=3, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFFFFF", fill_type="solid")
                cell.font = Font(size=8, bold=True, color='538135')
                worksheet.row_dimensions[3].height = 28.8
                worksheet.column_dimensions[col_letter].width = 11.95
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium', color='A8D08D'),
                    right=openpyxl.styles.Side(style='medium', color='A8D08D'),
                    top=openpyxl.styles.Side(style='medium', color='A8D08D'),
                    bottom=openpyxl.styles.Side(style='medium', color='A8D08D')
                )

            min_list = []
            all_left_over_ninty_percent = 0
            len_archive_hatch = 0
            len_hatch = 0
            left_over_archive = 0
            left_over = 0
            for poultry_hatching in hatching_between_50_70:
                if poultry_hatching.archive == True and poultry_hatching.allow_hatching == 'True':
                    len_archive_hatch += 1
                    left_over_archive += poultry_hatching.left_over
                if poultry_hatching.archive == False and poultry_hatching.allow_hatching == 'pending':
                    len_hatch += 1
                    left_over += poultry_hatching.left_over
                if poultry_hatching.chicken_age not in min_list:
                    min_list.append(poultry_hatching.chicken_age)

                left_over_ninty_percent = ((
                                                   poultry_hatching.quantity * 90) / 100) - poultry_hatching.killed_quantity
                all_left_over_ninty_percent += left_over_ninty_percent

            min_list = sorted(min_list)
            all_total_commitment = hatching_between_50_70.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_poultry_hatching_killed_quantity = hatching_between_50_70.aggregate(
                total_quantity=Sum('killed_quantity')).get(
                'total_quantity', 0)
            all_poultry_hatching_quantity = hatching_between_50_70.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_poultry_hatching_left_over = hatching_between_50_70.aggregate(total_quantity=Sum('left_over')).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)
            all_age1 = sorted(all_age)
            value_header_list = [
                len_hatch,
                len_archive_hatch,
                all_poultry_hatching_quantity,
                all_poultry_hatching_killed_quantity,
                all_total_killed_weight,
                all_poultry_hatching_left_over,
                left_over_archive,
                left_over,

                min_list[0] if len(min_list) > 0 else '-',
                min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                all_out_province_killed_quantity,
                all_out_province_killed_weight
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=4, column=item + 1, value=value_header_list[item])
                cell.fill = PatternFill(start_color="E2EFD9", fill_type="solid")

                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center', wrap_text=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium', color='A8D08D'),
                    right=openpyxl.styles.Side(style='medium', color='A8D08D'),
                    top=openpyxl.styles.Side(style='medium', color='A8D08D'),
                    bottom=openpyxl.styles.Side(style='medium', color='A8D08D')
                )
            worksheet[
                'A6'] = f'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی'

            worksheet['A7'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
            worksheet['F7'] = f'اطلاعات کلی بارها'
            worksheet['G11'] = f'تفکیک بارهای دولتی,آزاد و خارج از استان'
            worksheet['E15'] = f'اطلاعات بارهای تخلیه شده و تکمیل شده توسط کشتارگاه'
            worksheet['F19'] = f'اطلاعات بارهای تخلیه نشده و تکمیل نشده توسط کشتارگاه'
            worksheet['F23'] = f'تعداد قطعه نهایی کم شده از سالن مرغدار(ملاک کشتار)'
            worksheet['M11'] = f'درمجموع بارها محاسبه نمیشود*'

            worksheet['A6'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A7'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['F7'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['G11'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['E15'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['F19'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['F23'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['M11'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A6:D6'
            merge_range2 = 'A7:D7'
            merge_range3 = 'F7:J7'
            merge_range4 = 'G11:J11'
            merge_range5 = 'E15:K15'
            merge_range6 = 'F19:I19'
            merge_range7 = 'F23:I23'
            merge_range8 = 'M11:N11'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet['A6'].font = Font(size=10)
            worksheet['A7'].font = Font(size=9)
            worksheet['F7'].font = Font(size=11)
            worksheet['F11'].font = Font(size=11)
            worksheet['D15'].font = Font(size=11)
            worksheet['F19'].font = Font(size=10)
            worksheet['F23'].font = Font(size=8)
            worksheet['M11'].border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
            worksheet['M11'].fill = PatternFill(start_color="E9CFAF", fill_type="solid")
            header_list3 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',
                'کمترین سن کشتار',
                'بیشترین سن کشتار',
                'میانگین سنی کشتار',

            ]
            for col_num, option in enumerate(header_list3, 2):
                cell = worksheet.cell(row=8, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=8, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[8].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            header_list2 = [
                'تعداد بارهای ایجاد شده',
                'مجموع تعداد قطعه بارهای ایجاد شده',
                'مجموع وزن بارها ایجاد شده',
                'میانگین وزن',

            ]
            for col_num, option in enumerate(header_list2, 8):
                cell = worksheet.cell(row=8, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=8, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[8].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            header_list4 = [

                'تعداد بارهای دارای کد قرنطینه',
                'مجموع قطعه بارهای دارای کد قرنطینه',

            ]
            for col_num, option in enumerate(header_list4, 12):
                cell = worksheet.cell(row=8, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="C5E0B3", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[8].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            header_list5 = [
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',

            ]
            for col_num, option in enumerate(header_list5, 14):
                cell = worksheet.cell(row=8, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="8EAADB", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[8].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            header_list6 = [
                'تعداد بارهای فاقد کد قرنطینه',
                'مجموع قطعه بارهای فاقد کد قرنطینه',
                'تعداد بارهایی که در  قرنطینه و رصدیار اختلاف دارند',
            ]
            for col_num, option in enumerate(header_list6, 16):
                cell = worksheet.cell(row=8, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFF2CC", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[8].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            header_list7 = [
                'حجم بارها',
                'وزن بارها',

            ]
            for col_num, option in enumerate(header_list7, 19):
                cell = worksheet.cell(row=8, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=8, bold=True, color='FFFFFF')
                worksheet.row_dimensions[8].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            all_weighte = 0
            for kill in filtered_kill_reqs:
                w = kill.get(
                    'province_kill_request__province_request__poultry_request__Index_weight')
                weight = kill.get('quantity') * w
                all_weighte += weight

            difference_bar = len(filtered_kill_reqs.filter(~Q(quantity=F('quarantine_quantity'))))

            hasnt_code = filtered_kill_reqs.filter(clearance_code__isnull=True)
            all_quarantine_quantity_hasnt_code = hasnt_code.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            has_code = filtered_kill_reqs.filter(clearance_code__isnull=False)
            all_quarantine_quantity_has_code = has_code.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            has_qarantine = filtered_kill_reqs.filter(quarantine_quantity__isnull=False)
            all_has_qarantine = has_qarantine.aggregate(total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)

            accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            value_header = [
                len(poultry_request),
                total_requests_quantity if total_requests_quantity != None else 0,
                total_requests_weight if total_requests_weight != None else 0,
                all_age1[0] if len(all_age1) > 0 else '-',
                all_age1[len(all_age1) - 1] if len(all_age1) > 0 else '-',
                (sum(all_age1) / len(all_age1)) if len(all_age1) > 0 else '-',
                len(filtered_kill_reqs),
                all_quantity if all_quantity != None else 0,
                all_weighte,
                round(all_weighte / all_quantity, 1) if all_weighte > 0 and all_quantity > 0 else 0,
                len(has_code),
                all_quarantine_quantity_has_code if all_quarantine_quantity_has_code != None else 0,
                len(has_qarantine),
                all_has_qarantine if all_has_qarantine != None else 0,
                len(hasnt_code),
                all_quarantine_quantity_hasnt_code if all_quarantine_quantity_hasnt_code != None else 0,
                difference_bar,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header)):
                cell = worksheet.cell(row=9, column=item + 2, value=value_header[item])
                value = value_header[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            header_list7 = [
                'تعداد بار دولتی',
                'مجموع قطعه بارهای دولتی',
                'مجموع وزن بارهای دولتی',
                'بارهای دولتی دارای احراز شده قرنطینه',
                'تعداد  قطعه دولتی احراز شده از قرنطینه',
            ]

            for col_num, option in enumerate(header_list7, 2):
                cell = worksheet.cell(row=12, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=8, bold=True, color='FFFFFF')
                worksheet.row_dimensions[12].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            header_list8 = [
                'تعداد بارهای آزاد',
                'مجموع قطعه بارهای آزاد',
                'مجموع وزن بارهای آزاد',
                'بارهای آزاد احراز شده از قرنطینه',
                'مجموع تعداد قطعه بارهای آزاد احراز شده از قرنطینه',
                'کل بارهای آزاد دارای کد قرنطینه',

            ]
            header_listx = [
                'تعداد  بارهای خارج از استان',
                'مجموع قطعه بارهای خارج از استان',
            ]
            for col_num, option in enumerate(header_list8, 7):
                cell = worksheet.cell(row=12, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFE599", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[12].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            for col_num, option in enumerate(header_listx, 13):
                cell = worksheet.cell(row=12, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="E9CFAF", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[12].height = 42.8
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )

            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)
            accepted_real_wight_bar_government = bar_government.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 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', 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', 0)
            accepted_real_wight_bar_free = bar_free.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 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', 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', 0)

            value_header_free_and_goverment_bar = [
                len(bar_government),
                accepted_real_quantity_bar_government if accepted_real_quantity_bar_government != None else 0,
                accepted_real_wight_bar_government if accepted_real_wight_bar_government != None else 0,
                len(bar_government_quarantine_quantity),
                accepted_real_quantity_bar_government_quarantine_quantity if accepted_real_quantity_bar_government_quarantine_quantity != None else 0,
                len(bar_free),
                accepted_real_quantity_bar_free if accepted_real_quantity_bar_free != None else 0,
                accepted_real_wight_bar_free if accepted_real_wight_bar_free != None else 0,
                len(bar_free_quarantine_quantity),
                accepted_real_quantity_bar_free_quarantine_quantity if accepted_real_quantity_bar_free_quarantine_quantity != None else 0,
                bar_free_has_code,
                len(out_true_poultry_request),
                quantity_out_true_poultry_request if quantity_out_true_poultry_request != None else 0,

            ]
            for item in range(len(value_header_free_and_goverment_bar)):
                cell = worksheet.cell(row=13, column=item + 2, value=value_header_free_and_goverment_bar[item])
                value = value_header_free_and_goverment_bar[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )

            header_list_bar_complete = [

                'تعداد بارتخلیه شده دامپزشک',
                'مجموع تعداد قطعه تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',

            ]
            header_list_bar_completex2 = [f'وزن لاشه مرغ بعد از کسر {25} % افت',
                                          ]
            header_list_bar_completex = ['تعداد بار ورودی به کشتارگاه',
                                         'مجموع قطعه بارهای ورودی به کشتارگاه',
                                         'وزن بارهای ورودی به کشتارگاه',
                                         'میانگین وزن',
                                         ]
            for col_num, option in enumerate(header_list_bar_completex, 2):
                cell = worksheet.cell(row=16, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="F3CC85", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[16].height = 42
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            for col_num, option in enumerate(header_list_bar_completex2, 6):
                cell = worksheet.cell(row=16, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FF7979", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[16].height = 42
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            for col_num, option in enumerate(header_list_bar_complete, 7):
                cell = worksheet.cell(row=16, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="F4B083", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[16].height = 42
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            header_list_bar_complete2 = [
                'تعداد بارهای تکمیل شده کشتارگاه',
                'مجموع تعداد قطعه نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',

            ]
            header_list_bar_complete2x = ['بارهای تخلیه شده فاقد کد قرنطینه',
                                          'قطعه بارهای تخلیه شده فاقد کد قرنطینه',
                                          'وزن بارهای تخلیه شده فاقد کد قرنطینه', ]
            for col_num, option in enumerate(header_list_bar_complete2, 10):
                cell = worksheet.cell(row=16, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="BDD6EE", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[16].height = 42
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            for col_num, option in enumerate(header_list_bar_complete2x, 13):
                cell = worksheet.cell(row=16, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="AEF8FE", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[16].height = 42
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            bar_complete_with_kill_house_and_vet = filtered_kill_reqs.filter(
                ware_house_confirmation=True)
            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('ware_house_accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight_with_kill_house_and_vet = bar_complete_with_kill_house_and_vet.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight')).get(
                'total_quantity', 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', 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', 0)
            bar_complete_with_kill_house = filtered_kill_reqs.filter(Q(ware_house_confirmation=True)|
                                                                     Q(assignment_state_archive='True'))

            accepted_real_quantity_final = bar_complete_with_kill_house.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight_final = bar_complete_with_kill_house.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            accepted_real_quantity_no_code = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight_no_code = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 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
            value_header_complete_bar = [
                len(bar_complete_with_kill_house_and_vet),
                accepted_real_quantity_with_kill_house_and_vet if accepted_real_quantity_with_kill_house_and_vet != None else 0,
                accepted_real_wight_with_kill_house_and_vet if accepted_real_wight_with_kill_house_and_vet != None else 0,
                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 != None else 0,
                less_25,
                len(bar_complete_with_vet),
                all_vet_accepted_real_quantity_with_kill_house_and_vet if all_vet_accepted_real_quantity_with_kill_house_and_vet != None else 0,
                all_vet_accepted_real_weight_with_kill_house_and_vet if all_vet_accepted_real_weight_with_kill_house_and_vet != None else 0,
                len(bar_complete_with_kill_house),
                accepted_real_quantity_final if accepted_real_quantity_final != None else 0,
                accepted_real_wight_final if accepted_real_wight_final != None else 0,
                len(filtered_kill_reqs_not_code_but_have_assigment),
                accepted_real_quantity_no_code if accepted_real_quantity_no_code != None else 0,
                accepted_real_wight_no_code if accepted_real_wight_no_code != None else 0,

            ]
            for item in range(len(value_header_complete_bar)):
                cell = worksheet.cell(row=17, column=item + 2, value=value_header_complete_bar[item])
                value = value_header_complete_bar[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )

            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)
            accepted_real_wight_not_assigment_all = filtered_kill_reqs_not_assigment_all.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 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', 0)
            accepted_real_wight_havent_kill_house = filtered_kill_reqs_havent_kill_house.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            header_list_not_assigment = [
                'تعداد  بار تخلیه نشده',
                'مجموع قطعه بار های تخلیه نشده',
                'وزن بارهای تخلیه نشده',
            ]

            for col_num, option in enumerate(header_list_not_assigment, 5):
                cell = worksheet.cell(row=20, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="DA9694", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[20].height = 57
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            header_list_not_assigment2 = [
                'بارهای تخلیه شده و عدم تکمیل توسط کشتارگاه',
                'قطعه بارهای تخلیه شده و عدم تکمیل توسط کشتارگاه',
                'وزن بارهای  تخلیه شده و عدم تکمیل توسط کشتارگاه',
            ]

            for col_num, option in enumerate(header_list_not_assigment2, 8):
                cell = worksheet.cell(row=20, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FABF8F", fill_type="solid")
                cell.font = Font(size=8, bold=True)
                worksheet.row_dimensions[20].height = 57
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )

            value_header_list_not_assigment = [
                len(filtered_kill_reqs_not_assigment_all),
                accepted_real_quantity_not_assigment_all if accepted_real_quantity_not_assigment_all != None else 0,
                accepted_real_wight_not_assigment_all if accepted_real_wight_not_assigment_all != None else 0,
                len(filtered_kill_reqs_havent_kill_house),
                accepted_real_quantity_havent_kill_house if accepted_real_quantity_havent_kill_house != None else 0,
                accepted_real_wight_havent_kill_house if accepted_real_wight_havent_kill_house != None else 0,

            ]
            for item in range(len(value_header_list_not_assigment)):
                cell = worksheet.cell(row=21, column=item + 5, value=value_header_list_not_assigment[item])
                value = value_header_list_not_assigment[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )

            accepted_real_quantity_final = filtered_kill_reqs.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_weight_final = filtered_kill_reqs.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)
            header_final = [
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',
            ]

            for col_num, option in enumerate(header_final, 7):
                cell = worksheet.cell(row=24, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=8, bold=True, color='FFFFFF')
                worksheet.row_dimensions[24].height = 31
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            value_header_final = [
                accepted_real_quantity_final if accepted_real_quantity_final != None else 0,
                accepted_real_weight_final if accepted_real_weight_final != None else 0,

            ]
            for item in range(len(value_header_final)):
                cell = worksheet.cell(row=25, column=item + 7, value=value_header_final[item])
                value = value_header_final[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='thin'),
                    right=openpyxl.styles.Side(style='thin'),
                    top=openpyxl.styles.Side(style='thin'),
                    bottom=openpyxl.styles.Side(style='thin')
                )
            names_list = []
            tomorrow_date1 = date1 + timedelta(days=1)
            tomorrow_date2 = date2 + timedelta(days=1)
            from_date = jdatetime.date.fromgregorian(
                year=tomorrow_date1.year,
                month=tomorrow_date1.month,
                day=tomorrow_date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            tommorow_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=tomorrow_date2.year,
                month=tomorrow_date2.month,
                day=tomorrow_date2.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            tomorrow_date_2 = separate.join(reversed_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=tomorrow_date1,
                date__date__lte=tomorrow_date2, trash=False)
            for kill in kill_house_ware_houses:
                if kill.kill_house.name not in names_list:
                    names_list.append(kill.kill_house.name)

            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']
            abc_list = ['A', 'B', 'D', 'F', 'H', 'J', 'L', 'N', 'P', 'S', 'R']

            from_date = jdatetime.date.fromgregorian(
                year=date1.year,
                month=date1.month,
                day=date1.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            from_date_1 = separate.join(reversed_date)

            to_date = jdatetime.date.fromgregorian(
                year=date2.year,
                month=date2.month,
                day=date2.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(to_date.split("-"))
            separate = "-"
            to_date_1 = separate.join(reversed_date)

            worksheet.row_dimensions[27].height = 47
            # worksheet.row_dimensions[3].height = 30
            # worksheet.row_dimensions[5].height = 19.04
            # worksheet.row_dimensions[8].height = 32

            for abc in abc_list:
                worksheet[f'{abc}28'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            withe_font = Font(size=10, color='D9FFFFFF')
            blue = PatternFill(start_color="4472C4", fill_type="solid")
            worksheet['A26'] = f'اطلاعات کلی توزیع و پخش مرغ از تاریخ {tommorow_date_1} تا {tomorrow_date_2}'
            worksheet['G27'] = f'توزیع از کشتارگاه به مباشر و صنف'
            worksheet['A28'] = f'تعداد خریداران'
            worksheet['B28'] = f'ورودی از سردخانه'
            worksheet['D28'] = f'پیش سرد'
            worksheet['F28'] = f'خرید خارج از استان'
            worksheet['H28'] = f'بارهای روزانه'
            worksheet['J28'] = f'جمع کل انبار'
            worksheet['L28'] = f'توزیع شده'
            worksheet['N28'] = f'توزیع / تحویل شده'
            worksheet['P28'] = f'مانده انبار'
            worksheet['R28'] = f'تعداد مباشر تخصیص داده شده'
            worksheet['S28'] = f'تعداد صنف تخصیص داده شده'

            worksheet['G27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A26'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['B28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['D28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['H28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['J28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['L28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['N28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['P28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['R28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['S28'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            merge_range12 = 'G27:L27'
            merge_range0 = 'A26:D27'
            merge_range1 = 'A28:A30'
            merge_range2 = 'B28:C29'
            merge_range3 = 'D28:E29'
            merge_range4 = 'H28:I29'
            merge_range5 = 'J28:K29'
            merge_range6 = 'L28:M29'
            merge_range7 = 'N28:O29'
            merge_range8 = 'P28:Q29'
            merge_range9 = 'R28:R30'
            merge_range10 = 'S28:S30'
            merge_range11 = 'F28:G29'

            worksheet.merge_cells(merge_range12)
            worksheet.merge_cells(merge_range0)
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)
            worksheet.merge_cells(merge_range10)
            worksheet.merge_cells(merge_range11)

            worksheet['A26'].font = red_font
            worksheet['G27'].font = red_font
            worksheet['A28'].font = withe_font
            worksheet['B28'].font = withe_font
            worksheet['D28'].font = withe_font
            worksheet['F28'].font = withe_font
            worksheet['H28'].font = withe_font
            worksheet['J28'].font = withe_font
            worksheet['L28'].font = withe_font
            worksheet['N28'].font = withe_font
            worksheet['P28'].font = withe_font
            worksheet['R28'].font = withe_font
            worksheet['S28'].font = withe_font

            worksheet['A28'].fill = blue
            worksheet['B28'].fill = blue
            worksheet['D28'].fill = blue
            worksheet['F28'].fill = blue
            worksheet['H28'].fill = blue
            worksheet['J28'].fill = blue
            worksheet['L28'].fill = blue
            worksheet['N28'].fill = blue
            worksheet['P28'].fill = blue
            worksheet['R28'].fill = blue
            worksheet['S28'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

            for item in range(len(list1)):
                cell = worksheet.cell(row=30, column=item + 2, value=list1[item])
                worksheet.row_dimensions[30].height = 19

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            head_list1 = [len(names_list)
                , 0,
                          0,
                          total_pre_cold_quantity if total_pre_cold_quantity != None else 0,
                          total_pre_cold_weight if total_pre_cold_weight != None else 0,
                          total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                          total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                          total_number_of_carcasses if total_number_of_carcasses != None else 0,
                          total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                          final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                          final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                          total_allocated_quantity if total_allocated_quantity != None else 0,
                          total_allocated_weight if total_allocated_weight != None else 0,
                          total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                          total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                          total_remain_quantity if total_remain_quantity != None else 0,
                          total_remain_weight if total_remain_weight != None else 0,
                          number_of_steward,
                          number_of_guild,

                          ]
            for item in range(len(head_list1)):
                cell = worksheet.cell(row=31, column=item + 1, value=head_list1[item])
                worksheet.row_dimensions[31].height = 12
                value = head_list1[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            abc_list = ['A', 'B', 'D', 'F', 'H', 'J', 'L', 'N', 'P', 'R']

            for abc in abc_list:
                worksheet[f'{abc}36'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            withe_font = Font(size=10, color='D9FFFFFF')
            blue = PatternFill(start_color="4472C4", fill_type="solid")
            worksheet['A34'] = f'اطلاعات کلی توزیع و پخش مرغ از تاریخ {tommorow_date_1} تا {tomorrow_date_2}'
            worksheet['G34'] = f'توزیع از مباشر به صنف'
            worksheet['A36'] = f'تعداد خریداران'
            worksheet['B36'] = f'ورودی از سردخانه'
            worksheet['D36'] = f'پیش سرد'
            worksheet['F36'] = f'خرید خارج از استان'
            worksheet['H36'] = f'بارهای روزانه'
            worksheet['J36'] = f'جمع کل انبار'
            worksheet['L36'] = f'توزیع شده'
            worksheet['N36'] = f'توزیع / تحویل شده'
            worksheet['P36'] = f'مانده انبار'
            worksheet['R36'] = f'تعداد صنف تخصیص داده شده'

            worksheet['G34'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A34'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['B36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['D36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['H36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['J36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['L36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['N36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['P36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['R36'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            merge_range12 = 'G34:L34'
            merge_range0 = 'A34:D35'
            merge_range1 = 'A36:A38'
            merge_range2 = 'B36:C37'
            merge_range3 = 'D36:E37'
            merge_range4 = 'H36:I37'
            merge_range5 = 'J36:K37'
            merge_range6 = 'L36:M37'
            merge_range7 = 'N36:O37'
            merge_range8 = 'P36:Q37'
            merge_range9 = 'R36:R38'
            merge_range11 = 'F36:G37'

            worksheet.merge_cells(merge_range12)
            worksheet.merge_cells(merge_range0)
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)
            worksheet.merge_cells(merge_range11)

            worksheet['A34'].font = red_font
            worksheet['G34'].font = red_font
            worksheet['A36'].font = withe_font
            worksheet['B36'].font = withe_font
            worksheet['D36'].font = withe_font
            worksheet['F36'].font = withe_font
            worksheet['H36'].font = withe_font
            worksheet['J36'].font = withe_font
            worksheet['L36'].font = withe_font
            worksheet['N36'].font = withe_font
            worksheet['P36'].font = withe_font
            worksheet['R36'].font = withe_font

            worksheet['A36'].fill = blue
            worksheet['B36'].fill = blue
            worksheet['D36'].fill = blue
            worksheet['F36'].fill = blue
            worksheet['H36'].fill = blue
            worksheet['J36'].fill = blue
            worksheet['L36'].fill = blue
            worksheet['N36'].fill = blue
            worksheet['P36'].fill = blue
            worksheet['R36'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

            for item in range(len(list1)):
                cell = worksheet.cell(row=38, column=item + 2, value=list1[item])
                worksheet.row_dimensions[38].height = 19

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            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_allocations = StewardAllocation.objects.filter(
                Q(type='manual') | Q(type='auto', system_registration_code=True),
                steward_ware_house__in=steward_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

            total_number_of_free_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_free_carcasses'))[
                'total']
            total_free_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_free_carcasses'))[
                'total']
            total_number_of_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_carcasses'))[
                'total']
            total_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_carcasses'))[
                'total']

            final_total_number_of_carcasses = \
                steward_ware_houses.aggregate(total=Sum('real_number_of_carcasses'))[
                    'total']
            final_total_weight_of_carcasses = \
                steward_ware_houses.aggregate(total=Sum('real_weight_of_carcasses'))[
                    'total']

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

            total_remain_weight = \
                steward_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']

            head_list1 = [number_of_steward,
                          0,
                          0,
                          0,
                          0,
                          total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                          total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                          total_number_of_carcasses if total_number_of_carcasses != None else 0,
                          total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                          final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                          final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                          total_allocated_quantity if total_allocated_quantity != None else 0,
                          total_allocated_weight if total_allocated_weight != None else 0,
                          total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                          total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                          total_remain_quantity if total_remain_quantity != None else 0,
                          total_remain_weight if total_remain_weight != None else 0,
                          number_of_guild,

                          ]
            for item in range(len(head_list1)):
                cell = worksheet.cell(row=39, column=item + 1, value=head_list1[item])
                worksheet.row_dimensions[39].height = 12
                value = head_list1[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش جزئیات کشتار.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def pos_excel(request):
    guilds = Guilds.objects.filter(trash=False, has_pos=False)

    if 'key' in request.GET:
        poss = POSMachine.objects.filter(pos_company__user__key=request.GET['key'], trash=False).select_related('user',
                                                                                                                'guild',
                                                                                                                'user__province',
                                                                                                                'user__city')
    else:
        poss = POSMachine.objects.filter(trash=False).select_related('user', 'guild', 'user__province', 'user__city')
    list1 = ['مشخصات کارتخوان ها', 'اصناف']

    date1 = datetime.datetime.now().date()
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)
    output = BytesIO()
    workbook = Workbook()
    for name in list1:
        min_list = []
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000")
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000", bold=True)
        if sheet_name == 'مشخصات کارتخوان ها':
            excel_options = [
                'ردیف',
                'نام واحد صنفی',
                'نام شخص(موبایل)',
                'کد ملی',
                'نوع فعالیت',
                'حوزه فعالیت',
                'استان شهر',
                'مباشر',
                'شرکت',
                'آی دی',
                'شماره پذیرنده',
                'شماره ترمینال',
            ]

            # برای بالای هدر

            worksheet['A1'] = f'گزارش مدیریت کارتخوان ها'
            worksheet['A3'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:B1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 21.01
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            l = 7
            m = 1
            for pos in poss:
                company_name = '-'
                if pos.pos_company is not None:
                    company_name = pos.pos_company.name

                if pos.guild.steward == True:
                    state = 'می باشد'
                else:
                    state = 'نمی باشد'
                receiver_number = '-'
                national_id = '-'
                if pos.receiver_number is not None:
                    receiver_number = pos.receiver_number
                if pos.user.national_id is not None:
                    national_id = pos.user.national_id
                list1 = [
                    m,
                    pos.guild.guilds_name,
                    pos.user.fullname + '(' + pos.user.mobile + ')',
                    national_id,
                    pos.guild.type_activity,
                    pos.guild.area_activity,
                    pos.user.province.name + '/' + pos.user.city.name,
                    state,
                    company_name,
                    pos.pos_id,
                    receiver_number,
                    pos.terminal_number

                ]

                for item in range(len(list1)):
                    cell = worksheet.cell(row=l, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                    worksheet.row_dimensions[l + 1].height = 24
                l += 1
                m += 1
        else:
            worksheet['A1'] = f'گزارش مدیریت اصناف فاقد کارتخوان'
            worksheet['A3'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

            worksheet['A3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['A1'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'A1:B1'
            merge_range2 = 'A2:B2'
            merge_range = 'A3:B3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['A1'].font = red_font
            worksheet['A3'].font = Font(size=11)
            excel_options = [
                'ردیف',
                'شناسه صنف',
                'نام واحد صنفی',
                'نام شخص/شرکت',
                'موبایل',
                'کد ملی',
                'نوع فعالیت',
                'حوزه فعالیت',
                'کد پستی',
                'شماره مجوز',
                'استان/شهر',
                'آدرس',
                'مباشر',
                'حداکثر تخصیص',
                'محدودیت مباشر',
                'کشتارگاه انتخابی',
                'کارتخوان دارد/ندارد',

            ]
            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=4, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 20.01
                worksheet.row_dimensions[4].height = 25
                worksheet.freeze_panes = worksheet['A5']
                max_col = worksheet.max_column
                range_str = f'A4:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            l = 4
            m = 1
            for guild in guilds:
                postal_code = guild.address.postal_code if guild.address.postal_code else '-'
                national_code = guild.user.national_code if guild.user.national_code else '-'
                steward = 'می باشد' if guild.steward == True else 'نمی باشد'
                max_allocation = 0
                if guild.allocation_limit:
                    max_allocation = guild.allocation_limit
                centers_allocations = '-'
                kill_house_centers_allocations = '-'
                if guild.centers_allocation != None:
                    for center_allocation in guild.centers_allocation:
                        centers_allocations = center_allocation['label']
                if guild.kill_house_centers_allocation != None:
                    for kill_house_centers_allocation in guild.kill_house_centers_allocation:
                        kill_house_centers_allocations = kill_house_centers_allocation['label']
                province = '-'
                if guild.user.province:
                    province = guild.user.province.name
                city = '-'
                if guild.user.city:
                    city = guild.user.city.name
                pos = 'دارد' if guild.has_pos == True else 'ندارد'
                list1 = [
                    m,
                    guild.guilds_id,
                    guild.guilds_name,
                    guild.user.fullname,
                    guild.user.mobile,
                    national_code,
                    guild.type_activity,
                    guild.area_activity,
                    postal_code,
                    guild.license_number,
                    province + '-' + city,
                    guild.address.address,
                    steward,
                    max_allocation,
                    centers_allocations,
                    kill_house_centers_allocations,
                    pos

                ]
                l += 1
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l, column=item + 1, value=list1[item])
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='thin'),
                        right=openpyxl.styles.Side(style='thin'),
                        top=openpyxl.styles.Side(style='thin'),
                        bottom=openpyxl.styles.Side(style='thin')
                    )
                    worksheet.row_dimensions[l + 1].height = 24

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="اکسل پوز.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    now_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(now_date.split("-"))
    separate = "-"
    now_fa_date = separate.join(reversed_date)
    filtered_poultry_hatch = (PoultryHatching.objects.filter(
        trash=False).select_related('poultry__user')
                              .only('quantity', 'killed_quantity', 'total_killed_weight', 'left_over',
                                    'total_commitment'
                                    , 'governmental_quantity', 'governmental_killed_quantity',
                                    'losses', 'free_killed_quantity', 'free_quantity', 'out_province_killed_quantity',
                                    'out_province_killed_weight', 'create_date',
                                    'date', 'registrar', 'poultry__user__fullname', 'poultry__unit_name',
                                    'poultry__user__mobile', 'poultry__breeding_unique_id', 'poultry__system_code',
                                    'hall', 'period', 'chicken_breed', 'killed_quantity', 'total_average_killed_weight',
                                    'poultry__epidemiological_code', 'chicken_age', 'poultry__key')
                              .values('quantity', 'killed_quantity', 'total_killed_weight', 'left_over',
                                      'total_commitment'
                                      , 'governmental_quantity', 'governmental_killed_quantity',
                                      'losses', 'free_killed_quantity', 'free_quantity', 'out_province_killed_quantity',
                                      'out_province_killed_weight', 'create_date',
                                      'date', 'registrar', 'poultry__user__fullname', 'poultry__unit_name',
                                      'poultry__user__mobile', 'poultry__breeding_unique_id', 'poultry__system_code',
                                      'hall', 'period', 'chicken_breed', 'killed_quantity',
                                      'total_average_killed_weight',
                                      'poultry__epidemiological_code', 'chicken_age', 'poultry__key')).order_by('-date')

    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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date', 'province_request',
                                              'province_request__poultry_request',
                                              'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state').values(
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date',
        'province_request',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
    )

    header_list_gt_60_header = [
        'تعداد فارم فعال',
        'مجموع جوجه ریزی',
        'مجموع قطعه کشتار شده',
        'مجموع وزن کل کشتارشده',
        'مانده در سالن(قطعه)',
        'مانده در سالن از نود درصد(قطعه)',
        'کمترین سن',
        'بیشترین سن',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان'

    ]

    header_list_between_50_60 = [
        'تعداد فارم فعال',
        'مجموع جوجه ریزی',
        'مجموع قطعه کشتار شده',
        'مجموع وزن کل کشتارشده',
        'مانده در سالن(قطعه)',
        'مانده در سالن از نود درصد(قطعه)',
        'کمترین سن',
        'بیشترین سن',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان'

    ]

    header_list_between_40_50 = [
        'تعداد فارم فعال',
        'مجموع جوجه ریزی',
        'مجموع قطعه کشتار شده',
        'مجموع وزن کل کشتارشده',
        'مانده در سالن(قطعه)',
        'مانده در سالن از نود درصد(قطعه)',
        'کمترین سن',
        'بیشترین سن',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان'

    ]

    header_list_no_license1 = [
        'تعداد فارم فعال',
        'مجموع جوجه ریزی',
        'مجموع قطعه کشتار شده',
        'مجموع وزن کل کشتارشده',
        'مانده در سالن(قطعه)',
        'مانده در سالن از نود درصد(قطعه)',
        'کمترین سن',
        'بیشترین سن',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان'

    ]

    header_list = [
        'تعداد بارها',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    excel_options = {
        'آمار کشتار روزانه': [],
        'فارم بالای 60 روز': [],
        'فارم بین 50 تا 60 روز': [],
        'فارم بین 40 تا 50 روز': [],
        'تخلیه فارم بدون مجوز': [],
        'دامپزشکان فارم مغایرت قرنطینه': [],
        'عدم تخلیه دامپزشک کشتارگاه': [],
        'بار های تخلیه نشده کشتارگاه': [],
        'بار های تخلیه شده فاقد قرنطینه': [],

    }
    output = BytesIO()
    workbook = Workbook()

    gte_60 = filtered_poultry_hatch.filter(archive=False,
                                           allow_hatching='pending', chicken_age__gt=60)

    between_50_60 = filtered_poultry_hatch.filter(archive=False,
                                                  allow_hatching='pending', chicken_age__gt=50,
                                                  chicken_age__lte=60)
    between_40_50 = filtered_poultry_hatch.filter(archive=False,
                                                  allow_hatching='pending', chicken_age__gte=40,
                                                  chicken_age__lte=50)

    no_license1 = filtered_poultry_hatch.filter(archive=False,
                                                allow_hatching='pending')

    filtered_kill_reqs_not_code_but_have_assigment = filtered_kill_reqs.filter(
        Q(clearance_code__isnull=True) | Q(quantity__gt=F('quarantine_quantity')) | Q(
            quantity__lt=F('quarantine_quantity')))

    filtered_kill_reqs_not_assigment_but_have_code = filtered_kill_reqs.filter(
        vet_state='pending')

    filtered_kill_reqs_not_assigment_but_have_code1 = filtered_kill_reqs.filter(
        assignment_state_archive='pending', vet_state='pending')

    filtered_kill_reqs__assigment_but_havent_code = filtered_kill_reqs.filter(Q(assignment_state_archive='True',
                                                                                vet_state='pending') | Q(
        vet_state='accepted'), clearance_code__isnull=True)

    for name, options in excel_options.items():
        min_list = []

        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000")

        for col_num, option in enumerate(options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=1, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')

            # worksheet.column_dimensions[col_letter].width = 20.01
            # worksheet.row_dimensions[1].height = 22

        if sheet_name == 'فارم بالای 60 روز':

            gt_60_header = [
                'ردیف',
                'نام و خانوادگی',
                'نام فارم',
                'موبایل',
                'کد یکتا',
                'کد سیستمی واحد',
                'سالن',
                ' دوره جوجه ریزی',
                'تاریخ ثبت جوجه ریزی',
                'تاریخ جوجه ریزی',
                'نژاد',
                'سن',
                'تعداد جوجه ریزی',
                'تلفات دوره',
                'تعداد کشتار شده(قطعه)',
                'وزن کل کشتارشده(کیلوگرم)',
                'مانده در سالن',
                'مانده در سالن از نود درصد',
                'وزن تعهد دولتی(کیلوگرم)',
                'تعداد کشتار دولتی(قطعه)',
                'وزن کشتار دولتی(کیلوگرم)',
                'تعداد کشتار آزاد(قطعه)',
                'وزن کشتار آزاد(کیلوگرم)',
                'میانگین وزن کشتار(کیلوگرم)',
                'سازنده جوجه ریزی',
                'کد اپیدمیولوژیک',
                'تعداد کشتار خارج از استان(قطعه)',
                'وزن کشتار خارج از استان(کیلوگرم)',
            ]

            for col_num, option in enumerate(header_list_gt_60_header, 5):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20

            # worksheet['A1'] = f' وضعیت پرونده ها'
            worksheet['B2'] = f'این گزارش در مورخ {now_fa_date} صادر شده است.'

            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B2:C3'
            # merge_range2 = 'B2:C2'

            worksheet.merge_cells(merge_range1)
            # worksheet.merge_cells(merge_range2)
            worksheet['B2'].font = red_font

            # cell = worksheet.cell(row=1, column=1)
            # cell.alignment = Alignment(horizontal='center', vertical='center')
            for col_num, option in enumerate(gt_60_header, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 20.01
                worksheet.row_dimensions[6].height = 22
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            l = 5
            m = 1
            all_poultry_hatching_quantity = 0
            all_poultry_hatching_killed_quantity = 0
            all_poultry_hatching_left_over = 0
            all_left_over_ninty_percent = 0
            for poultry_hatching in gte_60:
                l += 1

                all_poultry_hatching_quantity += poultry_hatching['quantity']
                all_poultry_hatching_killed_quantity += poultry_hatching['killed_quantity']
                all_poultry_hatching_left_over += poultry_hatching['left_over']
                if poultry_hatching['chicken_age'] not in min_list:
                    min_list.append(poultry_hatching['chicken_age'])

                create_date = jdatetime.date.fromgregorian(
                    day=poultry_hatching['create_date'].day,
                    month=poultry_hatching['create_date'].month,
                    year=poultry_hatching['create_date'].year
                )
                date = jdatetime.date.fromgregorian(
                    day=poultry_hatching['date'].day,
                    month=poultry_hatching['date'].month,
                    year=poultry_hatching['date'].year
                )
                # date1 = datetime.datetime.strptime(str(poultry_hatching['date']), '%Y-%m-%d %H:%M:%S')
                age = (datetime.datetime.now().date() - poultry_hatching['date'].date()).days + 1

                creator = '-'
                if poultry_hatching['registrar']:
                    if poultry_hatching['registrar']['fullname'] != '':
                        creator = poultry_hatching['registrar']['fullname']
                else:
                    creator = 'پنجره واحد'
                left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                    'killed_quantity']
                all_left_over_ninty_percent += left_over_ninty_percent
                list1 = [
                    m,
                    poultry_hatching['poultry__user__fullname'],
                    poultry_hatching['poultry__unit_name'],
                    poultry_hatching['poultry__user__mobile'],
                    poultry_hatching['poultry__breeding_unique_id'],
                    poultry_hatching['poultry__system_code'],
                    poultry_hatching['hall'],
                    poultry_hatching['period'],
                    str(create_date),
                    str(date),
                    poultry_hatching['chicken_breed'],
                    age,
                    poultry_hatching['quantity'],
                    poultry_hatching['losses'],
                    poultry_hatching['killed_quantity'],
                    poultry_hatching['total_killed_weight'],
                    poultry_hatching['left_over'],
                    left_over_ninty_percent,
                    poultry_hatching['total_commitment'],
                    poultry_hatching['governmental_quantity'],
                    poultry_hatching['governmental_killed_quantity'],
                    poultry_hatching['free_quantity'],
                    poultry_hatching['free_killed_quantity'],
                    str(poultry_hatching['total_average_killed_weight']),
                    creator,
                    poultry_hatching['poultry__epidemiological_code'] if poultry_hatching[
                        'poultry__epidemiological_code'] else '-',
                    poultry_hatching['out_province_killed_quantity'] if poultry_hatching[
                                                                            'out_province_killed_quantity'] > 0 else '-',
                    poultry_hatching['out_province_killed_weight'] if poultry_hatching[
                                                                          'out_province_killed_weight'] > 0 else '-',
                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    value = list1[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center')
            min_list = sorted(min_list)
            all_quantity = gte_60.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_losses = gte_60.aggregate(total_quantity=Sum('losses')).get(
                'total_quantity', 0)
            all_killed_quantity = gte_60.aggregate(total_quantity=Sum('killed_quantity')).get(
                'total_quantity', 0)
            all_left_over = gte_60.aggregate(total_quantity=Sum('left_over')).get(
                'total_quantity', 0)
            all_total_commitment = gte_60.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity = gte_60.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity = gte_60.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight = gte_60.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity = gte_60.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity = gte_60.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity = gte_60.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight = gte_60.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list = [
                len(gte_60),
                all_poultry_hatching_quantity,
                all_poultry_hatching_killed_quantity,
                all_total_killed_weight,
                all_poultry_hatching_left_over,
                all_left_over_ninty_percent,
                min_list[0] if len(min_list) > 0 else '-',
                min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                all_out_province_killed_quantity,
                all_out_province_killed_weight
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_quantity,
                all_losses,
                all_killed_quantity,
                all_total_killed_weight,
                all_left_over,
                all_left_over_ninty_percent,
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                '',
                '',
                '',
                all_out_province_killed_quantity,
                all_out_province_killed_weight,

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'فارم بین 50 تا 60 روز':

            between_50_60_header = [
                'ردیف',
                'نام و خانوادگی',
                'نام فارم',
                'موبایل',
                'کد یکتا',
                'کد سیستمی واحد',
                'سالن',
                ' دوره جوجه ریزی',
                'تاریخ ثبت جوجه ریزی',
                'تاریخ جوجه ریزی',
                'نژاد',
                'سن',
                'تعداد جوجه ریزی',
                'تلفات دوره',
                'تعداد کشتار شده(قطعه)',
                'وزن کل کشتارشده(کیلوگرم)',
                'مانده در سالن',
                'مانده در سالن از نود درصد',
                'وزن تعهد دولتی(کیلوگرم)',
                'تعداد کشتار دولتی(قطعه)',
                'وزن کشتار دولتی(کیلوگرم)',
                'تعداد کشتار آزاد(قطعه)',
                'وزن کشتار آزاد(کیلوگرم)',
                'میانگین وزن کشتار(کیلوگرم)',
                'سازنده جوجه ریزی',
                'کد اپیدمیولوژیک',
                'تعداد کشتار خارج از استان(قطعه)',
                'وزن کشتار خارج از استان(کیلوگرم)',
            ]

            for col_num, option in enumerate(header_list_between_50_60, 5):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20

            # worksheet['A1'] = f' وضعیت پرونده ها'
            worksheet['B2'] = f'این گزارش در مورخ {now_fa_date} صادر شده است.'

            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B2:C3'
            # merge_range2 = 'B2:C2'

            worksheet.merge_cells(merge_range1)
            # worksheet.merge_cells(merge_range2)
            worksheet['B2'].font = red_font

            # cell = worksheet.cell(row=1, column=1)
            # cell.alignment = Alignment(horizontal='center', vertical='center')
            for col_num, option in enumerate(between_50_60_header, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 20.01
                worksheet.row_dimensions[6].height = 22
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            l = 5
            m = 1
            all_poultry_hatching_quantity = 0
            all_poultry_hatching_killed_quantity = 0
            all_poultry_hatching_left_over = 0
            min_list = []
            all_left_over_ninty_percent = 0
            for poultry_hatching in between_50_60:
                l += 1

                all_poultry_hatching_quantity += poultry_hatching['quantity']
                all_poultry_hatching_killed_quantity += poultry_hatching['killed_quantity']
                all_poultry_hatching_left_over += poultry_hatching['left_over']
                if poultry_hatching['chicken_age'] not in min_list:
                    min_list.append(poultry_hatching['chicken_age'])

                create_date = jdatetime.date.fromgregorian(
                    day=poultry_hatching['create_date'].day,
                    month=poultry_hatching['create_date'].month,
                    year=poultry_hatching['create_date'].year
                )
                date = jdatetime.date.fromgregorian(
                    day=poultry_hatching['date'].day,
                    month=poultry_hatching['date'].month,
                    year=poultry_hatching['date'].year
                )
                # date1 = datetime.datetime.strptime(str(poultry_hatching['date']), '%Y-%m-%d %H:%M:%S')
                age = (datetime.datetime.now().date() - poultry_hatching['date'].date()).days + 1

                creator = '-'
                if poultry_hatching['registrar']:
                    if poultry_hatching['registrar']['fullname'] != '':
                        creator = poultry_hatching['registrar']['fullname']
                else:
                    creator = 'پنجره واحد'
                left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                    'killed_quantity']
                all_left_over_ninty_percent += left_over_ninty_percent
                list1 = [
                    m,
                    poultry_hatching['poultry__user__fullname'],
                    poultry_hatching['poultry__unit_name'],
                    poultry_hatching['poultry__user__mobile'],
                    poultry_hatching['poultry__breeding_unique_id'],
                    poultry_hatching['poultry__system_code'],
                    poultry_hatching['hall'],
                    poultry_hatching['period'],
                    str(create_date),
                    str(date),
                    poultry_hatching['chicken_breed'],
                    age,
                    poultry_hatching['quantity'],
                    poultry_hatching['losses'],
                    poultry_hatching['killed_quantity'],
                    poultry_hatching['total_killed_weight'],
                    poultry_hatching['left_over'],
                    left_over_ninty_percent,
                    poultry_hatching['total_commitment'],
                    poultry_hatching['governmental_quantity'],
                    poultry_hatching['governmental_killed_quantity'],
                    poultry_hatching['free_quantity'],
                    poultry_hatching['free_killed_quantity'],
                    str(poultry_hatching['total_average_killed_weight']),
                    creator,
                    poultry_hatching['poultry__epidemiological_code'] if poultry_hatching[
                        'poultry__epidemiological_code'] else '-',
                    poultry_hatching['out_province_killed_quantity'] if poultry_hatching[
                                                                            'out_province_killed_quantity'] > 0 else '-',
                    poultry_hatching['out_province_killed_weight'] if poultry_hatching[
                                                                          'out_province_killed_weight'] > 0 else '-',
                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    value = list1[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center')
            min_list = sorted(min_list)
            all_quantity = between_50_60.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_losses = between_50_60.aggregate(total_quantity=Sum('losses')).get(
                'total_quantity', 0)
            all_killed_quantity = between_50_60.aggregate(total_quantity=Sum('killed_quantity')).get(
                'total_quantity', 0)
            all_left_over = between_50_60.aggregate(total_quantity=Sum('left_over')).get(
                'total_quantity', 0)
            all_total_commitment = between_50_60.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity = between_50_60.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity = between_50_60.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight = between_50_60.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity = between_50_60.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity = between_50_60.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity = between_50_60.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight = between_50_60.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list = [
                len(between_50_60),
                all_poultry_hatching_quantity,
                all_poultry_hatching_killed_quantity,
                all_total_killed_weight,
                all_poultry_hatching_left_over,
                all_left_over_ninty_percent,
                min_list[0] if len(min_list) > 0 else '-',
                min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                all_out_province_killed_quantity,
                all_out_province_killed_weight
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_quantity,
                all_losses,
                all_killed_quantity,
                all_total_killed_weight,
                all_left_over,
                all_left_over_ninty_percent,
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                '',
                '',
                '',
                all_out_province_killed_quantity,
                all_out_province_killed_weight,

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'فارم بین 40 تا 50 روز':

            between_40_50_header = [
                'ردیف',
                'نام و خانوادگی',
                'نام فارم',
                'موبایل',
                'کد یکتا',
                'کد سیستمی واحد',
                'سالن',
                ' دوره جوجه ریزی',
                'تاریخ ثبت جوجه ریزی',
                'تاریخ جوجه ریزی',
                'نژاد',
                'سن',
                'تعداد جوجه ریزی',
                'تلفات دوره',
                'تعداد کشتار شده(قطعه)',
                'وزن کل کشتارشده(کیلوگرم)',
                'مانده در سالن',
                'مانده در سالن از نود درصد',
                'وزن تعهد دولتی(کیلوگرم)',
                'تعداد کشتار دولتی(قطعه)',
                'وزن کشتار دولتی(کیلوگرم)',
                'تعداد کشتار آزاد(قطعه)',
                'وزن کشتار آزاد(کیلوگرم)',
                'میانگین وزن کشتار(کیلوگرم)',
                'سازنده جوجه ریزی',
                'کد اپیدمیولوژیک',
                'تعداد کشتار خارج از استان(قطعه)',
                'وزن کشتار خارج از استان(کیلوگرم)',
            ]

            for col_num, option in enumerate(header_list_between_40_50, 5):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20

            # worksheet['A1'] = f' وضعیت پرونده ها'
            worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B2:C3'
            # merge_range2 = 'B2:C2'

            worksheet.merge_cells(merge_range1)
            # worksheet.merge_cells(merge_range2)
            worksheet['B2'].font = red_font

            # cell = worksheet.cell(row=1, column=1)
            # cell.alignment = Alignment(horizontal='center', vertical='center')
            for col_num, option in enumerate(between_40_50_header, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 20.01
                worksheet.row_dimensions[6].height = 22
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            l = 5
            m = 1
            all_poultry_hatching_quantity = 0
            all_poultry_hatching_killed_quantity = 0
            all_poultry_hatching_left_over = 0
            min_list = []
            all_left_over_ninty_percent = 0
            for poultry_hatching in between_40_50:
                l += 1

                all_poultry_hatching_quantity += poultry_hatching['quantity']
                all_poultry_hatching_killed_quantity += poultry_hatching['killed_quantity']
                all_poultry_hatching_left_over += poultry_hatching['left_over']
                if poultry_hatching['chicken_age'] not in min_list:
                    min_list.append(poultry_hatching['chicken_age'])

                create_date = jdatetime.date.fromgregorian(
                    day=poultry_hatching['create_date'].day,
                    month=poultry_hatching['create_date'].month,
                    year=poultry_hatching['create_date'].year
                )
                date = jdatetime.date.fromgregorian(
                    day=poultry_hatching['date'].day,
                    month=poultry_hatching['date'].month,
                    year=poultry_hatching['date'].year
                )
                # date1 = datetime.datetime.strptime(str(poultry_hatching['date']), '%Y-%m-%d %H:%M:%S')
                age = (datetime.datetime.now().date() - poultry_hatching['date'].date()).days + 1

                creator = '-'
                if poultry_hatching['registrar']:
                    if poultry_hatching['registrar']['fullname'] != '':
                        creator = poultry_hatching['registrar']['fullname']
                else:
                    creator = 'پنجره واحد'
                left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                    'killed_quantity']
                all_left_over_ninty_percent += left_over_ninty_percent
                list1 = [
                    m,
                    poultry_hatching['poultry__user__fullname'],
                    poultry_hatching['poultry__unit_name'],
                    poultry_hatching['poultry__user__mobile'],
                    poultry_hatching['poultry__breeding_unique_id'],
                    poultry_hatching['poultry__system_code'],
                    poultry_hatching['hall'],
                    poultry_hatching['period'],
                    str(create_date),
                    str(date),
                    poultry_hatching['chicken_breed'],
                    age,
                    poultry_hatching['quantity'],
                    poultry_hatching['losses'],
                    poultry_hatching['killed_quantity'],
                    poultry_hatching['total_killed_weight'],
                    poultry_hatching['left_over'],
                    left_over_ninty_percent,
                    poultry_hatching['total_commitment'],
                    poultry_hatching['governmental_quantity'],
                    poultry_hatching['governmental_killed_quantity'],
                    poultry_hatching['free_quantity'],
                    poultry_hatching['free_killed_quantity'],
                    str(poultry_hatching['total_average_killed_weight']),
                    creator,
                    poultry_hatching['poultry__epidemiological_code'] if poultry_hatching[
                        'poultry__epidemiological_code'] else '-',
                    poultry_hatching['out_province_killed_quantity'] if poultry_hatching[
                                                                            'out_province_killed_quantity'] > 0 else '-',
                    poultry_hatching['out_province_killed_weight'] if poultry_hatching[
                                                                          'out_province_killed_weight'] > 0 else '-',
                ]
                m += 1
                for item in range(len(list1)):
                    cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                    value = list1[item]
                    # Check if the value is a number before formatting
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,###'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center')
            min_list = sorted(min_list)
            all_quantity = between_40_50.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_losses = between_40_50.aggregate(total_quantity=Sum('losses')).get(
                'total_quantity', 0)
            all_killed_quantity = between_40_50.aggregate(total_quantity=Sum('killed_quantity')).get(
                'total_quantity', 0)
            all_left_over = between_40_50.aggregate(total_quantity=Sum('left_over')).get(
                'total_quantity', 0)
            all_total_commitment = between_40_50.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity = between_40_50.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity = between_40_50.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight = between_40_50.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity = between_40_50.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity = between_40_50.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity = between_40_50.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight = between_40_50.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list = [
                len(between_40_50),
                all_poultry_hatching_quantity,
                all_poultry_hatching_killed_quantity,
                all_total_killed_weight,
                all_poultry_hatching_left_over,
                all_left_over_ninty_percent,
                min_list[0] if len(min_list) > 0 else '-',
                min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                all_out_province_killed_quantity,
                all_out_province_killed_weight
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_quantity,
                all_losses,
                all_killed_quantity,
                all_total_killed_weight,
                all_left_over,
                all_left_over_ninty_percent,
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                '',
                '',
                '',
                all_out_province_killed_quantity,
                all_out_province_killed_weight,

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'تخلیه فارم بدون مجوز':

            no_license1_header = [
                'ردیف',
                'نام و خانوادگی',
                'نام فارم',
                'موبایل',
                'کد یکتا',
                'کد سیستمی واحد',
                'سالن',
                ' دوره جوجه ریزی',
                'تاریخ ثبت جوجه ریزی',
                'تاریخ جوجه ریزی',
                'نژاد',
                'سن',
                'تعداد جوجه ریزی',
                'تلفات دوره',
                'تعداد کشتار شده(قطعه)',
                'وزن کل کشتارشده(کیلوگرم)',
                'مانده در سالن',
                'مانده در سالن از نود درصد',
                'وزن تعهد دولتی(کیلوگرم)',
                'تعداد کشتار دولتی(قطعه)',
                'وزن کشتار دولتی(کیلوگرم)',
                'تعداد کشتار آزاد(قطعه)',
                'وزن کشتار آزاد(کیلوگرم)',
                'میانگین وزن کشتار(کیلوگرم)',
                'سازنده جوجه ریزی',
                'کد اپیدمیولوژیک',
                'تعداد کشتار خارج از استان(قطعه)',
                'وزن کشتار خارج از استان(کیلوگرم)',
            ]

            for col_num, option in enumerate(header_list_no_license1, 5):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20

            # worksheet['A1'] = f' وضعیت پرونده ها'
            worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B2:C3'
            # merge_range2 = 'B2:C2'

            worksheet.merge_cells(merge_range1)
            # worksheet.merge_cells(merge_range2)
            worksheet['B2'].font = red_font

            # cell = worksheet.cell(row=1, column=1)
            # cell.alignment = Alignment(horizontal='center', vertical='center')
            for col_num, option in enumerate(no_license1_header, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                worksheet.column_dimensions[col_letter].width = 20.01
                worksheet.row_dimensions[6].height = 22
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            l = 5
            m = 1
            all_poultry_hatching_quantity = 0
            all_poultry_hatching_killed_quantity = 0
            all_poultry_hatching_left_over = 0
            min_list = []
            all_left_over_ninty_percent = 0
            no_license3 = []
            all_quantity = 0
            all_total_killed_weight = 0
            all_total_commitment = 0
            all_governmental_quantity = 0
            all_losses = 0
            all_governmental_killed_quantity = 0
            all_free_killed_quantity = 0
            all_free_quantity = 0
            all_out_province_killed_quantity = 0
            all_out_province_killed_weight = 0
            for no_license in no_license1:
                if no_license['period'] > 1:
                    no_licence2 = (filtered_poultry_hatch.filter(left_over__gt=F('quantity') * 0.1,
                                                                 poultry__key=no_license['poultry__key']
                                                                 , period=no_license['period'] - 1))
                    no_license3.append(no_licence2)

            for p in no_license3:
                for poultry_hatching in p:

                    all_quantity += poultry_hatching['quantity']
                    all_poultry_hatching_quantity += poultry_hatching['quantity']
                    all_poultry_hatching_killed_quantity += poultry_hatching['killed_quantity']
                    all_total_killed_weight += poultry_hatching['total_killed_weight']
                    all_poultry_hatching_left_over += poultry_hatching['left_over']
                    all_total_commitment += poultry_hatching['total_commitment']
                    all_governmental_quantity += poultry_hatching['governmental_quantity']
                    all_governmental_killed_quantity += poultry_hatching['governmental_killed_quantity']
                    all_losses += poultry_hatching['losses']
                    all_free_killed_quantity += poultry_hatching['free_killed_quantity']
                    all_free_quantity += poultry_hatching['free_quantity']
                    all_out_province_killed_quantity += poultry_hatching['out_province_killed_quantity']
                    all_out_province_killed_weight += poultry_hatching['out_province_killed_weight']
                    if poultry_hatching['chicken_age'] not in min_list:
                        min_list.append(poultry_hatching['chicken_age'])

                    create_date = jdatetime.date.fromgregorian(
                        day=poultry_hatching['create_date'].day,
                        month=poultry_hatching['create_date'].month,
                        year=poultry_hatching['create_date'].year
                    )
                    date = jdatetime.date.fromgregorian(
                        day=poultry_hatching['date'].day,
                        month=poultry_hatching['date'].month,
                        year=poultry_hatching['date'].year
                    )
                    # date1 = datetime.datetime.strptime(str(poultry_hatching['date']), '%Y-%m-%d %H:%M:%S')
                    age = (datetime.datetime.now().date() - poultry_hatching['date'].date()).days + 1

                    creator = '-'
                    if poultry_hatching['registrar']:
                        if poultry_hatching['registrar']['fullname'] != '':
                            creator = poultry_hatching['registrar']['fullname']
                    else:
                        creator = 'پنجره واحد'
                    left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                        'killed_quantity']
                    all_left_over_ninty_percent += left_over_ninty_percent
                    list1 = [
                        m,
                        poultry_hatching['poultry__user__fullname'],
                        poultry_hatching['poultry__unit_name'],
                        poultry_hatching['poultry__user__mobile'],
                        poultry_hatching['poultry__breeding_unique_id'],
                        poultry_hatching['poultry__system_code'],
                        poultry_hatching['hall'],
                        poultry_hatching['period'],
                        str(create_date),
                        str(date),
                        poultry_hatching['chicken_breed'],
                        age,
                        poultry_hatching['quantity'],
                        poultry_hatching['losses'],
                        poultry_hatching['killed_quantity'],
                        poultry_hatching['total_killed_weight'],
                        poultry_hatching['left_over'],
                        left_over_ninty_percent,
                        poultry_hatching['total_commitment'],
                        poultry_hatching['governmental_quantity'],
                        poultry_hatching['governmental_killed_quantity'],
                        poultry_hatching['free_quantity'],
                        poultry_hatching['free_killed_quantity'],
                        str(poultry_hatching['total_average_killed_weight']),
                        creator,
                        poultry_hatching['poultry__epidemiological_code'] if poultry_hatching[
                            'poultry__epidemiological_code'] else '-',
                        poultry_hatching['out_province_killed_quantity'] if poultry_hatching[
                                                                                'out_province_killed_quantity'] > 0 else '-',
                        poultry_hatching['out_province_killed_weight'] if poultry_hatching[
                                                                              'out_province_killed_weight'] > 0 else '-',
                    ]
                    m += 1
                    l += 1

                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        cell.alignment = Alignment(horizontal='center')
            min_list = sorted(min_list)
            all_left_over = all_poultry_hatching_left_over

            value_header_list = [
                len(no_license3),
                all_quantity,
                all_poultry_hatching_killed_quantity,
                all_total_killed_weight,
                all_poultry_hatching_left_over,
                all_left_over_ninty_percent,
                min_list[0] if len(min_list) > 0 else '-',
                min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                all_out_province_killed_quantity,
                all_out_province_killed_weight
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            all_killed_quantity = all_poultry_hatching_killed_quantity

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_quantity,
                all_losses,
                all_killed_quantity,
                all_total_killed_weight,
                all_left_over,
                all_left_over_ninty_percent,
                all_total_commitment,
                all_governmental_quantity,
                all_governmental_killed_quantity,
                all_free_quantity,
                all_free_killed_quantity,
                '',
                '',
                '',
                all_out_province_killed_quantity,
                all_out_province_killed_weight,

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'دامپزشکان فارم مغایرت قرنطینه':

            poultry_request = (
                PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs_not_code_but_have_assigment.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 = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str

            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'دامپزشکان فارمی که گواهی قرنطینه ثبت نکرده اند یا مغایرت در تعداد قطعه دارند.'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:E1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_code_but_have_assigment.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_code_but_have_assigment.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)

            if filtered_kill_reqs_not_code_but_have_assigment:
                for kill in filtered_kill_reqs_not_code_but_have_assigment:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'
                    age = (kill['province_request__poultry_request__send_date'].date() - kill[
                        'province_request__poultry_request__hatching__date'].date()).days + 1

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_code_but_have_assigment.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_code_but_have_assigment.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_code_but_have_assigment),
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'عدم تخلیه دامپزشک کشتارگاه':

            poultry_request = (
                PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs_not_assigment_but_have_code.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 = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارها',
                'مجموع تعداد قطعه بارها',
                'مجموع وزن بارها',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            worksheet['B1'] = f'بارهای تخلیه نشده با کد قرنطینه'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_assigment_but_have_code.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_assigment_but_have_code.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)

            if filtered_kill_reqs_not_assigment_but_have_code:
                for kill in filtered_kill_reqs_not_assigment_but_have_code:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'

                    age = (kill['province_request__poultry_request__send_date'].date() - kill[
                        'province_request__poultry_request__hatching__date'].date()).days + 1

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_assigment_but_have_code.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_assigment_but_have_code.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_assigment_but_have_code.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment_but_have_code),
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'بار های تخلیه نشده کشتارگاه':

            poultry_request = (
                PoultryRequest.objects.filter(trash=False,
                                              pk__in=filtered_kill_reqs_not_assigment_but_have_code1.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 = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارها',
                'مجموع تعداد قطعه بارها',
                'مجموع وزن بارها',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            # worksheet['B1'] = f'بارهای تخلیه نشده با کد قرنطینه'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_assigment_but_have_code1.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_assigment_but_have_code1.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)

            if filtered_kill_reqs_not_assigment_but_have_code1:
                for kill in filtered_kill_reqs_not_assigment_but_have_code1:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'

                    age = (kill['province_request__poultry_request__send_date'].date() - kill[
                        'province_request__poultry_request__hatching__date'].date()).days + 1

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs_not_assigment_but_have_code1.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_assigment_but_have_code1.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_assigment_but_have_code1.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment_but_have_code1),
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'بار های تخلیه شده فاقد قرنطینه':

            poultry_request = (
                PoultryRequest.objects.filter(trash=False,
                                              pk__in=filtered_kill_reqs__assigment_but_havent_code.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 = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

                'سن مرغ',
                'قیمت پیشنهادی مرغدار(ریال)',
                ' نژاد',
                'دامپزشک فارم',
                'تلفن دامپزشک فارم',
                ' ماهیت خریدار',
                'خریدار',
                ' تلفن خریدار',
                ' آدرس ',
                ' محل کشتار ',
                'نوع تخصیص',

                'دامپزشک کشتارگاه ',
                ' تلفن دامپزشک کشتارگاه ',
                'راننده',
                'موبایل راننده',
                'نوع خودرو',
                'کد بهداشتی حمل و نقل',
                'تعداد قطعه بار ',
                'وزن بار',
                'کد رهگیری سامانه قرنطینه',
                'تعداد قطعه وارد شده در قرنطینه',
                'وضعیت تخلیه',
                'تاریخ تخلیه (کشتارگاه)',
                'تعداد تخلیه شده دامپزشک',
                'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
                'تعداد نهایی در کشتارگاه',
                'وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=6, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[6].height = 19
                worksheet.freeze_panes = worksheet['A7']
                max_col = worksheet.max_column
                range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            header_list = [
                'تعداد بارها',
                'مجموع تعداد قطعه بارها',
                'مجموع وزن بارها',
                'تعداد بارهای دارای کد قرنطینه',
                'تعداد بار احراز شده از قرنطینه',
                'مجموع تعداد قطعه احراز شده از قرنطینه',
                'تعداد  تخلیه شده دامپزشک',
                'مجموع تعداد  تخلیه شده دامپزشک',
                'مجموع وزن  تخلیه شده دامپزشک',
                'تعداد بارهای تکمیل شده',
                'مجموع تعداد نهایی در کشتارگاه',
                'مجموع وزن نهایی در کشتار گاه',
                'ملاک قطعه کشتار شده',
                'ملاک وزن کشتار شده',

            ]
            for col_num, option in enumerate(header_list, 9):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=2, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
            # worksheet['B1'] = f'بارهای تخلیه نشده با کد قرنطینه'
            if filtered_kill_reqs.exists():
                name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
                worksheet['B2'] = f'استان {name}'

            worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range1 = 'B1:D1'
            merge_range2 = 'B2:D2'
            merge_range = 'B3:D3'
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range)
            worksheet.merge_cells(merge_range2)
            worksheet['B1'].font = red_font
            worksheet['B3'].font = Font(size=11)
            worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
            l = 5
            m = 1
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs__assigment_but_havent_code.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs__assigment_but_havent_code.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_kill_request_quantity = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_quantity = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)

            if filtered_kill_reqs__assigment_but_havent_code:
                for kill in filtered_kill_reqs__assigment_but_havent_code:
                    if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                        'vet_state'] == 'accepted':
                        state = 'تخلیه شده'
                    else:
                        state = 'درانتظار تخلیه'
                    l += 1
                    date_of_inner_bar = '-'
                    vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                                      trash=False).select_related('vet__user').only(
                        'vet__user__fullname',
                        'vet__user__mobile').values(
                        'vet__user__fullname',
                        'vet__user__mobile').first()
                    vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
                    vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
                    kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user')).select_related(
                        'vet__user').only('vet__user__fullname',
                                          'vet__user__mobile').values('vet__user__fullname',
                                                                      'vet__user__mobile').first()
                    vet_checks = VetCheckRequest.objects.filter(trash=False,
                                                                kill_house_request__key=kill.get('key')).only(
                        'create_date').values(
                        'create_date').first()
                    kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
                    kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity
                    else:
                        quantity = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    date_of_poultry_request = jdatetime.date.fromgregorian(
                        day=send_date.day,
                        month=send_date.month,
                        year=send_date.year
                    )
                    killers = 'کشتارکن'
                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity
                        vet_check_date = assignment.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )
                    else:
                        net_weighte = '-'
                        real_quantity = '-'
                    if vet_checks:
                        vet_check_date = vet_checks.get('create_date')
                        date_of_inner_bar = convert_to_shamsi(
                            datetime=vet_check_date
                        )

                    if kill.get('kill_request__slaughter_house') is not None:
                        kill_place = kill.get('kill_request__slaughter_house__name')
                    else:
                        kill_place = '-'

                    vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
                    vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight
                    quarantine_quantity = '-'

                    if kill['quarantine_quantity'] != None:
                        quarantine_quantity = kill['quarantine_quantity']
                    else:
                        if kill['quarantine_code_state'] == 'contradiction':
                            quarantine_quantity = 'مغایرت کد رهگیری'
                        elif kill['quarantine_code_state'] == 'noclearance':
                            quarantine_quantity = 'فاقد کد رهگیری'
                        elif kill['quarantine_code_state'] == 'notconfirmed':
                            quarantine_quantity = 'عدم تایید راهداری'
                        elif kill['quarantine_code_state'] == 'merge':
                            quarantine_quantity = 'ادغام'

                    sale_type = 'دولتی' if kill[
                                               'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

                    if kill['province_kill_request__province_request__poultry_request__union'] == True:
                        type = 'فروش آزاد'
                    elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                        type = 'خرید مستقیم'
                    else:
                        type = 'اتحادیه'

                    age = (kill['province_request__poultry_request__send_date'].date() - kill[
                        'province_request__poultry_request__hatching__date'].date()).days + 1

                    list1 = [
                        m,
                        str(kill.get('bar_code')),
                        str(date_of_poultry_request),
                        str(kill.get('province_request__poultry_request__order_code')),
                        kill.get('province_request__poultry_request__poultry__unit_name'),
                        str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                        kill.get('province_request__poultry_request__poultry__user__city__name'),
                        sale_type,
                        age,
                        kill.get('province_request__poultry_request__amount') if kill.get(
                            'province_request__poultry_request__amount') else '-',
                        kill.get('province_request__poultry_request__chicken_breed'),
                        vet_farm_name,
                        vet_farm_mobile,
                        killers,
                        kill.get('killhouse_user__name'),
                        kill.get('killhouse_user__kill_house_operator__user__mobile'),
                        kill.get('killhouse_user__system_address__city__name'),
                        kill_place,
                        type,
                        kill_house_vet_name,
                        kill_house_vet_mobile,
                        kill.get('add_car__driver__driver_name'),
                        kill.get('add_car__driver__driver_mobile'),
                        kill.get('add_car__driver__type_car'),
                        str(kill.get('traffic_code')),
                        quantity,
                        weight,
                        code,
                        quarantine_quantity,
                        state,
                        str(date_of_inner_bar),
                        vet_quantity,
                        vet_wight,
                        real_quantity,
                        net_weighte,
                        kill['accepted_real_quantity'],
                        kill['accepted_real_weight'],

                    ]
                    m += 1
                    for item in range(len(list1)):
                        cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                        value = list1[item]
                        # Check if the value is a number before formatting
                        if isinstance(value, (int, float)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values

                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            has_code = len(filtered_kill_reqs__assigment_but_havent_code.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs__assigment_but_havent_code.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs__assigment_but_havent_code.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs__assigment_but_havent_code),
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                total_requests_weight

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
                value = value_header_list2[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                all_kill_request_quantity,
                all_weighte,
                '',
                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                '',
                '',
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(list2)):
                cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        elif sheet_name == 'آمار کشتار روزانه':

            worksheet['A2'] = f'این گزارش در مورخ {now_fa_date} صادر شده است.'
            worksheet['G3'] = f'فارم های بالای 60 روز'
            worksheet['G3'] = f'فارم بین 50 تا 60 روز'
            worksheet['F8'] = f'فارم بین 50 تا 60 روز'
            worksheet['F12'] = f'فارم بین 40 تا 50 روز'
            worksheet['F17'] = f'تخلیه مرغداران بدون مجوز'
            worksheet['B21'] = f' گزارش مغایرت در اطلاعات از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
            worksheet['F22'] = 'بارهای دارای مغایرت یا فاقد کد قرنطینه (مسئول فنی فارم )'
            worksheet['G27'] = 'بارهای تخلیه نشده توسط دامپزشک کشتارگاه'
            worksheet['G32'] = 'بارهای  تکمیل نشده توسط کشتارگاه'
            worksheet['F37'] = 'بارهای تخلیه شده یا تکمیل شده فاقد کد قرنطینه'

            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F12'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F17'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['B21'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F22'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G32'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['F37'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            merge_range1 = 'A2:F2'
            merge_range2 = 'G3:M3'
            merge_range3 = 'F8:N8'
            merge_range4 = 'F12:N12'
            merge_range5 = 'F17:N17'
            merge_range6 = 'B21:E22'
            merge_range7 = 'F22:L22'
            merge_range8 = 'G27:J27'
            merge_range9 = 'G32:J32'
            merge_range10 = 'F37:J37'

            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)
            worksheet.merge_cells(merge_range10)
            worksheet['A2'].font = red_font
            worksheet['B21'].font = red_font

            for col_num, option in enumerate(header_list_gt_60_header, 3):
                cell = worksheet.cell(row=4, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFFF00", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[4].height = 36
            all_poultry_hatching_quantity_gte_60 = 0
            all_poultry_hatching_killed_quantity_gte_60 = 0
            all_poultry_hatching_left_over_gte_60 = 0
            all_left_over_ninty_percent_gte_60 = 0
            min_list_gte_60 = []

            for poultry_hatching in gte_60:

                all_poultry_hatching_quantity_gte_60 += poultry_hatching['quantity']
                all_poultry_hatching_killed_quantity_gte_60 += poultry_hatching['killed_quantity']
                all_poultry_hatching_left_over_gte_60 += poultry_hatching['left_over']
                if poultry_hatching['chicken_age'] not in min_list_gte_60:
                    min_list_gte_60.append(poultry_hatching['chicken_age'])
                left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                    'killed_quantity']
                all_left_over_ninty_percent_gte_60 += left_over_ninty_percent
            min_list_gte_60 = sorted(min_list_gte_60)
            all_total_commitment_gte_60 = gte_60.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity_gte_60 = gte_60.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity_gte_60 = gte_60.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight_gte_60 = gte_60.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity_gte_60 = gte_60.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity_gte_60 = gte_60.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity_gte_60 = gte_60.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight_gte_60 = gte_60.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list1 = [
                len(gte_60),
                all_poultry_hatching_quantity_gte_60,
                all_poultry_hatching_killed_quantity_gte_60,
                all_total_killed_weight_gte_60,
                all_poultry_hatching_left_over_gte_60,
                all_left_over_ninty_percent_gte_60,
                min_list_gte_60[0] if len(min_list_gte_60) > 0 else '-',
                min_list_gte_60[len(min_list) - 1] if len(min_list_gte_60) > 0 else '-',
                all_total_commitment_gte_60,
                all_governmental_quantity_gte_60,
                all_governmental_killed_quantity_gte_60,
                all_free_quantity_gte_60,
                all_free_killed_quantity_gte_60,
                all_out_province_killed_quantity_gte_60,
                all_out_province_killed_weight_gte_60
            ]
            for item in range(len(value_header_list1)):
                cell = worksheet.cell(row=5, column=item + 3, value=value_header_list1[item])
                value = value_header_list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            for col_num, option in enumerate(header_list_between_50_60, 3):
                cell = worksheet.cell(row=9, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="92CDDC", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[9].height = 37

            all_poultry_hatching_quantity_between_50_60 = 0
            all_poultry_hatching_killed_quantity_between_50_60 = 0
            all_poultry_hatching_left_over_between_50_60 = 0
            min_list_between_50_60 = []
            all_left_over_ninty_percent_between_50_60 = 0
            for poultry_hatching in between_50_60:

                all_poultry_hatching_quantity_between_50_60 += poultry_hatching['quantity']
                all_poultry_hatching_killed_quantity_between_50_60 += poultry_hatching['killed_quantity']
                all_poultry_hatching_left_over_between_50_60 += poultry_hatching['left_over']
                if poultry_hatching['chicken_age'] not in min_list_between_50_60:
                    min_list_between_50_60.append(poultry_hatching['chicken_age'])

                left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                    'killed_quantity']
                all_left_over_ninty_percent_between_50_60 += left_over_ninty_percent

            min_list_between_50_60 = sorted(min_list_between_50_60)
            all_total_commitment_between_50_60 = between_50_60.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight_between_50_60 = between_50_60.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list = [
                len(between_50_60),
                all_poultry_hatching_quantity_between_50_60,
                all_poultry_hatching_killed_quantity_between_50_60,
                all_total_killed_weight_between_50_60,
                all_poultry_hatching_left_over_between_50_60,
                all_left_over_ninty_percent_between_50_60,
                min_list_between_50_60[0] if len(min_list_between_50_60) > 0 else '-',
                min_list_between_50_60[len(min_list) - 1] if len(min_list_between_50_60) > 0 else '-',
                all_total_commitment_between_50_60,
                all_governmental_quantity_between_50_60,
                all_governmental_killed_quantity_between_50_60,
                all_free_quantity_between_50_60,
                all_free_killed_quantity_between_50_60,
                all_out_province_killed_quantity_between_50_60,
                all_out_province_killed_weight_between_50_60
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=10, column=item + 3, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            for col_num, option in enumerate(header_list_between_40_50, 3):
                cell = worksheet.cell(row=13, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="92D050", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[13].height = 37

            all_poultry_hatching_quantity_between_40_50 = 0
            all_poultry_hatching_killed_quantity_between_40_50 = 0
            all_poultry_hatching_left_over_between_40_50 = 0
            min_list_between_40_50 = []
            all_left_over_ninty_percent_between_40_50 = 0
            for poultry_hatching in between_40_50:
                all_poultry_hatching_quantity_between_40_50 += poultry_hatching['quantity']
                all_poultry_hatching_killed_quantity_between_40_50 += poultry_hatching['killed_quantity']
                all_poultry_hatching_left_over_between_40_50 += poultry_hatching['left_over']
                if poultry_hatching['chicken_age'] not in min_list_between_40_50:
                    min_list_between_40_50.append(poultry_hatching['chicken_age'])

                left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                    'killed_quantity']
                all_left_over_ninty_percent_between_40_50 += left_over_ninty_percent

            min_list_between_40_50 = sorted(min_list_between_40_50)

            all_total_commitment_between_40_50 = between_40_50.aggregate(total_quantity=Sum('total_commitment')).get(
                'total_quantity', 0)
            all_governmental_killed_quantity_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('governmental_killed_quantity')).get(
                'total_quantity', 0)
            all_free_killed_quantity_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('free_killed_quantity')).get(
                'total_quantity', 0)
            all_total_killed_weight_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('total_killed_weight')).get(
                'total_quantity', 0)
            all_governmental_quantity_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('governmental_quantity')).get(
                'total_quantity', 0)
            all_free_quantity_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('free_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_quantity_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('out_province_killed_quantity')).get(
                'total_quantity', 0)
            all_out_province_killed_weight_between_40_50 = between_40_50.aggregate(
                total_quantity=Sum('out_province_killed_weight')).get(
                'total_quantity', 0)
            value_header_list = [
                len(between_40_50),
                all_poultry_hatching_quantity_between_40_50,
                all_poultry_hatching_killed_quantity_between_40_50,
                all_total_killed_weight_between_40_50,
                all_poultry_hatching_left_over_between_40_50,
                all_left_over_ninty_percent_between_40_50,
                min_list_between_40_50[0] if len(min_list_between_40_50) > 0 else '-',
                min_list_between_40_50[len(min_list) - 1] if len(min_list_between_40_50) > 0 else '-',
                all_total_commitment_between_40_50,
                all_governmental_quantity_between_40_50,
                all_governmental_killed_quantity_between_40_50,
                all_free_quantity_between_40_50,
                all_free_killed_quantity_between_40_50,
                all_out_province_killed_quantity_between_40_50,
                all_out_province_killed_weight_between_40_50
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=14, column=item + 3, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            for col_num, option in enumerate(header_list_no_license1, 3):
                cell = worksheet.cell(row=18, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FCD5B4", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[18].height = 37

            all_poultry_hatching_quantity_no_license1 = 0
            all_poultry_hatching_killed_quantity_no_license1 = 0
            all_poultry_hatching_left_over_no_license1 = 0
            min_list_no_license1 = []
            all_left_over_ninty_percent_no_license1 = 0
            no_license3_no_license1 = []
            all_quantity_no_license1 = 0
            all_total_killed_weight_no_license1 = 0
            all_total_commitment_no_license1 = 0
            all_governmental_quantity_no_license1 = 0
            all_losses_no_license1 = 0
            all_governmental_killed_quantity_no_license1 = 0
            all_free_killed_quantity_no_license1 = 0
            all_free_quantity_no_license1 = 0
            all_out_province_killed_quantity_no_license1 = 0
            all_out_province_killed_weight_no_license1 = 0
            for no_license in no_license1:
                if no_license['period'] > 1:
                    no_licence2_no_license1 = (filtered_poultry_hatch.filter(left_over__gt=F('quantity') * 0.1,
                                                                             poultry__key=no_license['poultry__key']
                                                                             , period=no_license['period'] - 1))
                    no_license3_no_license1.append(no_licence2_no_license1)

            for p in no_license3_no_license1:
                for poultry_hatching in p:

                    all_quantity_no_license1 += poultry_hatching['quantity']
                    all_poultry_hatching_quantity_no_license1 += poultry_hatching['quantity']
                    all_poultry_hatching_killed_quantity_no_license1 += poultry_hatching['killed_quantity']
                    all_total_killed_weight_no_license1 += poultry_hatching['total_killed_weight']
                    all_poultry_hatching_left_over_no_license1 += poultry_hatching['left_over']
                    all_total_commitment_no_license1 += poultry_hatching['total_commitment']
                    all_governmental_quantity_no_license1 += poultry_hatching['governmental_quantity']
                    all_governmental_killed_quantity_no_license1 += poultry_hatching['governmental_killed_quantity']
                    all_losses_no_license1 += poultry_hatching['losses']
                    all_free_killed_quantity_no_license1 += poultry_hatching['free_killed_quantity']
                    all_free_quantity_no_license1 += poultry_hatching['free_quantity']
                    all_out_province_killed_quantity_no_license1 += poultry_hatching['out_province_killed_quantity']
                    all_out_province_killed_weight_no_license1 += poultry_hatching['out_province_killed_weight']
                    if poultry_hatching['chicken_age'] not in min_list_no_license1:
                        min_list_no_license1.append(poultry_hatching['chicken_age'])

                    left_over_ninty_percent = ((poultry_hatching['quantity'] * 90) / 100) - poultry_hatching[
                        'killed_quantity']
                    all_left_over_ninty_percent_no_license1 += left_over_ninty_percent

            min_list_no_license1 = sorted(min_list_no_license1)

            value_header_list = [
                len(no_license3_no_license1),
                all_quantity_no_license1,
                all_poultry_hatching_killed_quantity_no_license1,
                all_total_killed_weight_no_license1,
                all_poultry_hatching_left_over_no_license1,
                all_left_over_ninty_percent_no_license1,
                min_list_no_license1[0] if len(min_list_no_license1) > 0 else '-',
                min_list_no_license1[len(min_list) - 1] if len(min_list_no_license1) > 0 else '-',
                all_total_commitment_no_license1,
                all_governmental_quantity_no_license1,
                all_governmental_killed_quantity_no_license1,
                all_free_quantity_no_license1,
                all_free_killed_quantity_no_license1,
                all_out_province_killed_quantity_no_license1,
                all_out_province_killed_weight_no_license1
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=19, column=item + 3, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            for col_num, option in enumerate(header_list, 4):
                cell = worksheet.cell(row=23, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFC000", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[23].height = 48.8
            all_quantity = 0
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs_not_code_but_have_assigment.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs_not_code_but_have_assigment.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity', 0)
            accepted_real_wight = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity', 0)

            all_vet_accepted_real_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity', 0)
            all_vet_accepted_real_weight = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity', 0)

            if filtered_kill_reqs_not_code_but_have_assigment:
                for kill in filtered_kill_reqs_not_assigment_but_have_code:
                    code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity += quantity

                    if kill.get('killhouse_user__killer') == False:
                        killers = 'کشتارگاه'
                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity += real_quantity

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte += weight

            has_code = len(filtered_kill_reqs_not_code_but_have_assigment.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs_not_code_but_have_assigment.aggregate(
                total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity', 0)
            has_qarantine = len(
                filtered_kill_reqs_not_code_but_have_assigment.filter(quarantine_quantity__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_code_but_have_assigment),
                all_quantity,
                all_weighte,
                has_code,
                has_qarantine,

                all_quarantine_quantity if all_quarantine_quantity != None else 0,
                all_vet_state_accepted,
                all_vet_accepted_real_quantity,
                all_vet_accepted_real_weight,
                len(bar_complete),
                all_real_quantity,
                all_net_weighte,
                accepted_real_quantity if accepted_real_quantity != None else 0,
                accepted_real_wight if accepted_real_wight != None else 0

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=24, column=item + 4, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)
            for col_num, option in enumerate(header_list[:4], 7):
                cell = worksheet.cell(row=28, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFC000", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[28].height = 48.8

            all_quantity_2 = 0

            all_weighte_2 = 0

            if filtered_kill_reqs_not_assigment_but_have_code:
                for kill in filtered_kill_reqs_not_assigment_but_have_code:
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity_2 += quantity

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte_2 += weight

            has_code_2 = len(filtered_kill_reqs_not_assigment_but_have_code.filter(clearance_code__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment_but_have_code),
                all_quantity_2,
                all_weighte_2,
                has_code_2,
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=29, column=item + 7, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            for col_num, option in enumerate(header_list[:4], 7):
                cell = worksheet.cell(row=33, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFC000", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[33].height = 48.8
            all_quantity_3 = 0
            all_real_quantity_3 = 0
            all_net_weighte_3 = 0
            all_weighte_3 = 0
            if filtered_kill_reqs_not_assigment_but_have_code1:
                for kill in filtered_kill_reqs_not_assigment_but_have_code1:
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity_3 += quantity

                    assignment = KillHouseAssignmentInformation.objects.filter(
                        kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                                   'real_quantity').values(
                        'net_weight', 'real_quantity', 'create_date').first()
                    if assignment:
                        net_weighte = assignment.get('net_weight')
                        all_net_weighte_3 += net_weighte
                        real_quantity = assignment.get('real_quantity')
                        all_real_quantity_3 += real_quantity

                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte_3 += weight

            has_code_3 = len(filtered_kill_reqs_not_assigment_but_have_code1.filter(clearance_code__isnull=False))

            value_header_list = [
                len(filtered_kill_reqs_not_assigment_but_have_code1),
                all_quantity_3,
                all_weighte_3,
                has_code_3,
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=34, column=item + 7, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

            for col_num, option in enumerate(header_list[:3], 7):
                cell = worksheet.cell(row=38, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = PatternFill(start_color="FFC000", fill_type="solid")
                cell.font = Font(size=9, bold=True)
                worksheet.row_dimensions[38].height = 48.8

            all_quantity_4 = 0

            all_weighte_4 = 0
            if filtered_kill_reqs__assigment_but_havent_code:
                for kill in filtered_kill_reqs__assigment_but_havent_code:
                    if kill.get('quantity'):
                        quantity = kill.get('quantity')
                        all_quantity_4 += quantity
                    weight = kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight')
                    all_weighte_4 += weight
            value_header_list = [
                len(filtered_kill_reqs__assigment_but_havent_code),
                all_quantity_4,
                all_weighte_4,
            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=39, column=item + 7, value=value_header_list[item])
                value = value_header_list[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                cell.alignment = Alignment(horizontal='center')
                cell.font = Font(size=10, bold=True)

    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش روزانه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filterset_class = PoultryRequestFilterSet
    filterset_fields = [
        'order_code',
        'poultry__user__mobile',
        'poultry__user__fullname',
        'poultry__user__first_name',
        'poultry__user__last_name',
        'poultry__address__city__name',

    ]

    state = request.GET['state']

    name_bar = ''
    if request.GET['role'] == 'VetFarm':
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
        poultries = Poultry.objects.filter(
            pk__in=vet_farms.values('poultry')
        )
        if state == 'pending':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                      wage_pay=False),
                poultry__in=poultries, send_date__date__gte=date1,
                send_date__date__lte=date2,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
        elif state == 'accepted':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                poultry__in=poultries, send_date__date__gte=date1,
                send_date__date__lte=date2,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
        else:
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                  wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                         province_state='rejected',
                                                                         final_state='archive',
                                                                         has_wage=False, wage_pay=False,
                                                                         out_province_request_cancel=False) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True),
                poultry__in=poultries, send_date__date__gte=date1,
                send_date__date__lte=date2,
                trash=False).order_by('-send_date')

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

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

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

            name_bar = 'حذف/رد شده'

    elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        if state == 'pending':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                      wage_pay=False),
                poultry__address__city=user.city,
                send_date__date__gte=date1,
                send_date__date__lte=date2,
                out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
            name_bar = 'جدید'
        elif state == 'accepted':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                poultry__address__city=user.city,
                send_date__date__gte=date1,
                send_date__date__lte=date2,
                out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
            name_bar = 'تایید شده'
        else:
            name_bar = 'حذف/رد شده'
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                  wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                         province_state='rejected',
                                                                         final_state='archive',
                                                                         has_wage=False, wage_pay=False,
                                                                         out_province_request_cancel=False) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True),
                poultry__address__city=user.city,
                send_date__date__gte=date1,
                send_date__date__lte=date2,
                out=True,
                trash=False).order_by('-send_date')


    elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX']:
        if request.GET['state'] == 'pending':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                      wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
            name_bar = 'جدید'
        elif state == 'accepted':
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                  wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                     has_wage=False, wage_pay=False),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                out_province_request_cancel=False,
                trash=False).order_by('-send_date')
            name_bar = 'تایید شده'
        else:
            poultry_requests = PoultryRequest.objects.filter(
                Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                  wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                         province_state='rejected',
                                                                         final_state='archive',
                                                                         has_wage=False, wage_pay=False,
                                                                         out_province_request_cancel=False) | Q(
                    state_process='pending', province_state='pending', final_state='pending',
                    has_wage=False, wage_pay=False, out_province_request_cancel=True),
                send_date__date__gte=date1,
                send_date__date__lte=date2, out=True,
                trash=False).order_by('-send_date')
            name_bar = 'رد شده'
    else:
        poultry_requests = PoultryRequest.objects.filter(
            Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
              wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                  wage_pay=False),
            send_date__date__gte=date1,
            send_date__date__lte=date2,
            out_province_request_cancel=False,
            trash=False).order_by('-send_date')

    if 'search' in request.GET:
        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=poultry_requests
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=poultry_requests)
                        poultry_requests = ps.filter()

    poultry_requests_accepted = poultry_requests.filter(province_state='accepted')

    excel_options = [
        'ردیف',
        'وضعیت',
        'پرداخت کننده',
        'کدسفارش مرغدار',
        ' تاریخ ثبت درخواست',
        ' تاریخ کشتار',
        ' کشتار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        ' استان مرغدار',
        'سن مرغ',
        ' نژاد',
        'تعداد درخواست',
        'میانگین وزنی',
        'وزن درخواست',
        'مانده در سالن',
        'جوجه ریزی اولیه',

        ' ماهیت خریدار',
        'خریدار',
        'تلفن خریدار',
        ' شهر خریدار',
        'استان خریدار',
        'محل کشتار',
        'کد یکتای کشتارگاه',
        'شهر محل کشتار',

        'نوع خودرو',
        'پلاک',

        'نام راننده',
        'موبایل راننده',
        'کد بهداشتی حمل و نقل',

        'کد رهگیری سامانه قرنطینه',
        'تعداد در قرنطینه',
        'ثبت کننده کد قرنطینه',
        'تاریخ ثبت  کد قرنطینه',
        'سازنده',

    ]

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای تایید شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'کمترین سن مرغ',
        'بیشترین سن مرغ',
        'تعداد بارهای دارای کد قرنطینه',

    ]
    for col_num, option in enumerate(header_list, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای {name_bar} خارج از استان'
    if poultry_requests.exists():
        name = poultry_requests.first().poultry.user.province.name
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 6
    m = 1

    all_weighte = 0
    all_chicken_quantity = 0
    all_age = []
    all_quantity = poultry_requests_accepted.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)

    all_weighte = poultry_requests_accepted.aggregate(
        total=Sum(F('quantity') * F('Index_weight')))[
        'total']

    has_code = 0
    if poultry_requests:
        for poultry_request in poultry_requests:

            # if ProvinceKillRequest.objects.filter(
            #         province_request__city_request_Poultry__poultry_request=poultry_request,
            #         state='accepted').exists():
            #     age = (poultry_request.send_date - poultry_request.hatching.date).days + 1
            # else:
            age = (poultry_request.send_date - poultry_request.hatching.date).days + 1
            all_age.append(age)
            all_chicken_quantity += poultry_request.hatching.quantity
            create_date_of_poultry_request = jdatetime.date.fromgregorian(
                day=poultry_request.create_date.day,
                month=poultry_request.create_date.month,
                year=poultry_request.create_date.year
            )
            date_of_kill_request = jdatetime.date.fromgregorian(
                day=poultry_request.send_date.day,
                month=poultry_request.send_date.month,
                year=poultry_request.send_date.year
            )
            if poultry_request.quarantine_code_registrar is not None:
                date_code = poultry_request.quarantine_code_registrar['date'].split('-')

                date_of_create_code = jdatetime.date.fromgregorian(
                    day=int(date_code[2]),
                    month=int(date_code[1]),
                    year=int(date_code[0])
                )
                full_name = poultry_request.quarantine_code_registrar['fullname']
                mobile = poultry_request.quarantine_code_registrar['mobile']
            else:
                date_of_create_code = '-'
                full_name = '-'
                mobile = '-'

            killing_place = '-'
            killing_place_city = '-'
            uniq_id = '-'
            if poultry_request.out_province_poultry_request_buyer:
                if poultry_request.out_province_poultry_request_buyer.type == 'killhouse':
                    is_killer = 'کشتارگاه'
                    uniq_id = poultry_request.out_province_poultry_request_buyer.kill_house_unique_id if poultry_request.out_province_poultry_request_buyer.kill_house_unique_id else '-'

                else:
                    is_killer = 'کشتارکن'
                    killing_place = poultry_request.killer_kill_house_unit_name \
                        if poultry_request.killer_kill_house_unit_name is not None \
                        else '-'
                    killing_place_city = poultry_request.killer_kill_house_province \
                                         + '(' + poultry_request.killer_kill_house_city \
                                         + ')' if poultry_request.killer_kill_house_province \
                                                  and poultry_request.killer_kill_house_city is not None \
                        else '-'
                    uniq_id = poultry_request.kill_house_unique_id if poultry_request.kill_house_unique_id else '-'
            else:
                is_killer = 'کشتارگاه' if poultry_request.buyer is not None and poultry_request.buyer[
                    'buyerType'] == 'killhouse' else 'کشتارکن'
            if PoultryRequestQuarantineCode.objects.filter(trash=False,poultry_request=poultry_request).exists():
                all_quanrantine=PoultryRequestQuarantineCode.objects.filter(trash=False,poultry_request=poultry_request)
                quaranatine_quantity=all_quanrantine.aggregate(total=Sum('system_quarantine_quantity'))['total'] or 0
                all_code=all_quanrantine.values_list('quarantine_code',flat=True)
                code='-'.join(all_code)
            elif poultry_request.quarantine_code:
                code = poultry_request.quarantine_code
                quaranatine_quantity = poultry_request.quarantine_quantity
                has_code += 1
            else:
                code = '-'
                quaranatine_quantity=0

            freez_state = 'منجمد' if poultry_request.freezing == True else 'عادی'

            if poultry_request.out_province_poultry_request_buyer is not None:
                full_name_buyer = poultry_request.out_province_poultry_request_buyer.fullname
                mobile_buyer = poultry_request.out_province_poultry_request_buyer.user.mobile
                city_buyer = poultry_request.out_province_poultry_request_buyer.user.city.name
                province_buyer = poultry_request.out_province_poultry_request_buyer.user.province.name

            else:
                full_name_buyer = poultry_request.buyer['firstName']
                mobile_buyer = poultry_request.buyer['mobile']
                city_buyer = poultry_request.buyer['city']
                province_buyer = poultry_request.buyer['province']

            if poultry_request.province_state == 'rejected':
                state1 = 'رد شده'
            elif poultry_request.province_state == 'pending' and poultry_request.out_province_request_cancel == False:
                state1 = 'در انتظار تایید'

            elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False:
                state1 = 'در انتظار پرداخت'
            elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == False and poultry_request.wage_pay == False and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False:
                state1 = 'تایید شده'
            elif poultry_request.province_state == 'accepted' and poultry_request.has_wage == True and poultry_request.wage_pay == True and poultry_request.out_province_request_cancel == False and poultry_request.out_province_request_cancel == False:
                state1 = 'پرداخت شده'
            else:
                state1 = 'لغو شده'

            list1 = [
                m,
                state1,
                poultry_request.payer_fullname if poultry_request.payer_fullname else '-',
                str(poultry_request.order_code),
                str(create_date_of_poultry_request),
                str(date_of_kill_request),
                freez_state,
                poultry_request.poultry.user.fullname,
                poultry_request.poultry.user.mobile,
                poultry_request.poultry.user.city.name,
                poultry_request.poultry.user.province.name,
                age,
                poultry_request.hatching.chicken_breed,
                poultry_request.quantity,
                poultry_request.Index_weight,
                int(poultry_request.quantity * poultry_request.Index_weight),
                poultry_request.hatching.left_over,
                poultry_request.hatching.quantity,
                is_killer,
                full_name_buyer,
                mobile_buyer,
                city_buyer,
                province_buyer,
                killing_place,
                uniq_id,
                killing_place_city,
                poultry_request.out_province_driver_info[
                    'driverCar'] if poultry_request.out_province_driver_info != None else '-',
                poultry_request.out_province_driver_info[
                    'driverPelak'] if poultry_request.out_province_driver_info != None else '-',
                poultry_request.out_province_driver_info[
                    'driverName'] if poultry_request.out_province_driver_info != None else '-',
                poultry_request.out_province_driver_info[
                    'driverMobile'] if poultry_request.out_province_driver_info != None else '-',
                poultry_request.out_province_driver_info[
                    'driverhealthCode'] if poultry_request.out_province_driver_info != None else '-',
                code,
                quaranatine_quantity,
                full_name + '(' + mobile + ')',
                str(date_of_create_code),
                poultry_request.registrar['fullname'] if poultry_request.registrar else '-'
            ]

            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')
            l += 1

    # last_age=sorted(reversed(all_age))
    all_age = sorted(all_age)
    value_header_list2 = [
        len(poultry_requests_accepted),
        all_quantity if all_quantity != None else 0,
        all_weighte if all_weighte != None else 0,
        all_age[0] if len(all_age) > 0 else None,
        all_age[len(all_age) - 1] if len(all_age) > 0 else None,
        has_code,

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_quantity if all_quantity != None else 0,
        '',
        all_weighte,
        '',
        all_chicken_quantity,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="بار های خارج از استان.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def steward_ware_house_total_report_daily_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(request.GET['date1'],
                                       '%Y-%m-%d').date() if 'date1' in request.GET else now
    date2 = datetime.datetime.strptime(request.GET['date2'],
                                       '%Y-%m-%d').date() if 'date2' in request.GET else now
    names_list = {'اطلاعات کلی': '0'}

    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_allocations = StewardAllocation.objects.filter(
        Q(type='manual') | Q(type='auto', system_registration_code=True),
        steward_ware_house__in=steward_ware_houses, receiver_state__in=('pending', 'accepted'),
        trash=False).order_by(
        'id')

    for kill in steward_allocations:
        if kill.steward_ware_house:
            if kill.steward_ware_house.steward.guilds.key not in names_list.values():
                names_list.update(
                    {kill.steward_ware_house.steward.guilds.guilds_name: kill.steward_ware_house.steward.key})

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

    total_number_of_free_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_free_carcasses'))[
        'total']
    total_free_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_free_carcasses'))[
        'total']
    total_number_of_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_carcasses'))[
        'total']
    total_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_carcasses'))[
        'total']

    final_total_number_of_carcasses = \
        steward_ware_houses.aggregate(total=Sum('real_number_of_carcasses'))[
            'total']
    final_total_weight_of_carcasses = \
        steward_ware_houses.aggregate(total=Sum('real_weight_of_carcasses'))[
            'total']

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

    total_remain_weight = \
        steward_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']
    abc_list = ['A', 'B', 'C', 'D', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S']

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    number_of_steward = Steward.objects.filter(
        pk__in=steward_ware_houses.values('steward')
    )
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    for name, key in names_list.items():
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

        if sheet_name == 'اطلاعات کلی':
            worksheet.row_dimensions[2].height = 24
            worksheet.row_dimensions[3].height = 30
            worksheet.row_dimensions[5].height = 19.04
            worksheet.row_dimensions[8].height = 32

            worksheet['A2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'
            worksheet['G2'] = f'اطلاعات کلی توزیع و پخش مرغ گرم از تاریخ {from_date_1} تا {to_date_1}'

            worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['G2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range122 = 'A2:D2'
            merge_range123 = 'G2:N2'
            worksheet.merge_cells(merge_range122)
            worksheet.merge_cells(merge_range123)

            worksheet['G2'].font = Font(size=12, color='FF0000')

            for abc in abc_list:
                worksheet[f'{abc}8'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            for abc in abc_list[1:]:
                worksheet[f'{abc}3'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            withe_font = Font(size=10, color='D9FFFFFF')
            blue = PatternFill(start_color="4472C4", fill_type="solid")
            green = PatternFill(start_color="00B050", fill_type="solid")
            worksheet['B3'] = f'تعداد خریداران'
            worksheet['C3'] = f'ورودی از سردخانه'
            worksheet['E3'] = f'پیش سرد'
            worksheet['G3'] = f'خرید خارج از استان'
            worksheet['I3'] = f'بارهای روزانه'
            worksheet['K3'] = f'جمع کل انبار'
            worksheet['M3'] = f'توزیع شده'
            worksheet['O3'] = f'توزیع / تحویل شده'
            worksheet['Q3'] = f'مانده انبار'
            worksheet['S3'] = f'تعداد صنف تخصیص داده شده'

            worksheet['C3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['I3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['K3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['M3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['O3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['Q3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['S3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            merge_range1 = 'C3:D4'
            merge_range2 = 'E3:F4'
            merge_range3 = 'G3:H4'
            merge_range4 = 'I3:J4'
            merge_range5 = 'K3:L4'
            merge_range6 = 'M3:N4'
            merge_range7 = 'O3:P4'
            merge_range8 = 'Q3:R4'
            merge_range9 = 'B3:B5'
            merge_range10 = 'S3:S5'

            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)
            worksheet.merge_cells(merge_range10)

            worksheet['C3'].font = withe_font
            worksheet['B3'].font = withe_font
            worksheet['E3'].font = withe_font
            worksheet['G3'].font = withe_font
            worksheet['I3'].font = withe_font
            worksheet['K3'].font = withe_font
            worksheet['M3'].font = withe_font
            worksheet['O3'].font = withe_font
            worksheet['Q3'].font = withe_font
            worksheet['S3'].font = withe_font

            worksheet['B3'].fill = blue
            worksheet['C3'].fill = blue
            worksheet['E3'].fill = blue
            worksheet['G3'].fill = blue
            worksheet['I3'].fill = blue
            worksheet['K3'].fill = blue
            worksheet['M3'].fill = blue
            worksheet['O3'].fill = blue
            worksheet['Q3'].fill = blue
            worksheet['S3'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

            for item in range(len(list1)):
                cell = worksheet.cell(row=5, column=item + 3, value=list1[item])
                worksheet.row_dimensions[5].height = 19

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            worksheet['A8'] = f'ردیف'
            worksheet['B8'] = f'خریدار'
            worksheet['C8'] = f'شهرستان'
            worksheet['D8'] = f'تعداد صنف تخصیصی'
            worksheet['E8'] = f'ورودی از سردخانه'
            worksheet['G8'] = f'پیش سرد'
            worksheet['I8'] = f'خرید خارج از استان'
            worksheet['K8'] = f'بارهای روزانه'
            worksheet['M8'] = f'جمع کل انبار'
            worksheet['O8'] = f'توزیع شده'
            worksheet['Q8'] = f'توزیع / تحویل شده'
            worksheet['S8'] = f'مانده انبار'

            worksheet['A8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['B8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['C8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['D8'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['E8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['G8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['I8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['K8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['M8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['O8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['Q8'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['S8'].alignment = Alignment(horizontal='center', vertical='center')

            merge_range11 = 'A8:A10'
            merge_range12 = 'B8:B10'
            merge_range13 = 'C8:C10'
            merge_range14 = 'D8:D10'
            merge_range1 = 'E8:F9'
            merge_range2 = 'G8:H9'
            merge_range3 = 'I8:J9'
            merge_range4 = 'K8:L9'
            merge_range5 = 'M8:N9'
            merge_range6 = 'O8:P9'
            merge_range7 = 'Q8:R9'
            merge_range8 = 'S8:T9'

            worksheet.merge_cells(merge_range11)
            worksheet.merge_cells(merge_range12)
            worksheet.merge_cells(merge_range13)
            worksheet.merge_cells(merge_range14)
            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)

            worksheet['A8'].font = withe_font
            worksheet['B8'].font = withe_font
            worksheet['C8'].font = withe_font
            worksheet['D8'].font = withe_font
            worksheet['E8'].font = withe_font
            worksheet['G8'].font = withe_font
            worksheet['I8'].font = withe_font
            worksheet['K8'].font = withe_font
            worksheet['M8'].font = withe_font
            worksheet['O8'].font = withe_font
            worksheet['Q8'].font = withe_font
            worksheet['S8'].font = withe_font

            worksheet['A8'].fill = green
            worksheet['B8'].fill = green
            worksheet['C8'].fill = green
            worksheet['D8'].fill = green
            worksheet['E8'].fill = blue
            worksheet['G8'].fill = blue
            worksheet['I8'].fill = blue
            worksheet['K8'].fill = blue
            worksheet['M8'].fill = blue
            worksheet['O8'].fill = blue
            worksheet['Q8'].fill = blue
            worksheet['S8'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']
            for item in range(len(list1)):
                cell = worksheet.cell(row=10, column=item + 5, value=list1[item])
                worksheet.row_dimensions[5].height = 28

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            head_list1 = [len(number_of_steward),
                          0,
                          0,
                          0,
                          0,
                          total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                          total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                          total_number_of_carcasses if total_number_of_carcasses != None else 0,
                          total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                          final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                          final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                          total_allocated_quantity if total_allocated_quantity != None else 0,
                          total_allocated_weight if total_allocated_weight != None else 0,
                          total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                          total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                          total_remain_quantity if total_remain_quantity != None else 0,
                          total_remain_weight if total_remain_weight != None else 0,
                          number_of_guild,

                          ]
            for item in range(len(head_list1)):
                cell = worksheet.cell(row=6, column=item + 2, value=head_list1[item])
                worksheet.row_dimensions[6].height = 12
                value = head_list1[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            l = 11
            m = 1
            for steward in number_of_steward:
                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, steward=steward, trash=False)

                steward_allocations = StewardAllocation.objects.filter(
                    Q(type='manual') | Q(type='auto', system_registration_code=True),
                    steward_ware_house__in=steward_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

                total_number_of_free_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_free_carcasses'))[
                    'total']
                total_free_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_free_carcasses'))[
                    'total']
                total_number_of_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_carcasses'))[
                    'total']
                total_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_carcasses'))[
                    'total']

                final_total_number_of_carcasses = \
                    steward_ware_houses.aggregate(total=Sum('real_number_of_carcasses'))[
                        'total']
                final_total_weight_of_carcasses = \
                    steward_ware_houses.aggregate(total=Sum('real_weight_of_carcasses'))[
                        'total']

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

                total_remain_weight = \
                    steward_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']

                list2 = [
                    m,
                    steward.guilds.guilds_name,
                    steward.guilds.address.city.name,
                    number_of_guild,
                    0,
                    0,
                    0,
                    0,
                    total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                    total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                    total_number_of_carcasses if total_number_of_carcasses != None else 0,
                    total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                    final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                    final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                    total_allocated_quantity if total_allocated_quantity != None else 0,
                    total_allocated_weight if total_allocated_weight != None else 0,
                    total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                    total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                    total_remain_quantity if total_remain_quantity != None else 0,
                    total_remain_weight if total_remain_weight != None else 0,

                ]
                for item in range(len(list2)):
                    cell = worksheet.cell(row=l, column=item + 1, value=list2[item])
                    value = list2[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values
                    cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                    cell.font = Font(size=10, bold=True)
                    cell.border = openpyxl.styles.Border(
                        left=openpyxl.styles.Side(style='medium'),
                        right=openpyxl.styles.Side(style='medium'),
                        top=openpyxl.styles.Side(style='medium'),
                        bottom=openpyxl.styles.Side(style='medium')
                    )
                l += 1
                m += 1
        else:
            worksheet['F2'] = f'اطلاعات کلی توزیع و پخش از مباشر به صنف از تاریخ {from_date_1} تا {to_date_1}'

            worksheet['F2'].alignment = Alignment(horizontal='center', vertical='center')
            merge_range122 = 'F2:N2'
            worksheet.merge_cells(merge_range122)

            worksheet['F2'].font = Font(size=10)

            for abc in abc_list[2:]:
                worksheet[f'{abc}3'].border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )
            withe_font = Font(size=12, bold=True, color='D9FFFFFF')
            withe_font1 = Font(size=10, color='D9FFFFFF')
            blue = PatternFill(start_color="4472C4", fill_type="solid")
            worksheet['C3'] = f'ورودی از سردخانه'
            worksheet['E3'] = f'پیش سرد'
            worksheet['G3'] = f'خرید خارج از استان'
            worksheet['I3'] = f'مجموع بارها'
            worksheet['K3'] = f'جمع کل انبار'
            worksheet['M3'] = f'توزیع شده'
            worksheet['O3'] = f'توزیع / تحویل شده'
            worksheet['Q3'] = f'مانده انبار'
            worksheet['S3'] = f'تعداد صنف تخصیص داده شده'

            worksheet['C3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['I3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['K3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['M3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['O3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['Q3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            worksheet['S3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            merge_range1 = 'C3:D4'
            merge_range2 = 'E3:F4'
            merge_range3 = 'G3:H4'
            merge_range4 = 'I3:J4'
            merge_range5 = 'K3:L4'
            merge_range6 = 'M3:N4'
            merge_range7 = 'O3:P4'
            merge_range8 = 'Q3:R4'
            merge_range9 = 'S3:S5'

            worksheet.merge_cells(merge_range1)
            worksheet.merge_cells(merge_range2)
            worksheet.merge_cells(merge_range3)
            worksheet.merge_cells(merge_range4)
            worksheet.merge_cells(merge_range5)
            worksheet.merge_cells(merge_range6)
            worksheet.merge_cells(merge_range7)
            worksheet.merge_cells(merge_range8)
            worksheet.merge_cells(merge_range9)

            worksheet['C3'].font = withe_font
            worksheet['E3'].font = withe_font
            worksheet['G3'].font = withe_font
            worksheet['I3'].font = withe_font
            worksheet['K3'].font = withe_font
            worksheet['M3'].font = withe_font
            worksheet['O3'].font = withe_font
            worksheet['Q3'].font = withe_font
            worksheet['S3'].font = withe_font1

            worksheet['C3'].fill = blue
            worksheet['E3'].fill = blue
            worksheet['G3'].fill = blue
            worksheet['I3'].fill = blue
            worksheet['K3'].fill = blue
            worksheet['M3'].fill = blue
            worksheet['O3'].fill = blue
            worksheet['Q3'].fill = blue
            worksheet['S3'].fill = blue

            list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                     'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

            for item in range(len(list1)):
                cell = worksheet.cell(row=5, column=item + 3, value=list1[item])
                worksheet.row_dimensions[5].height = 19

                cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            steward = Steward.objects.get(key=key, trash=False)

            steward_ware_houses = StewardWareHouse.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                                  steward=steward, trash=False)

            steward_allocations = StewardAllocation.objects.filter(
                Q(type='manual') | Q(type='auto', system_registration_code=True),
                steward_ware_house__in=steward_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

            total_number_of_free_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_free_carcasses'))[
                'total']
            total_free_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_free_carcasses'))[
                'total']
            total_number_of_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_carcasses'))[
                'total']
            total_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_carcasses'))[
                'total']

            final_total_number_of_carcasses = \
                steward_ware_houses.aggregate(total=Sum('real_number_of_carcasses'))[
                    'total']
            final_total_weight_of_carcasses = \
                steward_ware_houses.aggregate(total=Sum('real_weight_of_carcasses'))[
                    'total']

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

            total_remain_weight = \
                steward_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']

            list2 = [
                0,
                0,
                0,
                0,
                total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
                total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
                total_number_of_carcasses if total_number_of_carcasses != None else 0,
                total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
                final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
                final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
                total_allocated_quantity if total_allocated_quantity != None else 0,
                total_allocated_weight if total_allocated_weight != None else 0,
                total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
                total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
                total_remain_quantity if total_remain_quantity != None else 0,
                total_remain_weight if total_remain_weight != None else 0,
                number_of_guild,

            ]

            for item in range(len(list2)):
                cell = worksheet.cell(row=6, column=item + 3, value=list2[item])
                value = list2[item]
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,##0'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.font = Font(size=10, bold=True)
                cell.border = openpyxl.styles.Border(
                    left=openpyxl.styles.Side(style='medium'),
                    right=openpyxl.styles.Side(style='medium'),
                    top=openpyxl.styles.Side(style='medium'),
                    bottom=openpyxl.styles.Side(style='medium')
                )

            excel_options = [
                'ردیف',
                'شناسه صنف',
                'تاریخ ثبت',
                'ماهیت',
                'نوع تخصیص',
                'نام واحد صنفی',
                'نام شخص',
                'کد ملی',
                'موبایل',
                'نوع فعالیت',
                'حوزه فعالیت',
                'شماره مجوز',
                'شهرستان',
                'تعداد لاشه تخصیص',
                'وزن لاشه تخصیصی',
                'تعداد لاشه تحویلی',
                'وزن لاشه تحویلی',
                'وضعیت',
                'کد احراز',
            ]

            for col_num, option in enumerate(excel_options, 1):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=9, column=col_num, value=option)
                cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                cell.fill = blue_fill
                cell.font = Font(size=10, bold=True, color='D9FFFFFF')
                if len(option) > worksheet.column_dimensions[col_letter].width:
                    worksheet.column_dimensions[col_letter].width = len(option) + 3

                    # تنظیم ارتفاع سطر
                    # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
                worksheet.row_dimensions[9].height = 26
                worksheet.freeze_panes = worksheet['A10']
                max_col = worksheet.max_column - 1
                range_str = f'A9:{get_column_letter(max_col)}{worksheet.max_row}'
                worksheet.auto_filter.ref = range_str
            m = 1
            l = 10

            steward = Steward.objects.get(key=key, trash=False)

            steward_ware_house = steward_ware_houses.filter(steward=steward)

            for s in steward_ware_house:
                stewards = (StewardAllocation.objects.filter(trash=False,
                                                             steward_ware_house=s,
                                                             date__date__gte=date1,
                                                             date__date__lte=date2).select_related('guilds',
                                                                                                   'guilds__user',
                                                                                                   'guilds__address__city',
                                                                                                   'kill_house',
                                                                                                   'kill_house__kill_house_operator').order_by(
                    'id'))

                if stewards.exists():
                    for steward_allocation in stewards:
                        create_date = jdatetime.date.fromgregorian(
                            day=steward_allocation.create_date.day,
                            month=steward_allocation.create_date.month,
                            year=steward_allocation.create_date.year
                        )
                        steward = 'مباشر' if steward_allocation.seller_type == 'steward' else 'صنف'
                        sell_type = 'اختصاصی' if steward_allocation.sell_type == 'exclusive' else 'آزاد'
                        type = 'دستی' if steward_allocation.type == 'manual' else 'اتوماتیک'
                        try:
                            guilds_name = steward_allocation.steward.guilds.guilds_name
                            guilds_id = steward_allocation.steward.guilds.guilds_id
                            fullname = steward_allocation.steward.guilds.user.fullname
                            national_id = steward_allocation.steward.guilds.user.national_id
                            mobile = steward_allocation.steward.guilds.user.mobile
                            type_activity = steward_allocation.steward.guilds.type_activity
                            area_activity = steward_allocation.steward.guilds.area_activity
                            license_number = steward_allocation.steward.guilds.license_number
                            city_name = steward_allocation.steward.guilds.address.city.name
                        except:
                            guilds_name = steward_allocation.guilds.guilds_name
                            guilds_id = steward_allocation.guilds.guilds_id
                            fullname = steward_allocation.guilds.user.fullname
                            national_id = steward_allocation.guilds.user.national_id
                            mobile = steward_allocation.guilds.user.mobile
                            type_activity = steward_allocation.guilds.type_activity
                            area_activity = steward_allocation.guilds.area_activity
                            license_number = steward_allocation.guilds.license_number
                            city_name = steward_allocation.guilds.address.city.name
                        if steward_allocation.receiver_state == 'pending':
                            reciver_type = 'در انتظار تحویل'
                            register = '-'
                        elif steward_allocation.receiver_state == 'accepted':
                            reciver_type = 'تحویل گرفته شد'
                            register = steward_allocation.logged_registration_code if steward_allocation.logged_registration_code else 'وارد نشده'

                        else:
                            reciver_type = 'رد شده'
                            register = '-'

                        list2 = [
                            m,
                            guilds_id,
                            str(create_date),
                            steward,
                            f'{sell_type}({type})',
                            guilds_name,
                            fullname,
                            national_id,
                            mobile,
                            type_activity,
                            area_activity,
                            license_number,
                            city_name,
                            steward_allocation.number_of_carcasses,
                            steward_allocation.weight_of_carcasses,
                            steward_allocation.receiver_real_number_of_carcasses,
                            steward_allocation.receiver_real_weight_of_carcasses,
                            reciver_type,
                            register,

                        ]
                        for item in range(len(list2)):
                            cell = worksheet.cell(row=l, column=item + 1, value=list2[item])
                            value = list2[item]
                            if isinstance(value, (int, float)):
                                if value != 0:
                                    cell.number_format = '#,##0'  # Apply general number format
                            else:
                                cell.value = value  # Keep as text for other values

                            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

                        m += 1
                        l += 1
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش پخش لاشه مرغ گرم از مباشر به صنف.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def steward_ware_house_total_report_daily_detail_excel(request):
    abc_list = ['A', 'B', 'C', 'D', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S']

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

    steward = Steward.objects.get(key=request.GET['key'], trash=False)

    steward_ware_houses = StewardWareHouse.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                          steward=steward, trash=False)

    steward_allocations = StewardAllocation.objects.filter(
        Q(type='manual') | Q(type='auto', system_registration_code=True),
        steward_ware_house__in=steward_ware_houses, receiver_state__in=('pending', 'accepted'),
        trash=False).order_by(
        'id')
    name = steward.guilds.guilds_name

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

    total_number_of_free_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_free_carcasses'))[
        'total']
    total_free_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_free_carcasses'))[
        'total']
    total_number_of_carcasses = steward_ware_houses.aggregate(total=Sum('number_of_carcasses'))[
        'total']
    total_weight_of_carcasses = steward_ware_houses.aggregate(total=Sum('weight_of_carcasses'))[
        'total']

    final_total_number_of_carcasses = \
        steward_ware_houses.aggregate(total=Sum('real_number_of_carcasses'))[
            'total']
    final_total_weight_of_carcasses = \
        steward_ware_houses.aggregate(total=Sum('real_weight_of_carcasses'))[
            'total']

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

    total_remain_weight = \
        steward_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']

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    names_list = [steward.guilds.guilds_name]
    output = BytesIO()
    workbook = Workbook()
    for name in names_list:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

        worksheet['F2'] = f'اطلاعات کلی توزیع و پخش مرغ گرم از تاریخ {from_date_1} تا {to_date_1}'

        worksheet['F2'].alignment = Alignment(horizontal='center', vertical='center')
        merge_range122 = 'F2:N2'
        worksheet.merge_cells(merge_range122)

        worksheet['F2'].font = Font(size=10)

        for abc in abc_list[2:11]:
            worksheet[f'{abc}3'].border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='medium'),
                right=openpyxl.styles.Side(style='medium'),
                top=openpyxl.styles.Side(style='medium'),
                bottom=openpyxl.styles.Side(style='medium')
            )
        withe_font = Font(size=12, bold=True, color='D9FFFFFF')
        blue = PatternFill(start_color="4472C4", fill_type="solid")
        worksheet['C3'] = f'ورودی از سردخانه'
        worksheet['E3'] = f'پیش سرد'
        worksheet['G3'] = f'خرید خارج از استان'
        worksheet['I3'] = f'بارهای روزانه'
        worksheet['K3'] = f'جمع کل انبار'
        worksheet['M3'] = f'توزیع شده'
        worksheet['O3'] = f'توزیع / تحویل شده'
        worksheet['Q3'] = f'مانده انبار'

        worksheet['C3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['E3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['G3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['I3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['K3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['M3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['O3'].alignment = Alignment(horizontal='center', vertical='center')
        worksheet['Q3'].alignment = Alignment(horizontal='center', vertical='center')

        merge_range1 = 'C3:D4'
        merge_range2 = 'E3:F4'
        merge_range3 = 'G3:H4'
        merge_range4 = 'I3:J4'
        merge_range5 = 'K3:L4'
        merge_range6 = 'M3:N4'
        merge_range7 = 'O3:P4'
        merge_range8 = 'Q3:R4'

        worksheet.merge_cells(merge_range1)
        worksheet.merge_cells(merge_range2)
        worksheet.merge_cells(merge_range3)
        worksheet.merge_cells(merge_range4)
        worksheet.merge_cells(merge_range5)
        worksheet.merge_cells(merge_range6)
        worksheet.merge_cells(merge_range7)
        worksheet.merge_cells(merge_range8)

        worksheet['C3'].font = withe_font
        worksheet['E3'].font = withe_font
        worksheet['G3'].font = withe_font
        worksheet['I3'].font = withe_font
        worksheet['K3'].font = withe_font
        worksheet['M3'].font = withe_font
        worksheet['O3'].font = withe_font
        worksheet['Q3'].font = withe_font

        worksheet['C3'].fill = blue
        worksheet['E3'].fill = blue
        worksheet['G3'].fill = blue
        worksheet['I3'].fill = blue
        worksheet['K3'].fill = blue
        worksheet['M3'].fill = blue
        worksheet['O3'].fill = blue
        worksheet['Q3'].fill = blue

        list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد',
                 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']

        for item in range(len(list1)):
            cell = worksheet.cell(row=5, column=item + 3, value=list1[item])
            worksheet.row_dimensions[5].height = 19

            cell.fill = PatternFill(start_color="FFD966", fill_type="solid")
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.font = Font(size=10, bold=True)
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='medium'),
                right=openpyxl.styles.Side(style='medium'),
                top=openpyxl.styles.Side(style='medium'),
                bottom=openpyxl.styles.Side(style='medium')
            )

        list2 = [
            0,
            0,
            0,
            0,
            total_number_of_free_carcasses if total_number_of_free_carcasses != None else 0,
            total_free_weight_of_carcasses if total_free_weight_of_carcasses != None else 0,
            total_number_of_carcasses if total_number_of_carcasses != None else 0,
            total_weight_of_carcasses if total_weight_of_carcasses != None else 0,
            final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0,
            final_total_weight_of_carcasses if final_total_weight_of_carcasses != None else 0,
            total_allocated_quantity if total_allocated_quantity != None else 0,
            total_allocated_weight if total_allocated_weight != None else 0,
            total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0,
            total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0,
            total_remain_quantity if total_remain_quantity != None else 0,
            total_remain_weight if total_remain_weight != None else 0,

        ]
        for item in range(len(list2)):
            cell = worksheet.cell(row=6, column=item + 3, value=list2[item])
            value = list2[item]
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,##0'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            cell.fill = PatternFill(start_color="E9EBF5", fill_type="solid")
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.font = Font(size=10, bold=True)
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='medium'),
                right=openpyxl.styles.Side(style='medium'),
                top=openpyxl.styles.Side(style='medium'),
                bottom=openpyxl.styles.Side(style='medium')
            )

        excel_options = [
            'ردیف',
            'شناسه صنف',
            'تاریخ ثبت',
            'ماهیت',
            'نوع تخصیص',
            'نام واحد صنفی',
            'نام شخص',
            'کد ملی',
            'موبایل',
            'نوع فعالیت',
            'حوزه فعالیت',
            'شماره مجوز',
            'شهرستان',
            'تعداد لاشه تخصیص',
            'وزن لاشه تخصیصی',
            'تعداد لاشه تحویلی',
            'وزن لاشه تحویلی',
            'وضعیت',
            'کد احراز',
        ]

        for col_num, option in enumerate(excel_options, 1):
            col_letter = get_column_letter(col_num)
            cell = worksheet.cell(row=9, column=col_num, value=option)
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.fill = blue_fill
            cell.font = Font(size=10, bold=True, color='D9FFFFFF')
            if len(option) > worksheet.column_dimensions[col_letter].width:
                worksheet.column_dimensions[col_letter].width = len(option) + 3

                # تنظیم ارتفاع سطر
                # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
            worksheet.row_dimensions[9].height = 26
            worksheet.freeze_panes = worksheet['A10']
            max_col = worksheet.max_column
            range_str = f'A9:{get_column_letter(max_col)}{worksheet.max_row}'
            worksheet.auto_filter.ref = range_str
        m = 1
        l = 10

        stewards = (StewardAllocation.objects.filter(trash=False,
                                                     steward_ware_house__in=steward_ware_houses,
                                                     date__date__gte=date1, date__date__lte=date2).select_related(
            'guilds',
            'guilds__user',
            'guilds__address__city',
            'kill_house',
            'kill_house__kill_house_operator').order_by(
            'id'))

        if stewards.exists():
            for steward_allocation in stewards:
                create_date = jdatetime.date.fromgregorian(
                    day=steward_allocation.create_date.day,
                    month=steward_allocation.create_date.month,
                    year=steward_allocation.create_date.year
                )
                steward = 'مباشر' if steward_allocation.seller_type == 'steward' else 'صنف'
                sell_type = 'اختصاصی' if steward_allocation.sell_type == 'exclusive' else 'آزاد'
                type = 'دستی' if steward_allocation.type == 'manual' else 'اتوماتیک'
                try:
                    guilds_name = steward_allocation.steward.guilds.guilds_name
                    guilds_id = steward_allocation.steward.guilds.guilds_id
                    fullname = steward_allocation.steward.guilds.user.fullname
                    national_id = steward_allocation.steward.guilds.user.national_id
                    mobile = steward_allocation.steward.guilds.user.mobile
                    type_activity = steward_allocation.steward.guilds.type_activity
                    area_activity = steward_allocation.steward.guilds.area_activity
                    license_number = steward_allocation.steward.guilds.license_number
                    city_name = steward_allocation.steward.guilds.address.city.name
                except:
                    guilds_name = steward_allocation.guilds.guilds_name
                    guilds_id = steward_allocation.guilds.guilds_id
                    fullname = steward_allocation.guilds.user.fullname
                    national_id = steward_allocation.guilds.user.national_id
                    mobile = steward_allocation.guilds.user.mobile
                    type_activity = steward_allocation.guilds.type_activity
                    area_activity = steward_allocation.guilds.area_activity
                    license_number = steward_allocation.guilds.license_number
                    city_name = steward_allocation.guilds.address.city.name
                if steward_allocation.receiver_state == 'pending':
                    reciver_type = 'در انتظار تحویل'
                    register = '-'
                elif steward_allocation.receiver_state == 'accepted':
                    reciver_type = 'تحویل گرفته شد'
                    register = steward_allocation.logged_registration_code if steward_allocation.logged_registration_code else 'وارد نشده'

                else:
                    reciver_type = 'رد شده'
                    register = '-'

                list2 = [
                    m,
                    guilds_id,
                    str(create_date),
                    steward,
                    f'{sell_type}({type})',
                    guilds_name,
                    fullname,
                    national_id,
                    mobile,
                    type_activity,
                    area_activity,
                    license_number,
                    city_name,
                    steward_allocation.number_of_carcasses,
                    steward_allocation.weight_of_carcasses,
                    steward_allocation.receiver_real_number_of_carcasses,
                    steward_allocation.receiver_real_weight_of_carcasses,
                    reciver_type,
                    register,

                ]
                for item in range(len(list2)):
                    cell = worksheet.cell(row=l, column=item + 1, value=list2[item])
                    value = list2[item]
                    if isinstance(value, (int, float)):
                        if value != 0:
                            cell.number_format = '#,##0'  # Apply general number format
                    else:
                        cell.value = value  # Keep as text for other values

                    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

                m += 1
                l += 1
    workbook.remove_sheet(workbook.get_sheet_by_name('Sheet'))
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="{name} در تاریخ {str(now)}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def hatching_by_age_range(request):
    min_age = request.GET.get('min_age')
    max_age = request.GET.get('max_age')
    
    # فیلتر اولیه برای تمام داده‌ها
    base_filtered_poultry_hatch = PoultryHatching.objects.filter(
        Q(left_over__gt=F('quantity') * percent_of_losses) | Q(violation=True),
        trash=False
    ).select_related('poultry', 'poultry__user')
    
    # تفکیک فعال‌ها: فیلتر براساس now_age (سن روز)
    active_poultry_hatch = base_filtered_poultry_hatch.filter(
        archive=False,
        allow_hatching='pending'
    )
    if min_age and max_age:
        # محاسبه now_age برای هر رکورد و فیلتر
        active_list = []
        for hatching in active_poultry_hatch:
            now_age = (datetime.datetime.now().date() - hatching.date.date()).days + 1
            if int(min_age) <= now_age <= int(max_age):
                active_list.append(hatching.id)
        active_poultry_hatch = active_poultry_hatch.filter(id__in=active_list)
    active_poultry_hatch = active_poultry_hatch.order_by('-date')
    
    # تفکیک بایگانی‌ها: فیلتر براساس chicken_age (سن بایگانی) با همان min_age و max_age
    archive_poultry_hatch = base_filtered_poultry_hatch.filter(
        archive=True,
        allow_hatching='True'
    )
    if min_age and max_age:
        archive_poultry_hatch = archive_poultry_hatch.filter(
            chicken_age__gte=int(min_age),
            chicken_age__lte=int(max_age)
        )
    archive_poultry_hatch = archive_poultry_hatch.order_by('-archive_date')
    
    excel_options = [
        'ردیف',
        'وضعیت فارم',
        'وضعیت تخلف',
        'نام و خانوادگی',
        'نام فارم',
        'موبایل',
        'شهرستان',
        'کد یکتا',
        'کد سیستمی واحد',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن بایگانی',
        'سن روز',
        'تعداد جوجه ریزی',
        'تلفات دامپزشک(قطعه)',
        'تلفات اتحادیه(قطعه)',
        'تلفات کل(قطعه)',
        'تعداد کشتار شده(قطعه)',
        'وزن کل کشتارشده(کیلوگرم)',
        'مانده در سالن',
        'یازده درصد جوجه ریزی',
        'تعداد تخلف',
        'وزن تعهد دولتی(کیلوگرم)',
        'تعداد کشتار دولتی(قطعه)',
        'وزن کشتار دولتی(کیلوگرم)',
        'تعداد کشتار آزاد(قطعه)',
        'وزن کشتار آزاد(کیلوگرم)',
        'میانگین وزن کشتار(کیلوگرم)',
        'سازنده جوجه ریزی',
        'کد اپیدمیولوژیک',
        'تعداد کشتار خارج از استان(قطعه)',
        'وزن کشتار خارج از استان(کیلوگرم)',
        'دلیل تخلف',
        'ثبت کننده گزارش',
        'متن گزارش',
        'تاریخ گزارش',
    ]
    from_date_1 = shamsi_date(datetime.datetime.now().date())
    
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    
    sheet_names = ['فعال', 'بایگانی']
    sheets_data = [
        {'name': 'فعال', 'data': active_poultry_hatch, 'is_archive': False},
        {'name': 'بایگانی', 'data': archive_poultry_hatch, 'is_archive': True}
    ]
    
    for sheet_info in sheets_data:
        sheet_name = sheet_info['name']
        filtered_data = sheet_info['data']
        is_archive = sheet_info['is_archive']
        
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        cell = worksheet.cell(row=1, column=1)
        cell.alignment = Alignment(horizontal='center', vertical='center')
        red_font = Font(color="C00000", bold=True)
        
        header_list = [
            'تعداد فارم',
            'تعداد فارم فعال',
            'تعداد فارم بایگانی شده',
            'مجموع جوجه ریزی',
            'مجموع تلفات دامپزشک(قطعه)',
            'مجموع تلفات اتحادیه(قطعه)',
            'مجموع تلفات کل(قطعه)',
            'مجموع قطعه کشتار شده',
            'مجموع وزن  کشتارشده',
            'جمع کل مانده در سالن(قطعه)',
            'جمع مانده در سال فارم فعال(قطعه)',
            'جمع مانده در سالن فارم بایگانی(قطعه)',
            'کمترین سن ',
            'بیشترین سن ',
            'مجموع وزن تعهد دولتی',
            ' مجموع قطعه کشتار دولتی',
            ' مجموع وزن کشتار دولتی',
            ' مجموع قطعه کشتار آزاد',
            ' مجموع وزن کشتار آزاد',
            'مجموع تعداد کشتار خارج از استان',
            'مجموع وزن کشتار خارج از استان',
            'تعداد فارم های فعال متخلف',
            'تعداد فارم های بایگانی متخلف',
        ]

        create_header(worksheet, header_list, 5, 2, height=20)
        worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است. بین بازه سنی {min_age} تا {max_age}'
        worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
        merge_range1 = 'B2:C3'
        worksheet.merge_cells(merge_range1)
        worksheet['B2'].font = red_font

        create_header_freez(worksheet, excel_options, 1, 6, 7, height=22, width=20.1, different_cell='تعداد تخلف')
        
        l = 6
        m = 1
        all_poultry_hatching_quantity = 0
        all_poultry_hatching_killed_quantity = 0
        all_poultry_hatching_left_over = 0
        min_list = []
        all_left_over_ninty_percent = 0
        violation_count = 0
        len_archive_hatch = 0
        len_hatch = 0
        left_over_archive = 0
        left_over_active = 0
        all_eleven_percent = 0
        
        for poultry_hatching in filtered_data:
            now_age = (datetime.datetime.now().date() - poultry_hatching.date.date()).days + 1

            reason = 'مانده بیش از حد مجاز در سالن'
            all_poultry_hatching_quantity += poultry_hatching.quantity
            all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity
            all_poultry_hatching_left_over += poultry_hatching.left_over
            
            age = poultry_hatching.chicken_age
            if age not in min_list:
                min_list.append(age)
            
            if now_age not in min_list:
                min_list.append(now_age)

            l += 1
            create_date = jdatetime.date.fromgregorian(
                day=poultry_hatching.create_date.day,
                month=poultry_hatching.create_date.month,
                year=poultry_hatching.create_date.year
            )
            date = jdatetime.date.fromgregorian(
                day=poultry_hatching.date.day,
                month=poultry_hatching.date.month,
                year=poultry_hatching.date.year
            )
            
            if is_archive:
                state = 'بایگانی'
                len_archive_hatch += 1
                left_over_archive += poultry_hatching.left_over
            else:
                state = 'فعال'
                len_hatch += 1
                left_over_active += poultry_hatching.left_over
            creator = 'پنجره واحد'
            left_over_ninty_percent = (poultry_hatching.quantity * percent_of_losses)
            eleven_percent = (poultry_hatching.left_over - (poultry_hatching.quantity * percent_of_losses))
            all_left_over_ninty_percent += left_over_ninty_percent
            all_eleven_percent += eleven_percent
            farm_state = 'عادی'
            if poultry_hatching.violation == True:
                farm_state = 'متخلف'
                violation_count += 1
            violation_report_date = shamsi_date(
                poultry_hatching.violation_report_date.date()) if poultry_hatching.violation_report_date else '-'

            list1 = [
                m,
                state,
                farm_state,
            poultry_hatching.poultry.user.fullname,
            poultry_hatching.poultry.unit_name,
            poultry_hatching.poultry.user.mobile,
            poultry_hatching.poultry.user.city.name,
            poultry_hatching.poultry.breeding_unique_id,
            poultry_hatching.poultry.system_code,
            poultry_hatching.hall,
            poultry_hatching.period,
            str(create_date),
            str(date),
            poultry_hatching.chicken_breed,
            age,
            now_age,
            poultry_hatching.quantity,
            poultry_hatching.losses,
            poultry_hatching.direct_losses,
            poultry_hatching.total_losses,
            poultry_hatching.killed_quantity,
            poultry_hatching.total_killed_weight,
            poultry_hatching.left_over,
            left_over_ninty_percent,
            eleven_percent,
            poultry_hatching.total_commitment,
            poultry_hatching.governmental_quantity,
            poultry_hatching.governmental_killed_quantity,
            poultry_hatching.free_quantity,
            poultry_hatching.free_killed_quantity,
            str(poultry_hatching.total_average_killed_weight),
            creator,
            poultry_hatching.poultry.epidemiological_code if poultry_hatching.poultry.epidemiological_code else '-',
            poultry_hatching.out_province_killed_quantity if poultry_hatching.out_province_killed_quantity > 0 else '-',
            poultry_hatching.out_province_killed_weight if poultry_hatching.out_province_killed_weight > 0 else '-',
            reason,
            poultry_hatching.violation_reporter if poultry_hatching.violation_reporter else '-',
            poultry_hatching.violation_report if poultry_hatching.violation_report else '-',
                str(violation_report_date),
            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l, column=item + 1, value=list1[item])
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            if list1[2] == 'متخلف':
                cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
                )
        
        min_list = sorted(min_list)
        all_quantity = filtered_data.aggregate(total_quantity=Sum('quantity')).get('total_quantity', 0)
        all_losses = filtered_data.aggregate(total_quantity=Sum('losses')).get('total_quantity', 0)
        all_direct_losses = filtered_data.aggregate(total_quantity=Sum('direct_losses')).get('total_quantity', 0)
        all_total_losses = filtered_data.aggregate(total_quantity=Sum('total_losses')).get('total_quantity', 0)
        all_killed_quantity = filtered_data.aggregate(total_quantity=Sum('killed_quantity')).get('total_quantity', 0)
        all_left_over_total = filtered_data.aggregate(total_quantity=Sum('left_over')).get('total_quantity', 0)
        all_total_commitment = filtered_data.aggregate(total_quantity=Sum('total_commitment')).get('total_quantity', 0)
        all_governmental_killed_quantity = filtered_data.aggregate(total_quantity=Sum('governmental_killed_quantity')).get('total_quantity', 0)
        all_free_killed_quantity = filtered_data.aggregate(total_quantity=Sum('free_killed_quantity')).get('total_quantity', 0)
        all_total_killed_weight = filtered_data.aggregate(total_quantity=Sum('total_killed_weight')).get('total_quantity', 0)
        all_governmental_quantity = filtered_data.aggregate(total_quantity=Sum('governmental_quantity')).get('total_quantity', 0)
        all_free_quantity = filtered_data.aggregate(total_quantity=Sum('free_quantity')).get('total_quantity', 0)
        all_out_province_killed_quantity = filtered_data.aggregate(total_quantity=Sum('out_province_killed_quantity')).get('total_quantity', 0)
        all_out_province_killed_weight = filtered_data.aggregate(total_quantity=Sum('out_province_killed_weight')).get('total_quantity', 0)
        
        violation_count_in_filter = filtered_data.filter(violation=True).count()

        value_header_list = [
            len(filtered_data),
            len_hatch,
            len_archive_hatch,
            all_poultry_hatching_quantity,
            all_losses,
            all_direct_losses,
            all_total_losses,
            all_poultry_hatching_killed_quantity,
            all_total_killed_weight,
            all_poultry_hatching_left_over,
            left_over_archive,
            left_over_active,
            min_list[0] if len(min_list) > 0 else '-',
            min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
            all_total_commitment,
            all_governmental_quantity,
            all_governmental_killed_quantity,
            all_free_quantity,
            all_free_killed_quantity,
            all_out_province_killed_quantity,
            all_out_province_killed_weight,
            0 if is_archive else violation_count_in_filter,
            violation_count_in_filter if is_archive else 0
        ]
        for item in range(len(value_header_list)):
            cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
            value = value_header_list[item]
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'
            else:
                cell.value = value
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(size=10, bold=True)

        list2 = [
            'مجموع==>',
            '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
            all_quantity,
            all_losses,
            all_direct_losses,
            all_total_losses,
            all_killed_quantity,
            all_total_killed_weight,
            all_left_over_total,
        all_left_over_ninty_percent,
        all_eleven_percent,
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        '',
        '',
        '',
        all_out_province_killed_quantity,
            all_out_province_killed_weight,
            '', '', '', '',
        ]
        for item in range(len(list2)):
            cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
            value = list2[item]
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'
            else:
                cell.value = value
            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(bold=True)
            cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename=" جوجه ریزی های متخلف بین بازه سنی {min_age} تا {max_age}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def hatching_for_detail_killing_excel(request):
    filtered_poultry_hatch = PoultryHatching.objects.filter(trash=False,
                                                            left_over__gt=F('quantity') * percent_of_losses,
                                                            chicken_age__range=(55, 90)).select_related('poultry',
                                                                                                        'poultry__user').order_by(
        '-chicken_age')

    excel_options = [
        'ردیف',
        'وضعیت فارم فعال/بایگانی',
        'وضعیت فارم',
        'نام و خانوادگی',
        'نام فارم',
        'موبایل',
        'کد یکتا',
        'کد سیستمی واحد',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن',
        'تعداد جوجه ریزی',
        'تلفات دوره',
        'تعداد کشتار شده(قطعه)',
        'وزن کل کشتارشده(کیلوگرم)',
        'مانده در سالن',
        'مانده در سالن از نود درصد',
        'وزن تعهد دولتی(کیلوگرم)',
        'تعداد کشتار دولتی(قطعه)',
        'وزن کشتار دولتی(کیلوگرم)',
        'تعداد کشتار آزاد(قطعه)',
        'وزن کشتار آزاد(کیلوگرم)',
        'میانگین وزن کشتار(کیلوگرم)',
        'سازنده جوجه ریزی',
        'کد اپیدمیولوژیک',
        'تعداد کشتار خارج از استان(قطعه)',
        'وزن کشتار خارج از استان(کیلوگرم)',
    ]
    date1 = datetime.datetime.now().date()
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    header_list = [
        'تعداد فارم',
        'تعداد فارم فعال',
        'تعداد فارم بایگانی شده',
        'مجموع جوجه ریزی',
        'مجموع قطعه کشتار شده',
        'مجموع وزن  کشتارشده',
        'جمع کل مانده در سالن(قطعه)',
        'جمع مانده در سال فارم فعال(قطعه)',
        'جمع مانده در سالن فارم بایگانی(قطعه)',
        'کمترین سن ',
        'بیشترین سن ',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان',
        'تعداد فارم های فعال متخلف',
        'تعداد فارم های بایگانی متخلف',

    ]

    for col_num, option in enumerate(header_list, 5):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20

    # worksheet['A1'] = f' وضعیت پرونده ها'
    worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B2:C3'
    # merge_range2 = 'B2:C2'

    worksheet.merge_cells(merge_range1)
    # worksheet.merge_cells(merge_range2)
    worksheet['B2'].font = red_font

    # cell = worksheet.cell(row=1, column=1)
    # cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[6].height = 22
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 5
    m = 1
    all_poultry_hatching_quantity = 0
    all_poultry_hatching_killed_quantity = 0
    all_poultry_hatching_left_over = 0
    min_list = []
    all_left_over_ninty_percent = 0
    violation = 0
    len_archive_hatch = 0
    len_hatch = 0
    left_over_archive = 0
    left_over = 0
    for poultry_hatching in filtered_poultry_hatch:
        age = '-'
        if poultry_hatching.archive == True and poultry_hatching.allow_hatching == 'True':
            if poultry_hatching.last_change:
                date1 = datetime.datetime.strptime((poultry_hatching.last_change['date'].split(' ')[0]),
                                                   '%Y-%m-%d').date()
                age = (date1 - poultry_hatching.date.date()).days + 1
            len_archive_hatch += 1
            left_over_archive += poultry_hatching.left_over
            state = 'بایگانی'
        elif poultry_hatching.archive == False and poultry_hatching.allow_hatching == 'pending':
            age = (datetime.datetime.now().date() - poultry_hatching.date.date()).days + 1
            len_hatch += 1
            left_over += poultry_hatching.left_over
            state = "فعال"
        else:
            state = ''
        all_poultry_hatching_quantity += poultry_hatching.quantity
        all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity
        all_poultry_hatching_left_over += poultry_hatching.left_over
        if poultry_hatching.chicken_age not in min_list:
            min_list.append(poultry_hatching.chicken_age)

        l += 1
        create_date = jdatetime.date.fromgregorian(
            day=poultry_hatching.create_date.day,
            month=poultry_hatching.create_date.month,
            year=poultry_hatching.create_date.year
        )
        date = jdatetime.date.fromgregorian(
            day=poultry_hatching.date.day,
            month=poultry_hatching.date.month,
            year=poultry_hatching.date.year
        )

        creator = '-'
        if poultry_hatching.registrar:
            if poultry_hatching.registrar['fullname'] != '':
                creator = poultry_hatching.registrar['fullname']
        else:
            creator = 'پنجره واحد'
        left_over_ninty_percent = ((poultry_hatching.quantity * 90) / 100) - poultry_hatching.killed_quantity
        all_left_over_ninty_percent += left_over_ninty_percent
        farm_state = 'عادی'
        if poultry_hatching.violation == True:
            farm_state = 'پیگیری'
            violation += 1

        list1 = [
            m,
            state,
            farm_state,
            poultry_hatching.poultry.user.fullname,
            poultry_hatching.poultry.unit_name,
            poultry_hatching.poultry.user.mobile,
            poultry_hatching.poultry.breeding_unique_id,
            poultry_hatching.poultry.system_code,
            poultry_hatching.hall,
            poultry_hatching.period,
            str(create_date),
            str(date),
            poultry_hatching.chicken_breed,
            age,
            poultry_hatching.quantity,
            poultry_hatching.losses,
            poultry_hatching.killed_quantity,
            poultry_hatching.total_killed_weight,
            poultry_hatching.left_over,
            left_over_ninty_percent,
            poultry_hatching.total_commitment,
            poultry_hatching.governmental_quantity,
            poultry_hatching.governmental_killed_quantity,
            poultry_hatching.free_quantity,
            poultry_hatching.free_killed_quantity,
            str(poultry_hatching.total_average_killed_weight),
            creator,
            poultry_hatching.poultry.epidemiological_code if poultry_hatching.poultry.epidemiological_code else '-',
            poultry_hatching.out_province_killed_quantity if poultry_hatching.out_province_killed_quantity > 0 else '-',
            poultry_hatching.out_province_killed_weight if poultry_hatching.out_province_killed_weight > 0 else '-',
        ]
        m += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            if list1[2] == 'متخلف':
                cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
            cell.alignment = Alignment(horizontal='center')
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
    min_list = sorted(min_list)
    all_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('losses')).get(
        'total_quantity', 0)
    all_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get(
        'total_quantity', 0)
    all_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get(
        'total_quantity', 0)
    all_total_commitment = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_commitment')).get(
        'total_quantity', 0)
    all_governmental_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('governmental_killed_quantity')).get(
        'total_quantity', 0)
    all_free_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('free_killed_quantity')).get(
        'total_quantity', 0)
    all_total_killed_weight = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('total_killed_weight')).get(
        'total_quantity', 0)
    all_governmental_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('governmental_quantity')).get(
        'total_quantity', 0)
    all_free_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('free_quantity')).get(
        'total_quantity', 0)
    all_out_province_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('out_province_killed_quantity')).get(
        'total_quantity', 0)
    all_out_province_killed_weight = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('out_province_killed_weight')).get(
        'total_quantity', 0)
    violation_archive = len(filtered_poultry_hatch.filter(violation=True, archive=True, allow_hatching='True'))
    violation_active = len(
        filtered_poultry_hatch.filter(violation=True, archive=False, allow_hatching='pending'))
    value_header_list = [
        len(filtered_poultry_hatch),
        len_hatch,
        len_archive_hatch,
        all_poultry_hatching_quantity,
        all_poultry_hatching_killed_quantity,
        all_total_killed_weight,
        all_poultry_hatching_left_over,
        left_over_archive,
        left_over,
        min_list[0] if len(min_list) > 0 else '-',
        min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        all_out_province_killed_quantity,
        all_out_province_killed_weight,
        violation_active,
        violation_archive
    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)

    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_quantity,
        all_losses,
        all_killed_quantity,
        all_total_killed_weight,
        all_left_over,
        all_left_over_ninty_percent,
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        '',
        '',
        '',
        all_out_province_killed_quantity,
        all_out_province_killed_weight,

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="فارم های متخلف بین 55تا 90 روز.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False,
                                                         kill_request__recive_date__date__gte=date1,
                                                         kill_request__recive_date__date__lte=date2,
                                                         province_request__poultry_request__freezing=True).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name', 'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای ایجاد شده در فرآیند کشتار مرغ گوشتی منجمد'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارها(پشتیبانی امور دام).xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def successful_transactions_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if "date1" in request.GET else now
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if "date2" in request.GET else now
    if 'key' in request.GET:
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        transactions = ExternalTransaction.objects.filter(
            date__date__gte=date1,
            date__date__lte=date2,
            kill_house_user=user,
            status='completed',
            transaction_type='wage-gateway',
            trash=False).order_by('id')
    else:
        transactions = ExternalTransaction.objects.filter(
            date__date__gte=date1,
            date__date__lte=date2,
            status='completed',
            transaction_type='wage-gateway',
            trash=False).order_by('id')

    excel_options = [
        'ردیف',
        'تاریخ و زمان',
        'پرداخت کننده',
        'تعداد سفارشات',
        'تعداد کل(قطعه)',
        'وزن کل(کیلوگرم)',
        'شماره درخواست',
        'شماره پیگیری',
        'کد سفارش',
        'شماره کارت',
        'قیمت(ریال)',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    for transaction in transactions:
        total_weight = 0
        total_quantity = 0
        total_request = 0
        wage_payment = WagePayment.objects.filter(
            Q(orderId=transaction.orderId) | Q(tracking_code=transaction.saleReferenceId),
            trash=False).first()
        if wage_payment.province_kill_request != None:
            total_request = len(wage_payment.province_kill_request)
            for province_kill_req in wage_payment.province_kill_request:
                province_kill = ProvinceKillRequest.objects.get(key=province_kill_req, trash=False)
                total_weight += province_kill.total_killed_weight
                total_quantity += province_kill.total_killed_quantity
        date = transaction.date
        date_create = convert_to_shamsi(datetime=date)
        list1 = [
            m,
            str(date_create),
            transaction.payer,
            total_request,
            total_quantity,
            total_weight,
            str(transaction.refId) if transaction.refId != None else '-',
            str(transaction.saleReferenceId) if transaction.saleReferenceId != None else '-',
            str(transaction.orderId) if transaction.orderId != None else '-',
            str(transaction.cardHolderPan) if transaction.cardHolderPan != None else '-',
            transaction.amount
        ]
        m += 1
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values

            worksheet.row_dimensions[l + 1].height = 29
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="تراکنش های موفق.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def unsuccessful_transactions_excel(request):
    now = datetime.datetime.now().date()
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date() if "date1" in request.GET else now
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date() if "date2" in request.GET else now
    if 'key' in request.GET:
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        transactions = ExternalTransaction.objects.filter(
            date__date__gte=date1,
            date__date__lte=date2,
            kill_house_user=user,
            status='failed',
            transaction_type='wage-gateway',
            trash=False).order_by('id')
    else:
        transactions = ExternalTransaction.objects.filter(
            date__date__gte=date1,
            date__date__lte=date2,
            status='failed',
            transaction_type='wage-gateway',
            trash=False).order_by('id')

    excel_options = [
        'ردیف',
        'تاریخ و زمان',
        'پرداخت کننده',
        'تعداد سفارشات',
        'تعداد کل(قطعه)',
        'وزن کل(کیلوگرم)',
        'شماره درخواست',
        'شماره پیگیری',
        'کد سفارش',
        'شماره کارت',
        'قیمت(ریال)',
        'متن خطا',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    for transaction in transactions:
        total_weight = 0
        total_quantity = 0
        total_request = 0
        wage_payment = WagePayment.objects.filter(
            Q(orderId=transaction.orderId) | Q(tracking_code=transaction.saleReferenceId),
            trash=False).first()
        if wage_payment.province_kill_request != None:
            total_request = len(wage_payment.province_kill_request)
            for province_kill_req in wage_payment.province_kill_request:
                province_kill = ProvinceKillRequest.objects.get(key=province_kill_req, trash=False)
                total_weight += province_kill.total_killed_weight
                total_quantity += province_kill.total_killed_quantity
        date = transaction.date
        date_create = convert_to_shamsi(datetime=date)
        message = transaction.message
        if message == 'ﻛﺎرﺑﺮ_از_اﻧﺠﺎم_ﺗﺮاﻛﻨﺶ_ﻣﻨﺼﺮف_ﺷﺪه_اﺳﺖ':
            message = 'ﻛﺎرﺑﺮ از اﻧﺠﺎم ﺗﺮاﻛﻨﺶ ﻣﻨﺼﺮف ﺷﺪه اﺳﺖ'

        list1 = [
            m,
            str(date_create),
            transaction.payer,
            total_request,
            total_quantity,
            total_weight,
            str(transaction.refId) if transaction.refId != None else '-',
            str(transaction.saleReferenceId) if transaction.saleReferenceId != None else '-',
            str(transaction.orderId) if transaction.orderId != None else '-',
            str(transaction.cardHolderPan) if transaction.cardHolderPan != None else '-',
            transaction.amount,
            message
        ]
        m += 1
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values

            worksheet.row_dimensions[l + 1].height = 29
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="تراکنش های ناموفق.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def poultry_hatching_between_50age_70age_excel(request):
    filtered_poultry_hatch = PoultryHatching.objects.filter(trash=False, left_over__gt=F('quantity') * 0.1,
                                                            chicken_age__range=(55, 90)).order_by('id')

    excel_options = [
        'ردیف',
        'وضعیت فارم',
        'نام و خانوادگی',
        'نام فارم',
        'موبایل',
        'کد یکتا',
        'کد سیستمی واحد',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن',
        'تعداد جوجه ریزی',
        'تلفات دوره',
        'تعداد کشتار شده(قطعه)',
        'وزن کل کشتارشده(کیلوگرم)',
        'مانده در سالن',
        'نود درصد جوجه ریزی',
        'وزن تعهد دولتی(کیلوگرم)',
        'تعداد کشتار دولتی(قطعه)',
        'وزن کشتار دولتی(کیلوگرم)',
        'تعداد کشتار آزاد(قطعه)',
        'وزن کشتار آزاد(کیلوگرم)',
        'میانگین وزن کشتار(کیلوگرم)',
        'سازنده جوجه ریزی',
        'کد اپیدمیولوژیک',
        'تعداد کشتار خارج از استان(قطعه)',
        'وزن کشتار خارج از استان(کیلوگرم)',
    ]
    date1 = datetime.datetime.now().date()
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    header_list = [
        'تعداد فارم فعال',
        'مجموع جوجه ریزی',
        'مجموع قطعه کشتار شده',
        'مجموع وزن کل کشتارشده',
        'مانده در سالن(قطعه)',
        'مانده در سالن از نود درصد(قطعه)',
        'کمترین سن',
        'بیشترین سن',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان',
        'تعداد فارم های متخلف',

    ]

    for col_num, option in enumerate(header_list, 5):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20

    # worksheet['A1'] = f' وضعیت پرونده ها'
    worksheet['B2'] = f'این گزارش در مورخ {from_date_1} صادر شده است.'

    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B2:C3'
    # merge_range2 = 'B2:C2'

    worksheet.merge_cells(merge_range1)
    # worksheet.merge_cells(merge_range2)
    worksheet['B2'].font = red_font

    # cell = worksheet.cell(row=1, column=1)
    # cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[6].height = 22
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 5
    m = 1
    all_poultry_hatching_quantity = 0
    all_poultry_hatching_killed_quantity = 0
    all_poultry_hatching_left_over = 0
    min_list = []
    all_left_over_ninty_percent = 0
    violation = 0
    for poultry_hatching in filtered_poultry_hatch:
        all_poultry_hatching_quantity += poultry_hatching.quantity
        all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity
        all_poultry_hatching_left_over += poultry_hatching.left_over
        if poultry_hatching.chicken_age not in min_list:
            min_list.append(poultry_hatching.chicken_age)

        l += 1
        create_date = jdatetime.date.fromgregorian(
            day=poultry_hatching.create_date.day,
            month=poultry_hatching.create_date.month,
            year=poultry_hatching.create_date.year
        )
        date = jdatetime.date.fromgregorian(
            day=poultry_hatching.date.day,
            month=poultry_hatching.date.month,
            year=poultry_hatching.date.year
        )
        date1 = datetime.datetime.strptime(str(poultry_hatching.date), '%Y-%m-%d %H:%M:%S')
        age = (datetime.datetime.now() - date1).days + 1

        creator = '-'
        if poultry_hatching.registrar:
            if poultry_hatching.registrar['fullname'] != '':
                creator = poultry_hatching.registrar['fullname']
        else:
            creator = 'پنجره واحد'
        left_over_ninty_percent = ((poultry_hatching.quantity * 90) / 100)
        all_left_over_ninty_percent += left_over_ninty_percent
        farm_state = 'عادی'
        if poultry_hatching.violation == True:
            farm_state = 'متخلف'
            violation += 1

        list1 = [
            m,
            farm_state,
            poultry_hatching.poultry.user.fullname,
            poultry_hatching.poultry.unit_name,
            poultry_hatching.poultry.user.mobile,
            poultry_hatching.poultry.breeding_unique_id,
            poultry_hatching.poultry.system_code,
            poultry_hatching.hall,
            poultry_hatching.period,
            str(create_date),
            str(date),
            poultry_hatching.chicken_breed,
            age,
            poultry_hatching.quantity,
            poultry_hatching.losses,
            poultry_hatching.killed_quantity,
            poultry_hatching.total_killed_weight,
            poultry_hatching.left_over,
            left_over_ninty_percent,
            poultry_hatching.total_commitment,
            poultry_hatching.governmental_quantity,
            poultry_hatching.governmental_killed_quantity,
            poultry_hatching.free_quantity,
            poultry_hatching.free_killed_quantity,
            str(poultry_hatching.total_average_killed_weight),
            creator,
            poultry_hatching.poultry.epidemiological_code if poultry_hatching.poultry.epidemiological_code else '-',
            poultry_hatching.out_province_killed_quantity if poultry_hatching.out_province_killed_quantity > 0 else '-',
            poultry_hatching.out_province_killed_weight if poultry_hatching.out_province_killed_weight > 0 else '-',
        ]
        m += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            value = list1[item]
            # Check if the value is a number before formatting
            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            if list1[1] == 'متخلف':
                cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
            cell.alignment = Alignment(horizontal='center')
    min_list = sorted(min_list)
    all_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('losses')).get(
        'total_quantity', 0)
    all_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get(
        'total_quantity', 0)
    all_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get(
        'total_quantity', 0)
    all_total_commitment = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_commitment')).get(
        'total_quantity', 0)
    all_governmental_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('governmental_killed_quantity')).get(
        'total_quantity', 0)
    all_free_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('free_killed_quantity')).get(
        'total_quantity', 0)
    all_total_killed_weight = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('total_killed_weight')).get(
        'total_quantity', 0)
    all_governmental_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('governmental_quantity')).get(
        'total_quantity', 0)
    all_free_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('free_quantity')).get(
        'total_quantity', 0)
    all_out_province_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('out_province_killed_quantity')).get(
        'total_quantity', 0)
    all_out_province_killed_weight = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('out_province_killed_weight')).get(
        'total_quantity', 0)
    value_header_list = [
        len(filtered_poultry_hatch),
        all_poultry_hatching_quantity,
        all_poultry_hatching_killed_quantity,
        all_total_killed_weight,
        all_poultry_hatching_left_over,
        all_left_over_ninty_percent,
        min_list[0] if len(min_list) > 0 else '-',
        min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        all_out_province_killed_quantity,
        all_out_province_killed_weight,
        violation
    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)

    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_quantity,
        all_losses,
        all_killed_quantity,
        all_total_killed_weight,
        all_left_over,
        all_left_over_ninty_percent,
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        '',
        '',
        '',
        all_out_province_killed_quantity,
        all_out_province_killed_weight,

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش کلی فارم های فعال مرغ گوشتی دارای مانده در سالن بیشتر از 10 درصد و بازه سنی 55 تا 90 روزه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False,
                                                         kill_request__recive_date__date__gte=date1,
                                                         kill_request__recive_date__date__lte=date2,
                                                         clearance_code__isnull=False).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای دارای کد قرنطینه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای دارای کد قرنطینه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False,
                                                         kill_request__recive_date__date__gte=date1,
                                                         kill_request__recive_date__date__lte=date2,
                                                         quarantine_quantity__isnull=False).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای احراز شده از قرنطینه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای احراز شده از قرنطینه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(trash=False,
                                                         kill_request__recive_date__date__gte=date1,
                                                         kill_request__recive_date__date__lte=date2,
                                                         clearance_code__isnull=True).order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای فاقد کد قرنطینه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای فاقد کد قرنطینه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity')), 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهایی که در قرنطینه و رصدیار اختلاف دارند'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهایی که در قرنطینه و تعاون اختلاف دارند.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        province_request__poultry_request__free_sale_in_province=False, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بار دولتی'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بار دولتی.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        province_request__poultry_request__free_sale_in_province=False, quarantine_quantity__isnull=False, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بار دولتی دارای کد قرنطینه احراز شده'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بار دولتی دارای کد قرنطینه احراز شده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        province_request__poultry_request__free_sale_in_province=True, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای آزاد'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای آزاد.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        province_request__poultry_request__free_sale_in_province=True, quarantine_quantity__isnull=False, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای آزاد احراز شده از قرنطینه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای آزاد احراز شده از قرنطینه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        province_request__poultry_request__free_sale_in_province=True, clearance_code__isnull=False, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای آزاد دارای کد قرنطینه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای آزاد دارای کد قرنطینه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    poultry_requests = (PoultryRequest.objects.filter(trash=False, out=True, province_state='accepted',
                                                      out_province_request_cancel=False
                                                      , send_date__date__gte=date1
                                                      , send_date__date__lte=date2).order_by(
        '-send_date').select_related('poultry', 'poultry__user', 'hatching'))

    poultry_requests_accepted = poultry_requests.filter(province_state='accepted')

    excel_options = [
        'ردیف',
        'کدسفارش مرغدار',
        ' تاریخ ثبت درخواست',
        ' تاریخ کشتار',
        ' کشتار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        ' استان مرغدار',
        'سن مرغ',
        ' نژاد',
        'تعداد درخواست',
        'میانگین وزنی',
        'وزن درخواست',
        'مانده در سالن',
        'جوجه ریزی اولیه',

        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' شهر خریدار',
        ' استان خریدار',

        'نوع خودرو',
        'پلاک',

        'نام راننده',
        'موبایل راننده',
        'کد بهداشتی حمل و نقل',

        'کد رهگیری سامانه قرنطینه',
        'ثبت کننده کد قرنطینه',
        'تاریخ ثبت  کد قرنطینه',
        'وضعیت',
        'سازنده',

    ]

    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای تایید شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'کمترین سن مرغ',
        'بیشترین سن مرغ',
        'تعداد بارهای دارای کد قرنطینه',

    ]
    for col_num, option in enumerate(header_list, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای خارج از استان'
    if poultry_requests.exists():
        name = poultry_requests.first().poultry.user.province.name
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 6
    m = 1

    all_weighte = 0
    all_chicken_quantity = 0
    all_age = []
    all_quantity = poultry_requests_accepted.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)

    all_weighte = poultry_requests_accepted.aggregate(
        total=Sum(F('quantity') * F('Index_weight')))[
        'total']

    has_code = 0
    if poultry_requests:
        for poultry_request in poultry_requests:
            age = (poultry_request.send_date.date() - poultry_request.hatching.date.date()).days + 1
            all_age.append(age)
            all_chicken_quantity += poultry_request.hatching.quantity
            create_date_of_poultry_request = jdatetime.date.fromgregorian(
                day=poultry_request.create_date.day,
                month=poultry_request.create_date.month,
                year=poultry_request.create_date.year
            )
            date_of_kill_request = jdatetime.date.fromgregorian(
                day=poultry_request.send_date.day,
                month=poultry_request.send_date.month,
                year=poultry_request.send_date.year
            )
            if poultry_request.quarantine_code_registrar is not None:
                date_code = poultry_request.quarantine_code_registrar['date'].split('-')

                date_of_create_code = jdatetime.date.fromgregorian(
                    day=int(date_code[2]),
                    month=int(date_code[1]),
                    year=int(date_code[0])
                )
                full_name = poultry_request.quarantine_code_registrar['fullname']
                mobile = poultry_request.quarantine_code_registrar['mobile']
            else:
                date_of_create_code = '-'
                full_name = '-'
                mobile = '-'
            is_killer = 'کشتارگاه' if poultry_request.buyer is not None and poultry_request.buyer[
                'buyerType'] == 'killhouse' else 'کشتارکن'
            if poultry_request.quarantine_code:
                code = poultry_request.quarantine_code
                has_code += 1
            else:
                code = '-'

            if poultry_request.province_state == 'pending':
                state = 'در انتظار تایید'
            elif poultry_request.province_state == 'accepted':
                state = 'تایید شده'
            else:
                state = 'حذف شده'
            freez_state = 'منجمد' if poultry_request.freezing == True else 'عادی'
            list1 = [
                m,
                str(poultry_request.order_code),
                str(create_date_of_poultry_request),
                str(date_of_kill_request),
                freez_state,
                poultry_request.poultry.user.fullname,
                poultry_request.poultry.user.mobile,
                poultry_request.poultry.user.city.name,
                poultry_request.poultry.user.province.name,
                age,
                poultry_request.hatching.chicken_breed,
                poultry_request.quantity,
                poultry_request.Index_weight,
                int(poultry_request.quantity * poultry_request.Index_weight),
                poultry_request.hatching.left_over,
                poultry_request.hatching.quantity,
                is_killer,
                poultry_request.buyer['firstName'],
                poultry_request.buyer['mobile'],
                poultry_request.buyer['city'],
                poultry_request.buyer['province'],
                poultry_request.out_province_driver_info['driverCar'],
                poultry_request.out_province_driver_info['driverPelak'],
                poultry_request.out_province_driver_info['driverName'],
                poultry_request.out_province_driver_info['driverMobile'],
                poultry_request.out_province_driver_info['driverhealthCode'],
                code,
                full_name + '(' + mobile + ')',
                str(date_of_create_code),
                state,
                poultry_request.registrar['fullname'] if poultry_request.registrar else '-'
            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')
            l += 1

    # last_age=sorted(reversed(all_age))
    all_age = sorted(all_age)
    value_header_list2 = [
        len(poultry_requests_accepted),
        all_quantity if all_quantity != None else 0,
        all_weighte if all_weighte != None else 0,
        all_age[0] if len(all_age) > 0 else None,
        all_age[len(all_age) - 1] if len(all_age) > 0 else None,
        has_code,

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_quantity if all_quantity != None else 0,
        '',
        all_weighte,
        '',
        all_chicken_quantity,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="بار های خارج از استان.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        ware_house_confirmation=True, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش  بارهای ورودی به کشتارگاه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت  بارهای ورودی به کشتارگاه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        vet_state='accepted', 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش  بارهای تخلیه شده دامپزشک'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت  تخلیه شده دامپزشک.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        assignment_state_archive='True', 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش  بارهای تکمیل شده کشتارگاه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تکمیل شده کشتارگاه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        Q(assignment_state_archive='True', vet_state='pending')
        | Q(vet_state='accepted'), clearance_code__isnull=True, 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای تخلیه شده فاقد کد قرنطینه '

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تخلیه شده فاقد کد قرنطینه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        assignment_state_archive='pending', vet_state='pending', 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای تخلیه نشده'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تخلیه نشده.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        assignment_state_archive='pending'
        , vet_state='accepted', 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__poultry__user',
        'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name',
                                              'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values(
        'province_request__poultry_request__freezing',
        'province_request__poultry_request',
        'killhouse_user',
        'killhouse_user__name',
        'killhouse_user__kill_house_operator__user__mobile',
        'killhouse_user__system_address__city__name',
        'killhouse_user__killer',
        'kill_request__slaughter_house',
        'kill_request__slaughter_house__name',
        'province_request__poultry_request__poultry',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__chicken_breed',
        'province_request__poultry_request__poultry__user__city__name',
        'province_request__poultry_request__poultry__unit_name',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__send_date',
        'add_car__driver__driver_name',
        'add_car__driver__driver_mobile',
        'add_car__driver__type_car',
        'add_car__driver__health_code',
        'key',
        'province_kill_request__province_request__poultry_request__Index_weight',
        'clearance_code',
        'quantity',
        'bar_code',
        'accepted_real_weight',
        'accepted_real_quantity',
        'vet_state',
        'vet_accepted_real_quantity',
        'vet_accepted_real_weight',
        'quarantine_quantity',
        'killhouse_user__kill_house_operator__user__province__name',
        'province_request__poultry_request__hatching__chicken_age',
        'province_request__poultry_request__amount',
        'assignment_state_archive',
        'traffic_code',
        'province_kill_request__province_request__poultry_request__free_sale_in_province',
        'province_kill_request__province_request__poultry_request__union',
        'province_kill_request__province_request__poultry_request__direct_buying',
        'quarantine_code_state',
        'province_request__poultry_request__send_date', 'province_request__poultry_request__hatching__date'
    )
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای تخلیه شده و عدم تکمیل توسط کشتارگاه'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] != None else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] != None else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تخلیه شده و عدم تکمیل توسط کشتارگاه.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def hatching_date_range_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    filtered_poultry_hatch = PoultryHatching.objects.filter(date__date__gte=date1, date__date__lte=date2, archive=False,
                                                            allow_hatching='pending',
                                                            trash=False).select_related('poultry',
                                                                                        'poultry__user').order_by(
        '-chicken_age')

    excel_options = [
        'ردیف',
        'وضعیت فارم',
        'نام و خانوادگی',
        'نام فارم',
        'موبایل',
        'کد یکتا',
        'کد سیستمی واحد',
        'سالن',
        ' دوره جوجه ریزی',
        'تاریخ ثبت جوجه ریزی',
        'تاریخ جوجه ریزی',
        'نژاد',
        'سن',
        'تعداد جوجه ریزی',
        'تلفات دامپزشک(قطعه)',
        'تلفات اتحادیه(قطعه)',
        'تلفات کل(قطعه)',
        'تعداد کشتار شده(قطعه)',
        'وزن کل کشتارشده(کیلوگرم)',
        'مانده در سالن',
        'نود درصد جوجه ریزی',
        'وزن تعهد دولتی(کیلوگرم)',
        'تعداد کشتار دولتی(قطعه)',
        'وزن کشتار دولتی(کیلوگرم)',
        'تعداد کشتار آزاد(قطعه)',
        'وزن کشتار آزاد(کیلوگرم)',
        'میانگین وزن کشتار(کیلوگرم)',
        'سازنده جوجه ریزی',
        'کد اپیدمیولوژیک',
        'تعداد کشتار خارج از استان(قطعه)',
        'وزن کشتار خارج از استان(کیلوگرم)',
        'ثبت کننده گزارش',
        'متن گزارش',
        'تاریخ گزارش',
    ]

    from_date_1 = shamsi_date(date1)
    from_date_2 = shamsi_date(date2)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')

    header_list = [
        'تعداد فارم فعال',
        'تعداد فارم دارای زنجیره فعال',
        'مجموع جوجه ریزی',
        'مجموع تلفات دامپزشک(قطعه)',
        'مجموع تلفات اتحادیه(قطعه)',
        'مجموع تلفات کل(قطعه)',
        'مجموع قطعه کشتار شده',
        'مجموع وزن کل کشتارشده',
        'مانده در سالن(قطعه)',
        'مانده در سالن از نود درصد(قطعه)',
        'کمترین سن',
        'بیشترین سن',
        'مجموع وزن تعهد دولتی',
        ' مجموع قطعه کشتار دولتی',
        ' مجموع وزن کشتار دولتی',
        ' مجموع قطعه کشتار آزاد',
        ' مجموع وزن کشتار آزاد',
        'مجموع تعداد کشتار خارج از استان',
        'مجموع وزن کشتار خارج از استان',
        'تعداد فارم های متخلف',
        'تعداد بار ایجاد شده',
        'حجم بار ایجاد شده',
        'وزن بار ایجاد شده',
        'تعداد بار کشتار شده',
        'حجم بار کشتار شده',
        'وزن بار کشتار شده',
        'تعداد بار ورودی به انبار',
        'حجم لاشه ها',
        'وزن لاشه ها',
        'درصد افت بارها',

    ]

    create_header(worksheet, header_list, 5, 2, height=20)

    excel_description(worksheet, 'B1', f'جوجه ریزی های فعال از تاریخ {from_date_1} تا {from_date_2}', color='red',
                      row2='C3')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)

    kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                          province_request__poultry_request__hatching__in=filtered_poultry_hatch)

    first_quantity = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity') or 0
    first_weight = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity') or 0

    ware_house_bars = kill_house_requests.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 = kill_house_requests.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

    l = 5
    m = 1
    all_poultry_hatching_quantity = 0
    all_poultry_hatching_killed_quantity = 0
    all_poultry_hatching_left_over = 0
    min_list = []
    all_left_over_ninty_percent = 0
    violation = 0
    all_chain_company = 0
    for poultry_hatching in filtered_poultry_hatch:
        all_poultry_hatching_quantity += poultry_hatching.quantity
        all_poultry_hatching_killed_quantity += poultry_hatching.killed_quantity
        all_poultry_hatching_left_over += poultry_hatching.left_over
        if poultry_hatching.chicken_age not in min_list:
            min_list.append(poultry_hatching.chicken_age)

        l += 1
        create_date = jdatetime.date.fromgregorian(
            day=poultry_hatching.create_date.day,
            month=poultry_hatching.create_date.month,
            year=poultry_hatching.create_date.year
        )
        date = jdatetime.date.fromgregorian(
            day=poultry_hatching.date.day,
            month=poultry_hatching.date.month,
            year=poultry_hatching.date.year
        )
        date1 = datetime.datetime.strptime(str(poultry_hatching.date), '%Y-%m-%d %H:%M:%S')
        age = poultry_hatching.chicken_age

        creator = '-'
        if poultry_hatching.registrar:
            if poultry_hatching.registrar['fullname'] != '':
                creator = poultry_hatching.registrar['fullname']
        else:
            creator = 'پنجره واحد'
        left_over_ninty_percent = ((poultry_hatching.quantity * 90) / 100)
        all_left_over_ninty_percent += left_over_ninty_percent
        farm_state = 'عادی'
        if poultry_hatching.violation == True:
            farm_state = 'متخلف' + ' ' + '(وجود فارم فعال دیگر)'
            violation += 1
        if poultry_hatching.chain_company:
            chain_company = poultry_hatching.chain_company.name
            all_chain_company += 1
        else:
            chain_company = '-'

        kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                              province_request__poultry_request__hatching=poultry_hatching)

        first_quantity = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
            'total_quantity') or 0
        first_weight = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_weight')).get(
            'total_quantity') or 0

        ware_house_bars = kill_house_requests.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 = kill_house_requests.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
        violation_report_date = shamsi_date(
            poultry_hatching.violation_report_date.date()) if poultry_hatching.violation_report_date else '-'

        list1 = [
            m,
            farm_state,
            poultry_hatching.poultry.user.fullname,
            poultry_hatching.poultry.unit_name,
            poultry_hatching.poultry.user.mobile,
            poultry_hatching.poultry.breeding_unique_id,
            poultry_hatching.poultry.system_code,
            poultry_hatching.hall,
            poultry_hatching.period,
            str(create_date),
            str(date),
            poultry_hatching.chicken_breed,
            age,
            poultry_hatching.quantity,
            poultry_hatching.losses,
            poultry_hatching.direct_losses,
            poultry_hatching.total_losses,
            poultry_hatching.killed_quantity,
            poultry_hatching.total_killed_weight,
            poultry_hatching.left_over,
            left_over_ninty_percent,
            poultry_hatching.total_commitment,
            poultry_hatching.governmental_quantity,
            poultry_hatching.governmental_killed_quantity,
            poultry_hatching.free_quantity,
            poultry_hatching.free_killed_quantity,
            str(poultry_hatching.total_average_killed_weight),
            creator,
            poultry_hatching.poultry.epidemiological_code if poultry_hatching.poultry.epidemiological_code else '-',
            poultry_hatching.out_province_killed_quantity if poultry_hatching.out_province_killed_quantity > 0 else '-',
            poultry_hatching.out_province_killed_weight if poultry_hatching.out_province_killed_weight > 0 else '-',

            poultry_hatching.violation_reporter if poultry_hatching.violation_reporter else '-',
            poultry_hatching.violation_report if poultry_hatching.violation_report else '-',
            str(violation_report_date),

        ]
        m += 1
        create_value(worksheet, list1, l + 1, 1, border_style='thin', different_cell=1,
                     different_value='متخلف' + ' ' + '(وجود فارم فعال دیگر)')

    min_list = sorted(min_list)
    all_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('losses')).get(
        'total_quantity', 0)
    all_direct_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('direct_losses')).get(
        'total_quantity', 0)
    all_total_losses = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_losses')).get(
        'total_quantity', 0)
    all_killed_quantity = filtered_poultry_hatch.aggregate(total_quantity=Sum('killed_quantity')).get(
        'total_quantity', 0)
    all_left_over = filtered_poultry_hatch.aggregate(total_quantity=Sum('left_over')).get(
        'total_quantity', 0)
    all_total_commitment = filtered_poultry_hatch.aggregate(total_quantity=Sum('total_commitment')).get(
        'total_quantity', 0)
    all_governmental_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('governmental_killed_quantity')).get(
        'total_quantity', 0)
    all_free_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('free_killed_quantity')).get(
        'total_quantity', 0)
    all_total_killed_weight = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('total_killed_weight')).get(
        'total_quantity', 0)
    all_governmental_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('governmental_quantity')).get(
        'total_quantity', 0)
    all_free_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('free_quantity')).get(
        'total_quantity', 0)
    all_out_province_killed_quantity = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('out_province_killed_quantity')).get(
        'total_quantity', 0)
    all_out_province_killed_weight = filtered_poultry_hatch.aggregate(
        total_quantity=Sum('out_province_killed_weight')).get(
        'total_quantity', 0)

    kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                          province_request__poultry_request__hatching__in=filtered_poultry_hatch)

    first_quantity = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity') or 0
    first_weight = kill_house_requests.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity') or 0

    ware_house_bars = kill_house_requests.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 = kill_house_requests.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
    value_header_list = [
        len(filtered_poultry_hatch),
        all_chain_company,
        all_poultry_hatching_quantity,
        all_losses,
        all_direct_losses,
        all_total_losses,
        all_poultry_hatching_killed_quantity,
        all_total_killed_weight,
        all_poultry_hatching_left_over,
        all_left_over_ninty_percent,
        min_list[0] if len(min_list) > 0 else '-',
        min_list[len(min_list) - 1] if len(min_list) > 0 else '-',
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        all_out_province_killed_quantity,
        all_out_province_killed_weight,
        violation,
        len(kill_house_requests),
        first_quantity,
        first_weight,
        len(bar_complete_with_kill_house),
        accepted_real_quantity_final,
        accepted_real_wight_final,
        len(ware_house_bars),
        ware_house_bars_quantity,
        ware_house_bars_weight,
        str(round(ware_house_bars_weight_lose / len(
            ware_house_bars), 2) if ware_house_bars else 0)
    ]
    create_value(worksheet, value_header_list, 3, 5)

    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_quantity,
        all_losses,
        all_direct_losses,
        all_total_losses,
        all_killed_quantity,
        all_total_killed_weight,
        all_left_over,
        all_left_over_ninty_percent,
        all_total_commitment,
        all_governmental_quantity,
        all_governmental_killed_quantity,
        all_free_quantity,
        all_free_killed_quantity,
        '',
        '',
        '',
        all_out_province_killed_quantity,
        all_out_province_killed_weight,
        '',
        '',
        '',

    ]
    create_value(worksheet, list2, l + 3, 1, color='green')
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="جوجه ریزی در بازه تاریخی.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def wallete_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    user = SystemUserProfile.objects.get(key=request.GET['key'])
    transactions = ExternalTransaction.objects.filter(type__isnull=False,
                                                      date__date__gte=date1,
                                                      date__date__lte=date2,
                                                      kill_house_user=user,
                                                      status__in=('completed', 'failed'),
                                                      transaction_type='wallet',
                                                      trash=False).order_by('id')

    excel_options = [
        'ردیف',
        'وضعیت پرداختی',
        'تاریخ و زمان',
        'پرداخت کننده',
        'شماره درخواست',
        'شماره پیگیری',
        'کدسفارش',
        'شماره کارت',
        'مبلغ',
        'متن خطا',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    from_date2 = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date2.split("-"))
    separate = "-"
    from_date_2 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    header_list = [
        'تعداد تراکنش ها',
        'تعداد تراکنش های موفق',
        'مبلغ تراکنش های موفق',
        'تعداد تراکنش های ناموفق',
        'مبلغ تراکنش های ناموفق',

    ]

    for col_num, option in enumerate(header_list, 5):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20

    worksheet['B2'] = f'گزارش کیف پول کشتارگاه از تاریخ {from_date_1} تا {from_date_2}'

    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    merge_range1 = 'B2:D3'
    worksheet.merge_cells(merge_range1)
    worksheet['B2'].font = red_font

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 20.01
        worksheet.row_dimensions[6].height = 22
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str

    l = 5
    m = 1

    for transaction in transactions:
        l += 1
        state = 'موفق' if transaction.status == 'completed' else 'ناموفق'
        date = convert_to_shamsi(
            datetime=transaction.date
        )
        list1 = [
            m,
            state,
            date,
            transaction.payer,
            transaction.orderId,
            transaction.saleReferenceId if transaction.saleReferenceId is not None else '-',
            transaction.orderId,
            transaction.cardHolderPan if transaction.cardHolderPan is not None else '-',
            transaction.amount,
            transaction.message if transaction.message is not None else '-',

        ]
        m += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            value = list1[item]
            # Check if the value is a number before formatting

            if isinstance(value, (int, float)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            if list1[1] == 'ناموفق':
                cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            cell.border = openpyxl.styles.Border(
                left=openpyxl.styles.Side(style='thin'),
                right=openpyxl.styles.Side(style='thin'),
                top=openpyxl.styles.Side(style='thin'),
                bottom=openpyxl.styles.Side(style='thin')
            )
    complete_trans = transactions.filter(status='completed')
    complete_trans_amount = complete_trans.aggregate(
        total_quantity=Sum('amount')).get(
        'total_quantity') or 0
    failed_trans = transactions.filter(status='failed')
    failed_trans_amount = failed_trans.aggregate(
        total_quantity=Sum('amount')).get(
        'total_quantity') or 0
    value_header_list = [
        m - 1,
        len(complete_trans),
        complete_trans_amount,
        len(failed_trans),
        failed_trans_amount,

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 5, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)

    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="گزارش کیف پول.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_request_suspended_load_excel(request):
    date1 = datetime.datetime.strptime(str(request.GET['start']), '%Y-%m-%d').date()
    date2 = datetime.datetime.strptime(str(request.GET['end']), '%Y-%m-%d').date()
    filtered_kill_request = 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, vet_state='pending', assignment_state_archive='pending').order_by(
        '-create_date').select_related(
        'killhouse_user', 'province_request__poultry_request__poultry__user', 'province_request__poultry_request',
        'province_request__poultry_request__poultry', 'add_car__driver', 'killhouse_user__system_address__city',
        'kill_request__slaughter_house').only('message', 'province_request__poultry_request__freezing',
                                              'province_request__poultry_request', 'traffic_code',
                                              'assignment_state_archive',
                                              'province_request__poultry_request__hatching__chicken_age',
                                              'killhouse_user__kill_house_operator__user__province__name',
                                              'killhouse_user',
                                              'killhouse_user__name', 'province_request__poultry_request__amount',
                                              'killhouse_user__kill_house_operator__user__mobile',
                                              'killhouse_user__system_address__city__name',
                                              'killhouse_user__killer',
                                              'kill_request__slaughter_house',
                                              'kill_request__slaughter_house__name',
                                              'province_request__poultry_request__poultry',
                                              'province_request__poultry_request__order_code',
                                              'province_request__poultry_request__chicken_breed',
                                              'province_request__poultry_request__poultry__user__city__name',
                                              'province_request__poultry_request__poultry__unit_name',
                                              'province_request__poultry_request__poultry__user__mobile',
                                              'province_request__poultry_request__send_date',
                                              'province_kill_request__province_request__poultry_request__Index_weight',
                                              'add_car__driver__driver_name',
                                              'add_car__driver__driver_mobile',
                                              'add_car__driver__type_car',
                                              'add_car__driver__health_code',
                                              'key',
                                              'clearance_code',
                                              'quantity',
                                              'bar_code',
                                              'accepted_real_weight',
                                              'accepted_real_quantity',
                                              'vet_state', 'vet_accepted_real_quantity',
                                              'vet_accepted_real_weight', 'quarantine_quantity',
                                              'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                              'province_kill_request__province_request__poultry_request__union',
                                              'province_kill_request__province_request__poultry_request__direct_buying',
                                              'quarantine_code_state',
                                              'province_request__poultry_request__send_date',
                                              'province_request__poultry_request__hatching__date').values('message',
                                                                                                          'province_request__poultry_request__freezing',
                                                                                                          'province_request__poultry_request',
                                                                                                          'killhouse_user',
                                                                                                          'killhouse_user__name',
                                                                                                          'killhouse_user__kill_house_operator__user__mobile',
                                                                                                          'killhouse_user__system_address__city__name',
                                                                                                          'killhouse_user__killer',
                                                                                                          'kill_request__slaughter_house',
                                                                                                          'kill_request__slaughter_house__name',
                                                                                                          'province_request__poultry_request__poultry',
                                                                                                          'province_request__poultry_request__order_code',
                                                                                                          'province_request__poultry_request__chicken_breed',
                                                                                                          'province_request__poultry_request__poultry__user__city__name',
                                                                                                          'province_request__poultry_request__poultry__unit_name',
                                                                                                          'province_request__poultry_request__poultry__user__mobile',
                                                                                                          'province_request__poultry_request__send_date',
                                                                                                          'add_car__driver__driver_name',
                                                                                                          'add_car__driver__driver_mobile',
                                                                                                          'add_car__driver__type_car',
                                                                                                          'add_car__driver__health_code',
                                                                                                          'key',
                                                                                                          'province_kill_request__province_request__poultry_request__Index_weight',
                                                                                                          'clearance_code',
                                                                                                          'quantity',
                                                                                                          'bar_code',
                                                                                                          'accepted_real_weight',
                                                                                                          'accepted_real_quantity',
                                                                                                          'vet_state',
                                                                                                          'vet_accepted_real_quantity',
                                                                                                          'vet_accepted_real_weight',
                                                                                                          'quarantine_quantity',
                                                                                                          'killhouse_user__kill_house_operator__user__province__name',
                                                                                                          'province_request__poultry_request__hatching__chicken_age',
                                                                                                          'province_request__poultry_request__amount',
                                                                                                          'assignment_state_archive',
                                                                                                          'traffic_code',
                                                                                                          'province_kill_request__province_request__poultry_request__free_sale_in_province',
                                                                                                          'province_kill_request__province_request__poultry_request__union',
                                                                                                          'province_kill_request__province_request__poultry_request__direct_buying',
                                                                                                          'quarantine_code_state',
                                                                                                          'province_request__poultry_request__send_date',
                                                                                                          'province_request__poultry_request__hatching__date'
                                                                                                          )
    if 'key' in request.GET:
        if 'role' in request.GET:
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            if request.GET['role'] == 'CityOperator':
                city_operator = CityOperator.objects.get(trash=False, user=user)
                filtered_kill_reqs = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__city_operator=city_operator.unit_name)
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                filtered_kill_reqs = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__user__city=user.city)
            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)
                filtered_kill_reqs = filtered_kill_request.filter(
                    province_request__poultry_request__poultry__in=poultries)

            elif request.GET['role'] == 'KillHouse':
                filtered_kill_reqs = filtered_kill_request.filter(killhouse_user=user)
            else:
                filtered_kill_reqs = filtered_kill_request
        else:
            filtered_kill_reqs = filtered_kill_request
    else:
        filtered_kill_reqs = filtered_kill_request
    poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs.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']
    excel_options = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'فروش',

        'سن مرغ',
        'قیمت پیشنهادی مرغدار(ریال)',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        ' محل کشتار ',
        'نوع تخصیص',

        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه بار ',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد قطعه وارد شده در قرنطینه',
        'وضعیت تخلیه',
        'تاریخ تخلیه (کشتارگاه)',
        'تعداد تخلیه شده دامپزشک',
        'وزن بار تخلیه شده(کیلوگرم)دامپزشک',
        'تعداد نهایی در کشتارگاه',
        'وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',
        'وضعیت',

    ]
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    from_date_1 = separate.join(reversed_date)

    to_date = jdatetime.date.fromgregorian(
        year=date2.year,
        month=date2.month,
        day=date2.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(to_date.split("-"))
    separate = "-"
    to_date_1 = separate.join(reversed_date)

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)

    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=6, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        if len(option) > worksheet.column_dimensions[col_letter].width:
            worksheet.column_dimensions[col_letter].width = len(option) + 3

            # تنظیم ارتفاع سطر
            # ارتفاع سطر را برابر با ارتفاع آخرین سطر قرار می‌دهیم
        worksheet.row_dimensions[6].height = 19
        worksheet.freeze_panes = worksheet['A7']
        max_col = worksheet.max_column
        range_str = f'A6:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    header_list = [
        'تعداد بارهای ایجاد شده',
        'مجموع تعداد قطعه بارها',
        'مجموع وزن بارها',
        'تعداد بارهای دارای کد قرنطینه',
        'تعداد بار احراز شده از قرنطینه',
        'مجموع تعداد قطعه احراز شده از قرنطینه',
        'تعداد  تخلیه شده دامپزشک',
        'مجموع تعداد  تخلیه شده دامپزشک',
        'مجموع وزن  تخلیه شده دامپزشک',
        'تعداد بارهای تکمیل شده',
        'مجموع تعداد نهایی در کشتارگاه',
        'مجموع وزن نهایی در کشتار گاه',
        'ملاک قطعه کشتار شده',
        'ملاک وزن کشتار شده',

    ]
    for col_num, option in enumerate(header_list, 9):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="0070C0", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    for col_num, option in enumerate(header_list2, 6):
        cell = worksheet.cell(row=2, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
        cell.font = Font(size=9, bold=True, color='D9FFFFFF')
        worksheet.row_dimensions[2].height = 20.8

    worksheet['B1'] = f'گزارش بارهای معلق در فرآیند کشتار مرغ گوشتی'

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first()['killhouse_user__kill_house_operator__user__province__name']
        worksheet['B2'] = f'استان {name}'

    worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    worksheet['B3'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B2'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range1 = 'B1:D1'
    merge_range2 = 'B2:D2'
    merge_range = 'B3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['B3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1
    all_quantity = 0
    all_real_quantity = 0
    all_net_weighte = 0
    all_weighte = 0
    all_vet_state_accepted = len(
        filtered_kill_reqs.filter(vet_state='accepted'))
    bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')
    accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity', 0)
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity', 0)

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity', 0)
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity', 0)

    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:
            if (kill['assignment_state_archive'] == 'True' and kill['vet_state'] == 'pending') or kill[
                'vet_state'] == 'accepted':
                state = 'تخلیه شده'
            else:
                state = 'درانتظار تخلیه'
            l += 1
            date_of_inner_bar = '-'
            vet_farm = VetFarm.objects.filter(poultry=kill.get('province_request__poultry_request__poultry'),
                                              trash=False).select_related('vet__user').only('vet__user__fullname',
                                                                                            'vet__user__mobile').values(
                'vet__user__fullname',
                'vet__user__mobile').first()
            vet_farm_name = vet_farm.get('vet__user__fullname') if vet_farm else '-'
            vet_farm_mobile = vet_farm.get('vet__user__mobile') if vet_farm else '-'
            kil_house_vet = KillHouseVet.objects.filter(kill_house=kill.get('killhouse_user'),
                                                        trash=False).select_related(
                'vet__user').only('vet__user__fullname',
                                  'vet__user__mobile').values('vet__user__fullname',
                                                              'vet__user__mobile').first()
            vet_checks = VetCheckRequest.objects.filter(trash=False, kill_house_request__key=kill.get('key')).only(
                'create_date').values(
                'create_date').first()
            kill_house_vet_name = kil_house_vet.get('vet__user__fullname') if kil_house_vet else '-'
            kill_house_vet_mobile = kil_house_vet.get('vet__user__mobile') if kil_house_vet else '-'
            code = kill.get('clearance_code') if kill.get('clearance_code') else '-'
            if kill.get('quantity'):
                quantity = kill.get('quantity')
                all_quantity += quantity
            else:
                quantity = '-'
            send_date = kill.get('province_request__poultry_request__send_date')
            date_of_poultry_request = jdatetime.date.fromgregorian(
                day=send_date.day,
                month=send_date.month,
                year=send_date.year
            )
            killers = 'کشتارکن'
            if kill.get('killhouse_user__killer') == False:
                killers = 'کشتارگاه'
            assignment = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key=kill.get('key'), trash=False).only('create_date', 'net_weight',
                                                                           'real_quantity').values(
                'net_weight', 'real_quantity', 'create_date').first()
            if assignment:
                net_weighte = assignment.get('net_weight')
                all_net_weighte += net_weighte
                real_quantity = assignment.get('real_quantity')
                all_real_quantity += real_quantity
                vet_check_date = assignment.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )
            else:
                net_weighte = '-'
                real_quantity = '-'
            if vet_checks:
                vet_check_date = vet_checks.get('create_date')
                date_of_inner_bar = convert_to_shamsi(
                    datetime=vet_check_date
                )

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            vet_quantity = kill['vet_accepted_real_quantity'] if kill['vet_accepted_real_quantity'] else '-'
            vet_wight = kill['vet_accepted_real_weight'] if kill['vet_accepted_real_weight'] else '-'

            weight = kill.get('quantity') * kill.get(
                'province_kill_request__province_request__poultry_request__Index_weight')
            all_weighte += weight
            quarantine_quantity = '-'

            if kill['quarantine_quantity'] != None:
                quarantine_quantity = kill['quarantine_quantity']
            else:
                if kill['quarantine_code_state'] == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif kill['quarantine_code_state'] == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif kill['quarantine_code_state'] == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                elif kill['quarantine_code_state'] == 'merge':
                    quarantine_quantity = 'ادغام'

            sale_type = 'دولتی' if kill[
                                       'province_kill_request__province_request__poultry_request__free_sale_in_province'] == False else 'آزاد'

            if kill['province_kill_request__province_request__poultry_request__union'] == True:
                type = 'فروش آزاد'
            elif kill['province_kill_request__province_request__poultry_request__direct_buying'] == True:
                type = 'خرید مستقیم'
            else:
                type = 'اتحادیه'
            age = (kill.get('province_request__poultry_request__send_date').date() -
                   kill.get('province_request__poultry_request__hatching__date').date()).days + 1

            freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
            if kill['message'] is not None:
                state_delete = 'بار حذف شده'
            else:
                state_delete = 'فعال'
            list1 = [
                m,
                str(kill.get('bar_code')),
                str(date_of_poultry_request),
                freez_state,
                str(kill.get('province_request__poultry_request__order_code')),
                kill.get('province_request__poultry_request__poultry__unit_name'),
                str(kill.get('province_request__poultry_request__poultry__user__mobile')),
                kill.get('province_request__poultry_request__poultry__user__city__name'),
                sale_type,
                age,
                kill.get('province_request__poultry_request__amount') if kill.get(
                    'province_request__poultry_request__amount') else '-',
                kill.get('province_request__poultry_request__chicken_breed'),
                vet_farm_name,
                vet_farm_mobile,
                killers,
                kill.get('killhouse_user__name'),
                kill.get('killhouse_user__kill_house_operator__user__mobile'),
                kill.get('killhouse_user__system_address__city__name'),
                kill_place,
                type,
                kill_house_vet_name,
                kill_house_vet_mobile,
                kill.get('add_car__driver__driver_name'),
                kill.get('add_car__driver__driver_mobile'),
                kill.get('add_car__driver__type_car'),
                str(kill.get('traffic_code')),
                quantity,
                weight,
                code,
                quarantine_quantity,
                state,
                str(date_of_inner_bar),
                vet_quantity,
                vet_wight,
                real_quantity,
                net_weighte,
                kill['accepted_real_quantity'],
                kill['accepted_real_weight'],
                state_delete,

            ]
            m += 1
            for item in range(len(list1)):
                cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
                value = list1[item]
                # Check if the value is a number before formatting
                if isinstance(value, (int, float)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')

    has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
    all_quarantine_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quarantine_quantity')).get(
        'total_quantity', 0)
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))

    value_header_list = [
        len(filtered_kill_reqs),
        all_quantity,
        all_weighte,
        has_code,
        has_qarantine,

        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        all_vet_state_accepted,
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        len(bar_complete),
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 9, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    value_header_list2 = [
        len(poultry_request),
        total_requests_quantity,
        total_requests_weight

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list2[item])
        value = value_header_list2[item]
        # Check if the value is a number before formatting
        if isinstance(value, (int, float)):
            if value != 0:
                cell.number_format = '#,###'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        all_quarantine_quantity if all_quarantine_quantity != None else 0,
        '',
        '',
        all_vet_accepted_real_quantity,
        all_vet_accepted_real_weight,
        all_real_quantity,
        all_net_weighte,
        accepted_real_quantity if accepted_real_quantity != None else 0,
        accepted_real_wight if accepted_real_wight != None else 0,
        ''

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l + 3, column=item + 1, value=list2[item])
        value = list2[item]
        if isinstance(value, (int, float)):
            cell.number_format = '#,##0'  # Apply general number format
        else:
            cell.value = value  # Keep as text for other values

        cell.alignment = Alignment(horizontal='center')
        cell.font = Font(size=10, bold=True)
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="00B050", fill_type="solid")
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    if 'role' in request.GET:
        if request.GET['role'] == 'KillHouse':
            name = filtered_kill_request.first()['killhouse_user__name']
            response[
                'Content-Disposition'] = f'attachment; filename="مدیریت بارهای کشتارگاه {name}.xlsx"'.encode(
                'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename=" مدیریت بارها معلق.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def chain_excel(request):
    chain = ChainCompany.objects.filter(trash=False)

    excel_options = [
        'ردیف',
        'نام شرکت',
        'نام مدیرعامل',
        'نام خانوادگی مدیرعامل',
        'موبایل',
        'شهر',
        'آدرس',
        'کد پستی',

    ]
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    blue_fill = PatternFill(start_color="1E487B", fill_type="solid")
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    for col_num, option in enumerate(excel_options, 1):
        col_letter = get_column_letter(col_num)
        cell = worksheet.cell(row=3, column=col_num, value=option)
        cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        cell.fill = blue_fill
        cell.font = Font(size=10, bold=True, color='D9FFFFFF')
        worksheet.column_dimensions[col_letter].width = 26.01
        worksheet.row_dimensions[3].height = 25
        worksheet.freeze_panes = worksheet['A4']
        max_col = worksheet.max_column
        range_str = f'A3:{get_column_letter(max_col)}{worksheet.max_row}'
        worksheet.auto_filter.ref = range_str
    worksheet['A2'] = f'مدیریت شرکت های استان {chain.first().address.province.name}'

    worksheet['A2'].font = Font(color="C00000", bold=True)
    worksheet['A2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    merge_range1 = 'A2:B2'

    worksheet.merge_cells(merge_range1)
    l = 2
    m = 1

    for user in chain:

        list1 = [
            m,
            user.name,
            user.user.first_name,
            user.user.last_name,
            user.user.mobile,
            user.address.city.name,
            user.address.address,
            user.address.postal_code,

        ]
        l += 1
        for item in range(len(list1)):
            cell = worksheet.cell(row=l + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
        m += 1
    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="مدیریت شرکت ها.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def test_excel(request):
    start_excel()
    return close_excel('nima')


def test_all_excel_functions(request):
    from panel.VetFarm.excel_processing import technical_responsible_performance_excel, totoal_technical_responsible_performance_excel
    from panel.ProvinceOperator.excel_processing import (
        kill_house_total_transactions_wage_payid_super_admin_excel, kill_house_total_transactions_wage_payid_excel,
        payment_transactions_province_excel, general_free_bar_excel, out_province_poultry_request_buyers_excel,
        chain_company_buyers_excel, bar_chain_excel, kill_house_total_transactions_wage_payid_admin_x_excel,
        buy_outside_the_province_excel, poultry_request_report_excel, transacion_out_request_excel,
        from_allocation_to_distribution_excel, login_user_excel, city_operator_for_sub_sector_excel,
        vet_for_sub_sector_excel, guild_for_sub_sector_excel, all_guilds_transaction_excel,
        detail_guilds_transaction_excel, management_hatching_excel, user_without_role_excel,
        sub_section_of_cooperative_share_detail_with_date_excel, vet_for_sub_sector_with_date_excel,
        dashboard_monitoring_bar_and_killing_excel, steward_allocation_excel,
        sevrence_kill_house_steward_allocation_excel, free_sale_out_province_excel,
        steward_free_sale_out_province_excel, total_steward_dashboard_excel,
        detail_of_killing_and_warehouse_excel, market_requests_excel, return_province_request_excel,
        guilds_without_allocation_excel
    )
    from panel.poultry.excel_processing import (
        hatching_excel, archive_hatching_excel, hatching_age_range_excel, poultry_monitoring_excel,
        poultry_hatching_prediction_chart_excel, hatching_report_from_age_excel,
        poultry_hatching_prediction_excel, bar_difference_reques_excel
    )
    from panel.KillHouse.excel_processing import (
        direct_purchase_excel, direct_purchase_archive_excel, kill_house_assignment_information_excel,
        kill_house_user_excel, bar_excel, kill_house_total_wage_excel, slaughterhouse_export_excel,
        export_kill_house_excel, monitor_loads_excel, kill_house_free_bar_excel,
        comprehensive_report_of_the_slaughterhouse_excel, out_province_carcasses_buyer_kill_house_excel,
        kill_house_free_sale_bar_information_for_excel_excel, kill_house_free_sale_bar_information_excel,
        notentered_bars_for_kill_house_excel, entered_bars_for_kill_house_excel,
        kill_house_free_bar_entered_for_warehouse_excel, kill_house_free_bar_carcasses_for_warehouse_excel,
        steward_allocation_for_warehouse_excel, cold_house_excel, management_cold_house_excel,
        create_guilds_or_stewards_from_excel, non_receipt_request_excel, return_kill_house_request_excel,
        warehouse_archive_combined_excel
    )
    from helper_eata import token, chat_id
    from django.http import QueryDict

    class MockRequest:
        def __init__(self, get_params=None):
            if get_params:
                self.GET = QueryDict(get_params)
            else:
                self.GET = QueryDict()
            self.FILES = {}
            self.data = {}
            if adminx_user:
                self.user = adminx_user.user
            else:
                self.user = None

    adminx_user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    adminx_key = adminx_user.key if adminx_user else None
    adminx_token = None
    if adminx_user:
        access_token = AccessToken.objects.filter(user=adminx_user.user).first()
        adminx_token = access_token.token if access_token else None

    today = datetime.datetime.now().date()
    date1 = today - timedelta(days=1)
    date2 = today

    date1_str = date1.strftime('%Y-%m-%d')
    date2_str = date2.strftime('%Y-%m-%d')

    def add_params(base_params, use_start_end=False, use_date1_date2=False, use_token=False):
        params = base_params.copy() if base_params else {}
        if adminx_key:
            params['key'] = adminx_key
            params['role'] = 'AdminX'
        if use_token and adminx_token:
            params['token'] = adminx_token
        if use_start_end:
            params['start'] = date1_str
            params['end'] = date2_str
        elif use_date1_date2:
            params['date1'] = date1_str
            params['date2'] = date2_str
        else:
            params['date1'] = date1_str
            params['date2'] = date2_str
        return params

    excel_functions = [
        # (vet_check_excel, add_params({}, use_start_end=True)),
        (kill_house_request_excel, add_params({}, use_start_end=True)),
        # (request_report_excel, add_params({}, use_date1_date2=True)),
        (allocated_excel, add_params({}, use_start_end=True)),
        (allocated_trash_true_excel, add_params({}, use_start_end=True)),
        (poultry_kill_request_excel, add_params({'token': adminx_token} if adminx_token else {}, use_start_end=True)),
        (car_allocation_excel, add_params({}, use_start_end=True)),
        (guilds_excel, add_params({})),
        # (commerce_report_excel, add_params({}, use_start_end=True)),
        # (commerce_bar_excel, add_params({}, use_start_end=True)),
        (number_of_kills_weight_excel, add_params({'day': 1})),
        (number_of_kills_excel, add_params({'day': 1})),
        (single_hatching_age_range_excel, add_params({})),
        # (total_poultry_request_dashboard_excel, add_params({})),
        (total_poultry_hatching_dashboard_excel, add_params({})),
        # (doughnut_left_hatching_excel, add_params({}, use_token=True)),
        # (doughnut_hatching_excel, add_params({}, use_token=True)),
        (forecast_hatching_left_over_excel, add_params({'age': 60})),
        (manager_of_farm_excel, add_params({})),
        (kill_house__request_vet_killing_process_excel, add_params({})),
        (kill_house_percent_excel, add_params({})),
        # (poultry_request_out_excel, add_params({'date': date1_str})),
        (get_all_user_excel, add_params({})),
        (stewards_excel, add_params({})),
        (all_kill_house_total_wage_excel, add_params({'token': adminx_token})),
        (kill_house_total_wage_not_payid_excel, add_params({'token': adminx_token})),
        (slaughterhouse_fee_excel, add_params({})),
        (slaughterhouse_fee_not_paid_excel, add_params({})),
        (car_province_excel, add_params({})),
        (kill_house_wage_archive_excel, add_params({})),
        (kill_house_total_wage_archive_excel, add_params({})),
        (bar_management_kill_house_excel, add_params({})),
        (all_inventory_excel, add_params({})),
        (daily_process_excel, add_params({})),
        (daily_process_klling_proccess_excel, add_params({'date': date1_str})),
        (killing_process_from_date_excel, add_params({}, use_start_end=True)),
        (discrepancy_report_excel, add_params({})),
        # (bar_for_each_persion_excel, add_params({'code': 'test_code'})),
        # (poultry_excel, add_params({}, use_start_end=True)),
        (bar_contradiction_of_quarantine_excel, add_params({}, use_start_end=True)),
        (detail_of_killing_excel, add_params({})),
        # (pos_excel, add_params({})),
        (poultry_and_bar_daily_report_excel, add_params({})),
        (bar_free_excel, add_params({'state': 'pending'})),
        (steward_ware_house_total_report_daily_excel, add_params({})),
        # (steward_ware_house_total_report_daily_detail_excel, add_params({}, use_date1_date2=True)),
        (hatching_for_detail_killing_excel, add_params({})),
        (bar_live_stock_support_excel, add_params({}, use_start_end=True)),
        (successful_transactions_excel, add_params({})),
        (unsuccessful_transactions_excel, add_params({})),
        (poultry_hatching_between_50age_70age_excel, add_params({})),
        (number_of_times_with_quarantine_code_excel, add_params({})),
        (the_burden_of_quarantine_excel, add_params({})),
        (bar_without_quarantine_code_excel, add_params({})),
        (loads_that_differ_in_quarantine_and_cooperation_excel, add_params({})),
        (government_burden_excel, add_params({})),
        (goverment_bar_state_with_a_certified_quarantine_code_excel, add_params({})),
        (free_loads_excel, add_params({})),
        (free_cargoes_obtained_from_quarantine_excel, add_params({})),
        (free_loads_with_quarantine_code_excel, add_params({})),
        # (loads_outside_the_province_excel, add_params({})),
        (loads_entering_the_slaughterhouse_excel, add_params({})),
        (veterinarian_unloaded_load_excel, add_params({})),
        (completed_slaughterhouse_loads_excel, add_params({})),
        (unloaded_cargo_without_quarantine_code_excel, add_params({})),
        (unloaded_load_excel, add_params({})),
        (loads_unloaded_and_not_completed_by_the_slaughterhouse_excel, add_params({})),
        (hatching_date_range_excel, add_params({}, use_date1_date2=True)),
        (wallete_excel, add_params({})),
        (kill_house_request_suspended_load_excel, add_params({}, use_start_end=True)),
        # (chain_excel, add_params({})),
        # (technical_responsible_performance_excel, add_params({})),
        # (totoal_technical_responsible_performance_excel, add_params({}, use_date1_date2=True)),
        (kill_house_total_transactions_wage_payid_super_admin_excel, add_params({})),
        (kill_house_total_transactions_wage_payid_excel, add_params({})),
        (payment_transactions_province_excel, add_params({})),
        (general_free_bar_excel, add_params({})),
        (out_province_poultry_request_buyers_excel, add_params({})),
        (chain_company_buyers_excel, add_params({})),
        (bar_chain_excel, add_params({'state': 'accepted'}, use_date1_date2=True)),
        (kill_house_total_transactions_wage_payid_admin_x_excel, add_params({})),
        (buy_outside_the_province_excel, add_params({})),
        (poultry_request_report_excel, add_params({}, use_start_end=True)),
        (transacion_out_request_excel, add_params({'type': 'poultry'}, use_date1_date2=True)),
        (from_allocation_to_distribution_excel, add_params({})),
        (login_user_excel, add_params({})),
        (city_operator_for_sub_sector_excel, add_params({'type': 'city'})),
        (vet_for_sub_sector_excel, add_params({'type': 'vet'})),
        (guild_for_sub_sector_excel, add_params({'type': 'guild'}, use_date1_date2=True)),
        (all_guilds_transaction_excel, add_params({})),
        # (detail_guilds_transaction_excel, add_params({}, use_date1_date2=True)),
        (management_hatching_excel, add_params({})),
        (user_without_role_excel, add_params({})),
        # (sub_section_of_cooperative_share_detail_with_date_excel, add_params({}, use_date1_date2=True)),
        (vet_for_sub_sector_with_date_excel, add_params({}, use_date1_date2=True)),
        (dashboard_monitoring_bar_and_killing_excel, add_params({})),
        (steward_allocation_excel, add_params({})),
        # (sevrence_kill_house_steward_allocation_excel, add_params({'type':'KillHouse'})),
        (free_sale_out_province_excel, add_params({'type': 1})),
        (steward_free_sale_out_province_excel, add_params({})),
        (total_steward_dashboard_excel, add_params({})),
        (detail_of_killing_and_warehouse_excel, add_params({})),
        (market_requests_excel, add_params({})),
        (return_province_request_excel, add_params({})),
        (guilds_without_allocation_excel, add_params({})),
        (hatching_excel, add_params({})),
        (archive_hatching_excel, add_params({})),
        (hatching_age_range_excel, add_params({})),
        # (poultry_monitoring_excel, add_params({})),
        # (poultry_hatching_prediction_chart_excel, add_params({})),
        (hatching_report_from_age_excel, add_params({'age1': 50, 'age2': 60})),
        # (poultry_hatching_prediction_excel, add_params({})),
        # (bar_difference_reques_excel, add_params({'state':'pending'})),
        (direct_purchase_excel, add_params({}, use_date1_date2=True)),
        (direct_purchase_archive_excel, add_params({}, use_date1_date2=True)),
        # (kill_house_assignment_information_excel, add_params({}, use_start_end=True)),
        (kill_house_user_excel, add_params({})),
        (bar_excel, add_params({}, use_start_end=True)),
        (kill_house_total_wage_excel, add_params({})),
        # (slaughterhouse_export_excel, add_params({}, use_date1_date2=True)),
        (export_kill_house_excel, add_params({})),
        (monitor_loads_excel, add_params({})),
        (kill_house_free_bar_excel, add_params({'type': 'all'}, use_date1_date2=True)),
        (comprehensive_report_of_the_slaughterhouse_excel, add_params({})),
        # (out_province_carcasses_buyer_kill_house_excel, add_params({})),
        # (kill_house_free_sale_bar_information_for_excel_excel, add_params({})),
        # (kill_house_free_sale_bar_information_excel, add_params({}, use_date1_date2=True)),
        (notentered_bars_for_kill_house_excel, add_params({})),
        (entered_bars_for_kill_house_excel, add_params({})),
        (kill_house_free_bar_entered_for_warehouse_excel, add_params({'type': 'all', 'bar_state': 'entered'})),
        (kill_house_free_bar_carcasses_for_warehouse_excel, add_params({'type': 'all', 'bar_state': 'carcasses'})),
        (steward_allocation_for_warehouse_excel, add_params({})),
        # (cold_house_excel, add_params({}, use_date1_date2=True)),
        (management_cold_house_excel, add_params({})),
        (non_receipt_request_excel, add_params({})),
        (return_kill_house_request_excel, add_params({})),
        (warehouse_archive_combined_excel, add_params({})),
    ]

    failed_functions = []

    for func, params in excel_functions:
        try:
            if params:
                query_string = '&'.join([f'{k}={v}' for k, v in params.items()])
                mock_request = MockRequest(query_string)
            else:
                mock_request = MockRequest()
            response = func(mock_request)
            if not response or not isinstance(response, HttpResponse):
                failed_functions.append(func.__name__)
        except Exception as e:
            failed_functions.append(func.__name__)

    if failed_functions:
        url = f'https://eitaayar.ir/api/{token}/sendMessage'
        message = f'❌ توابع اکسل که خطا داشتند:\n\n'
        message += f'❌ استان:{base_url_for_sms_report}\n\n'
        for func_name in failed_functions:

            message += f'• {func_name}\n'

        data = {
            'chat_id': 10046800,
            'text': message,
        }
        requests.post(url, data=data, verify=False)

    return HttpResponse(f'تست انجام شد. تعداد توابع با خطا: {len(failed_functions)}')


def test_all_excel_functions_cron():
    from panel.VetFarm.excel_processing import technical_responsible_performance_excel, totoal_technical_responsible_performance_excel
    from panel.ProvinceOperator.excel_processing import (
        kill_house_total_transactions_wage_payid_super_admin_excel, kill_house_total_transactions_wage_payid_excel,
        payment_transactions_province_excel, general_free_bar_excel, out_province_poultry_request_buyers_excel,
        chain_company_buyers_excel, bar_chain_excel, kill_house_total_transactions_wage_payid_admin_x_excel,
        buy_outside_the_province_excel, poultry_request_report_excel, transacion_out_request_excel,
        from_allocation_to_distribution_excel, login_user_excel, city_operator_for_sub_sector_excel,
        vet_for_sub_sector_excel, guild_for_sub_sector_excel, all_guilds_transaction_excel,
        detail_guilds_transaction_excel, management_hatching_excel, user_without_role_excel,
        sub_section_of_cooperative_share_detail_with_date_excel, vet_for_sub_sector_with_date_excel,
        dashboard_monitoring_bar_and_killing_excel, steward_allocation_excel,
        sevrence_kill_house_steward_allocation_excel, free_sale_out_province_excel,
        steward_free_sale_out_province_excel, total_steward_dashboard_excel,
        detail_of_killing_and_warehouse_excel, market_requests_excel, return_province_request_excel,
        guilds_without_allocation_excel
    )
    from panel.poultry.excel_processing import (
        hatching_excel, archive_hatching_excel, hatching_age_range_excel, poultry_monitoring_excel,
        poultry_hatching_prediction_chart_excel, hatching_report_from_age_excel,
        poultry_hatching_prediction_excel, bar_difference_reques_excel
    )
    from panel.KillHouse.excel_processing import (
        direct_purchase_excel, direct_purchase_archive_excel, kill_house_assignment_information_excel,
        kill_house_user_excel, bar_excel, kill_house_total_wage_excel, slaughterhouse_export_excel,
        export_kill_house_excel, monitor_loads_excel, kill_house_free_bar_excel,
        comprehensive_report_of_the_slaughterhouse_excel, out_province_carcasses_buyer_kill_house_excel,
        kill_house_free_sale_bar_information_for_excel_excel, kill_house_free_sale_bar_information_excel,
        notentered_bars_for_kill_house_excel, entered_bars_for_kill_house_excel,
        kill_house_free_bar_entered_for_warehouse_excel, kill_house_free_bar_carcasses_for_warehouse_excel,
        steward_allocation_for_warehouse_excel, cold_house_excel, management_cold_house_excel,
        create_guilds_or_stewards_from_excel, non_receipt_request_excel, return_kill_house_request_excel,
        warehouse_archive_combined_excel
    )
    from helper_eata import token, chat_id
    from django.http import QueryDict

    class MockRequest:
        def __init__(self, get_params=None):
            if get_params:
                self.GET = QueryDict(get_params)
            else:
                self.GET = QueryDict()
            self.FILES = {}
            self.data = {}
            if adminx_user:
                self.user = adminx_user.user
            else:
                self.user = None

    adminx_user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    adminx_key = adminx_user.key if adminx_user else None
    adminx_token = None
    if adminx_user:
        access_token = AccessToken.objects.filter(user=adminx_user.user).first()
        adminx_token = access_token.token if access_token else None

    today = datetime.datetime.now().date()
    date1 = today - timedelta(days=1)
    date2 = today

    date1_str = date1.strftime('%Y-%m-%d')
    date2_str = date2.strftime('%Y-%m-%d')

    def add_params(base_params, use_start_end=False, use_date1_date2=False, use_token=False):
        params = base_params.copy() if base_params else {}
        if adminx_key:
            params['key'] = adminx_key
            params['role'] = 'AdminX'
        if use_token and adminx_token:
            params['token'] = adminx_token
        if use_start_end:
            params['start'] = date1_str
            params['end'] = date2_str
        elif use_date1_date2:
            params['date1'] = date1_str
            params['date2'] = date2_str
        else:
            params['date1'] = date1_str
            params['date2'] = date2_str
        return params

    excel_functions = [
        # (vet_check_excel, add_params({}, use_start_end=True)),
        (kill_house_request_excel, add_params({}, use_start_end=True)),
        # (request_report_excel, add_params({}, use_date1_date2=True)),
        (allocated_excel, add_params({}, use_start_end=True)),
        (allocated_trash_true_excel, add_params({}, use_start_end=True)),
        (poultry_kill_request_excel, add_params({'token': adminx_token} if adminx_token else {}, use_start_end=True)),
        (car_allocation_excel, add_params({}, use_start_end=True)),
        (guilds_excel, add_params({})),
        # (commerce_report_excel, add_params({}, use_start_end=True)),
        # (commerce_bar_excel, add_params({}, use_start_end=True)),
        (number_of_kills_weight_excel, add_params({'day': 1})),
        (number_of_kills_excel, add_params({'day': 1})),
        (single_hatching_age_range_excel, add_params({})),
        # (total_poultry_request_dashboard_excel, add_params({})),
        (total_poultry_hatching_dashboard_excel, add_params({})),
        # (doughnut_left_hatching_excel, add_params({}, use_token=True)),
        # (doughnut_hatching_excel, add_params({}, use_token=True)),
        (forecast_hatching_left_over_excel, add_params({'age': 60})),
        (manager_of_farm_excel, add_params({})),
        (kill_house__request_vet_killing_process_excel, add_params({})),
        (kill_house_percent_excel, add_params({})),
        # (poultry_request_out_excel, add_params({'date': date1_str})),
        (get_all_user_excel, add_params({})),
        (stewards_excel, add_params({})),
        (all_kill_house_total_wage_excel, add_params({'token': adminx_token})),
        (kill_house_total_wage_not_payid_excel, add_params({'token': adminx_token})),
        (slaughterhouse_fee_excel, add_params({})),
        (slaughterhouse_fee_not_paid_excel, add_params({})),
        (car_province_excel, add_params({})),
        (kill_house_wage_archive_excel, add_params({})),
        (kill_house_total_wage_archive_excel, add_params({})),
        (bar_management_kill_house_excel, add_params({})),
        (all_inventory_excel, add_params({})),
        (daily_process_excel, add_params({})),
        (daily_process_klling_proccess_excel, add_params({'date': date1_str})),
        (killing_process_from_date_excel, add_params({}, use_start_end=True)),
        (discrepancy_report_excel, add_params({})),
        # (bar_for_each_persion_excel, add_params({'code': 'test_code'})),
        # (poultry_excel, add_params({}, use_start_end=True)),
        (bar_contradiction_of_quarantine_excel, add_params({}, use_start_end=True)),
        (detail_of_killing_excel, add_params({})),
        # (pos_excel, add_params({})),
        (poultry_and_bar_daily_report_excel, add_params({})),
        (bar_free_excel, add_params({'state': 'pending'})),
        (steward_ware_house_total_report_daily_excel, add_params({})),
        # (steward_ware_house_total_report_daily_detail_excel, add_params({}, use_date1_date2=True)),
        (hatching_for_detail_killing_excel, add_params({})),
        (bar_live_stock_support_excel, add_params({}, use_start_end=True)),
        (successful_transactions_excel, add_params({})),
        (unsuccessful_transactions_excel, add_params({})),
        (poultry_hatching_between_50age_70age_excel, add_params({})),
        (number_of_times_with_quarantine_code_excel, add_params({})),
        (the_burden_of_quarantine_excel, add_params({})),
        (bar_without_quarantine_code_excel, add_params({})),
        (loads_that_differ_in_quarantine_and_cooperation_excel, add_params({})),
        (government_burden_excel, add_params({})),
        (goverment_bar_state_with_a_certified_quarantine_code_excel, add_params({})),
        (free_loads_excel, add_params({})),
        (free_cargoes_obtained_from_quarantine_excel, add_params({})),
        (free_loads_with_quarantine_code_excel, add_params({})),
        # (loads_outside_the_province_excel, add_params({})),
        (loads_entering_the_slaughterhouse_excel, add_params({})),
        (veterinarian_unloaded_load_excel, add_params({})),
        (completed_slaughterhouse_loads_excel, add_params({})),
        (unloaded_cargo_without_quarantine_code_excel, add_params({})),
        (unloaded_load_excel, add_params({})),
        (loads_unloaded_and_not_completed_by_the_slaughterhouse_excel, add_params({})),
        (hatching_date_range_excel, add_params({}, use_date1_date2=True)),
        (wallete_excel, add_params({})),
        (kill_house_request_suspended_load_excel, add_params({}, use_start_end=True)),
        # (chain_excel, add_params({})),
        # (technical_responsible_performance_excel, add_params({})),
        # (totoal_technical_responsible_performance_excel, add_params({}, use_date1_date2=True)),
        (kill_house_total_transactions_wage_payid_super_admin_excel, add_params({})),
        (kill_house_total_transactions_wage_payid_excel, add_params({})),
        (payment_transactions_province_excel, add_params({})),
        (general_free_bar_excel, add_params({})),
        (out_province_poultry_request_buyers_excel, add_params({})),
        (chain_company_buyers_excel, add_params({})),
        (bar_chain_excel, add_params({'state': 'accepted'}, use_date1_date2=True)),
        (kill_house_total_transactions_wage_payid_admin_x_excel, add_params({})),
        (buy_outside_the_province_excel, add_params({})),
        (poultry_request_report_excel, add_params({}, use_start_end=True)),
        (transacion_out_request_excel, add_params({'type': 'poultry'}, use_date1_date2=True)),
        (from_allocation_to_distribution_excel, add_params({})),
        (login_user_excel, add_params({})),
        (city_operator_for_sub_sector_excel, add_params({'type': 'city'})),
        (vet_for_sub_sector_excel, add_params({'type': 'vet'})),
        (guild_for_sub_sector_excel, add_params({'type': 'guild'}, use_date1_date2=True)),
        (all_guilds_transaction_excel, add_params({})),
        # (detail_guilds_transaction_excel, add_params({}, use_date1_date2=True)),
        (management_hatching_excel, add_params({})),
        (user_without_role_excel, add_params({})),
        # (sub_section_of_cooperative_share_detail_with_date_excel, add_params({}, use_date1_date2=True)),
        (vet_for_sub_sector_with_date_excel, add_params({}, use_date1_date2=True)),
        (dashboard_monitoring_bar_and_killing_excel, add_params({})),
        (steward_allocation_excel, add_params({})),
        # (sevrence_kill_house_steward_allocation_excel, add_params({'type':'KillHouse'})),
        (free_sale_out_province_excel, add_params({'type': 1})),
        (steward_free_sale_out_province_excel, add_params({})),
        (total_steward_dashboard_excel, add_params({})),
        (detail_of_killing_and_warehouse_excel, add_params({})),
        (market_requests_excel, add_params({})),
        (return_province_request_excel, add_params({})),
        (guilds_without_allocation_excel, add_params({})),
        (hatching_excel, add_params({})),
        (archive_hatching_excel, add_params({})),
        (hatching_age_range_excel, add_params({})),
        # (poultry_monitoring_excel, add_params({})),
        # (poultry_hatching_prediction_chart_excel, add_params({})),
        (hatching_report_from_age_excel, add_params({'age1': 50, 'age2': 60})),
        # (poultry_hatching_prediction_excel, add_params({})),
        # (bar_difference_reques_excel, add_params({'state':'pending'})),
        (direct_purchase_excel, add_params({}, use_date1_date2=True)),
        (direct_purchase_archive_excel, add_params({}, use_date1_date2=True)),
        # (kill_house_assignment_information_excel, add_params({}, use_start_end=True)),
        (kill_house_user_excel, add_params({})),
        (bar_excel, add_params({}, use_start_end=True)),
        (kill_house_total_wage_excel, add_params({})),
        # (slaughterhouse_export_excel, add_params({}, use_date1_date2=True)),
        (export_kill_house_excel, add_params({})),
        (monitor_loads_excel, add_params({})),
        (kill_house_free_bar_excel, add_params({'type': 'all'}, use_date1_date2=True)),
        (comprehensive_report_of_the_slaughterhouse_excel, add_params({})),
        # (out_province_carcasses_buyer_kill_house_excel, add_params({})),
        # (kill_house_free_sale_bar_information_for_excel_excel, add_params({})),
        # (kill_house_free_sale_bar_information_excel, add_params({}, use_date1_date2=True)),
        (notentered_bars_for_kill_house_excel, add_params({})),
        (entered_bars_for_kill_house_excel, add_params({})),
        (kill_house_free_bar_entered_for_warehouse_excel, add_params({'type': 'all', 'bar_state': 'entered'})),
        (kill_house_free_bar_carcasses_for_warehouse_excel, add_params({'type': 'all', 'bar_state': 'carcasses'})),
        (steward_allocation_for_warehouse_excel, add_params({})),
        # (cold_house_excel, add_params({}, use_date1_date2=True)),
        (management_cold_house_excel, add_params({})),
        (non_receipt_request_excel, add_params({})),
        (return_kill_house_request_excel, add_params({})),
        (warehouse_archive_combined_excel, add_params({})),
    ]

    failed_functions = []

    for func, params in excel_functions:
        try:
            if params:
                query_string = '&'.join([f'{k}={v}' for k, v in params.items()])
                mock_request = MockRequest(query_string)
            else:
                mock_request = MockRequest()
            response = func(mock_request)
            if not response or not isinstance(response, HttpResponse):
                failed_functions.append(func.__name__)
        except Exception as e:
            failed_functions.append(func.__name__)

    if failed_functions:
        url = f'https://eitaayar.ir/api/{token}/sendMessage'
        message = f'❌ توابع اکسل که خطا داشتند:\n\n'
        message += f'❌ استان:{base_url_for_sms_report}\n\n'
        for func_name in failed_functions:

            message += f'• {func_name}\n'

        data = {
            'chat_id': 10046800,
            'text': message,
        }
        requests.post(url, data=data, verify=False)
