import datetime
import string
from io import BytesIO
from datetime import timedelta
import jdatetime
import openpyxl
from django.contrib.auth.models import Group
from django.db.models import Sum, F, Q, Count
from django.http import QueryDict, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from openpyxl import Workbook
from openpyxl.chart import Reference, BarChart, LineChart
from openpyxl.drawing.image import Image
from openpyxl.styles import PatternFill, Alignment, Font
from openpyxl.utils import get_column_letter
from django.db.models import Value
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny

from authentication.models import SystemUserProfile, City, Province
from general_urls import base_url_sms
from panel.KillHouse.serializers import KillHouseForProvinceWareHouseDashboardSerializer, \
    KillHouseRequestForBarManagementSerializer, TotalKillHouseWarehouseArchiveDashboardSerializer
from panel.ProvinceOperator.serializers import WarehouseArchiveSerializer
from panel.convert_date import convert_to_shamsi
from panel.filterset import KillRequestFilterSet, KillHouseRequestFilterSet, KillHouseFreeBarInformationFilterSet, \
    OutProvinceCarcassesBuyerFilterSet, StewardAllocationFilterSet, DashboardEnterLoadInformationFilterSet, \
    WarehouseArchiveFilterSet, KillHouseFilterSet
from panel.helper import build_query
from panel.helper_excel import shamsi_date, create_header, create_header_freez, \
    excel_description, create_value, Alignment_CELL, blue_fill, cell_color_changer, add_chart, convert_str_to_date
from panel.models import KillRequest, KillHouse, KillHouseVet, KillHousePercentage, ProvinceKillRequest, \
    KillHouseRequest, CityOperator, VetFarm, PoultryRequest, VetCheckRequest, KillHouseAssignmentInformation, Vet, \
    KillHouseFreeBarInformation, KillHouseOperator, Poultry, ChainAllocation, KillHouseWareHouse, StewardAllocation, \
    OutProvinceCarcassesBuyer, KillHouseFreeSaleBarInformation, WageType, RolesProducts, ColdHouse, Guilds, \
    WarehouseArchive
from django.db.models import Sum, F, Case, When, BooleanField


def direct_purchase_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
    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',
    ]
    kill_requests = KillRequest.objects.filter(
        trash=False,
        recive_date__date__gte=date1,
        recive_date__date__lte=date2, poultry__isnull=False,
        direct_buying_state__in=(
            'accepted', 'rejected', 'deleted', 'pending'),
        export_status=False
    ).order_by(
        Case(
            When(direct_buying_state='pending', then=Value(0)),
            default=Value(1)
        ),
        '-recive_date'  # مرتب‌سازی بر اساس تاریخ بعد از مرتب‌سازی بر اساس حالت
    )
    if request.GET['role'] == 'KillHouse':
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        kill_requests = kill_requests.filter(kill_house__kill_house_operator__user=user)
    else:
        kill_requests = kill_requests
    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=kill_requests
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=kill_requests)
                        kill_requests = ps.filter()

    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')
    create_header_freez(worksheet, excel_options, 1, 4, 5, height=18, width=20.1)
    create_header(worksheet, header_list, 4, 2, height=24, width=20.01)

    row = 3
    m = 1
    all_direct_buying_code = 0
    for kill_request in kill_requests:
        row += 1
        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.recive_date else '-'
        create_date = jdatetime.date.fromgregorian(
            day=kill_request.create_date.day,
            month=kill_request.create_date.month,
            year=kill_request.create_date.year
        ) if kill_request.create_date else '-'
        if kill_request.slaughter_house is not None:
            kill_place = kill_request.slaughter_house.name
        else:
            kill_place = kill_request.kill_house.name
        if kill_request.direct_buying_state == 'pending':
            state = 'درانتظار تایید'
        elif kill_request.direct_buying_state == 'rejected':
            state = 'رد شده'
        elif kill_request.direct_buying_state == 'deleted':
            state = 'حذف شده'
        else:
            state = 'تایید شده'
        cepacity = kill_request.kill_capacity if kill_request.kill_capacity else '-'
        if kill_request.input_direct_buying_code:
            direct_buying_code = kill_request.input_direct_buying_code
            all_direct_buying_code += 1
        else:
            direct_buying_code = '-'
        list1 = [
            m,
            str(create_date),
            str(recive_date),
            kill_request.kill_house.name,
            kill_request.kill_house.kill_house_operator.user.mobile,
            kill_place,
            kill_request.poultry.unit_name,
            kill_request.poultry.user.mobile,
            kill_request.chicken_breed,
            kill_request.previous_kill_capacity,
            cepacity,
            kill_request.Index_weight,
            kill_request.Index_weight * kill_request.previous_kill_capacity,
            direct_buying_code,
            str(shamsi_date(kill_request.payment_deadline_date, in_value=True)) if kill_request.payment_deadline_date else '-',
            state,

        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=row + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
        m += 1
    total_quantity = kill_requests.aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity') or 0
    total_wight = kill_requests.aggregate(
        total_quantity=Sum(F('Index_weight') * F('previous_kill_capacity'))).get(
        'total_quantity') or 0
    value_list = [
        m - 1,
        total_quantity,
        total_wight,
        all_direct_buying_code,
    ]
    for item in range(len(value_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=value_list[item])
        value = value_list[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)
    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 direct_purchase_archive_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
    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',
    ]
    kill_requests = KillRequest.objects.filter(
        trash=False,
        recive_date__date__gte=date1,
        recive_date__date__lte=date2, poultry__isnull=False,
        direct_buying_state__in=(
            'accepted', 'rejected', 'deleted')
    ).order_by(
        'recive_date')
    if request.GET['role'] == 'KillHouse':
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        kill_requests = kill_requests.filter(kill_house__kill_house_operator__user=user)
    else:
        kill_requests = kill_requests
    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=kill_requests
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=kill_requests)
                        kill_requests = ps.filter()

    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')
    create_header_freez(worksheet, excel_options, 1, 4, 5, height=18, width=20.1)
    create_header(worksheet, header_list, 4, 2, height=24, width=20.01)

    row = 3
    m = 1
    all_direct_buying_code = 0
    for kill_request in kill_requests:
        row += 1
        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.recive_date else '-'
        create_date = jdatetime.date.fromgregorian(
            day=kill_request.create_date.day,
            month=kill_request.create_date.month,
            year=kill_request.create_date.year
        ) if kill_request.create_date else '-'
        if kill_request.slaughter_house is not None:
            kill_place = kill_request.slaughter_house.name
        else:
            kill_place = kill_request.kill_house.name
        if kill_request.direct_buying_state == 'pending':
            state = 'درانتظار تایید'
        elif kill_request.direct_buying_state == 'rejected':
            state = 'رد شده'
        else:
            state = 'تایید شده'
        cepacity = kill_request.kill_capacity if kill_request.kill_capacity else '-'
        if kill_request.input_direct_buying_code:
            direct_buying_code = kill_request.input_direct_buying_code
            all_direct_buying_code += 1
        else:
            direct_buying_code = '-'
        list1 = [
            m,
            str(create_date),
            str(recive_date),
            kill_request.kill_house.name,
            kill_request.kill_house.kill_house_operator.user.mobile,
            kill_place,
            kill_request.poultry.unit_name,
            kill_request.poultry.user.mobile,
            kill_request.chicken_breed,
            kill_request.previous_kill_capacity,
            cepacity,
            kill_request.Index_weight,
            kill_request.Index_weight * kill_request.previous_kill_capacity,
            direct_buying_code,
            state,
        ]
        for item in range(len(list1)):
            cell = worksheet.cell(row=row + 1, column=item + 1, value=list1[item])
            cell.alignment = Alignment(horizontal='center')
        m += 1
    total_quantity = kill_requests.aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity') or 0
    total_wight = kill_requests.aggregate(
        total_quantity=Sum(F('Index_weight') * F('previous_kill_capacity'))).get(
        'total_quantity') or 0
    value_list = [
        m - 1,
        total_quantity,
        total_wight,
        all_direct_buying_code,
    ]
    for item in range(len(value_list)):
        cell = worksheet.cell(row=3, column=item + 4, value=value_list[item])
        value = value_list[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)

    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_assignment_information_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 = 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('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__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',
                                              'killer__name',
                                              'killhouse_user__type', 'killer').values('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',
                                                                                       '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',
                                                                                       )
    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__kill_house_operator__user=user)
            else:
                filtered_kill_reqs = filtered_kill_request
        else:
            filtered_kill_reqs = filtered_kill_request

    else:
        filtered_kill_reqs = filtered_kill_request
    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'))
    )

    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
    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') or 0
    accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity') or 0

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_quantity')).get(
        'total_quantity') or 0
    all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(
        total_quantity=Sum('vet_accepted_real_weight')).get(
        'total_quantity') or 0
    killer_exclusive = 0
    all_assignment_state_archive_state = 0
    len_weight_loss = 0
    all_state_ware_house_confirmation = 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')

            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 = 'کشتارکن'
            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'])
                killer_exclusive += 1
            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 = '-'

            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 = 'فعال'
                all_quantity += quantity
                all_weighte += weight
                all_real_quantity += real_quantity if real_quantity != '-' else 0
                all_net_weighte += net_weighte if net_weighte != '-' else 0

            if kill['assignment_state_archive'] == 'True':
                all_assignment_state_archive_state += 1
                assignment_state_archive_state = 'وارد شده است'
            else:
                assignment_state_archive_state = 'وارد نشده است'

            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 weight_loss > 0:
                len_weight_loss += 1
            if kill['ware_house_confirmation'] == True:
                state_ware_house_confirmation = 'ورود به انبار'
                all_state_ware_house_confirmation += 1

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

                state_delete,
                assignment_state_archive_state,
                state_ware_house_confirmation,
                ware_house_accepted_real_quantity,
                ware_house_accepted_real_weight,
                weight_loss,
                f'%{round(total_weight_loss, 2)}',
                f'%{weight_loss}',

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

                if isinstance(value, (int)):
                    if value != 0:
                        cell.number_format = '#,###'  # Apply general number format
                else:
                    cell.value = value  # Keep as text for other values
                if list1[40] == 'بار حذف شده':
                    cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
                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') or 0
    has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))
    all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('ware_house_accepted_real_quantity')).get(
        'total_quantity') or 0
    all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate(
        total_quantity=Sum('ware_house_accepted_real_weight')).get(
        'total_quantity', 0) or 0
    all_weight_loss = filtered_kill_reqs.aggregate(
        total_quantity=Sum('weight_loss')).get(
        'total_quantity', 0) or 0
    all_weight_loss = round(all_weight_loss / len_weight_loss, 2)
    value_header_list = [
        len(filtered_kill_reqs),
        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,
        all_assignment_state_archive_state,
        all_state_ware_house_confirmation,
        all_ware_house_accepted_real_quantity,
        all_ware_house_accepted_real_weight,
        all_weight_loss

    ]
    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)):
            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)):
            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,
        '',
        '',
        '',
        all_ware_house_accepted_real_quantity,
        all_ware_house_accepted_real_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)):
            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.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 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 kill_house_user_excel(request):
    kill_houses = KillHouse.objects.filter(trash=False).select_related('kill_house_operator__user').order_by('id')
    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')
        worksheet.row_dimensions[4].height = 25
        worksheet.column_dimensions[col_letter].width = 20.01
        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 = [
        'تعداد خریداران',
        'تعداد کشتارکن',
        'تعداد کشتارکن های عمومی',
        'تعداد کشتارکن های اختصاصی',
        'تعداد کل سفارشات',
        'حجم کل سفارشات',
        'وزن کل سفارشات',
        'تعداد بارها',
        'حجم بارها',
        'وزن بارها',
        'تعداد بار ورودی به انبار',
        'حجم ورودی به انبار',
        'وزن ورودی به انبار',

    ]
    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

    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        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['B1'] = f'مدیریت خریداران از تاریخ {from_date_1} تا {to_date_1}'
    else:
        worksheet['B1'] = f'مدیریت خریداران'

    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 = 4
    m = 1
    killer_type_public = 0
    killer_type_exclusive = 0
    killer = 0
    len_province_kill_request = 0
    all_province_weight = 0
    all_province_quantity = 0
    len_kill_request = 0
    all_kill_request_quantity = 0
    all_kill_request_weight = 0
    all_len_kill_req1 = 0
    all_ware_house_accepted_real_weight = 0
    all_ware_house_accepted_real_quantity = 0
    all_weight_loss = 0
    for kill_house in kill_houses:
        if 'date1' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            province_kill_request = ProvinceKillRequest.objects.filter(kill_request__recive_date__date__gte=date1,
                                                                       kill_request__recive_date__date__lte=date2,
                                                                       trash=False, return_to_province=False,
                                                                       state__in=('accepted', 'pending'),
                                                                       killhouse_user=kill_house).select_related(
                'province_request__poultry_request') \
                .only('main_quantity', 'province_request__poultry_request__Index_weight')

            kill_request = KillHouseRequest.objects.filter(Q(killhouse_user=kill_house) | Q(killer=kill_house),
                                                           trash=False
                                                           , kill_request__recive_date__date__gte=date1,
                                                           kill_request__recive_date__date__lte=date2).only(
                'accepted_assignment_real_quantity',
                'accepted_assignment_real_weight')
        else:
            province_kill_request = ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                                       state__in=('accepted', 'pending'),
                                                                       killhouse_user=kill_house).select_related(
                'province_request__poultry_request') \
                .only('main_quantity', 'province_request__poultry_request__Index_weight')

            kill_request = KillHouseRequest.objects.filter(Q(killhouse_user=kill_house) | Q(killer=kill_house),
                                                           trash=False
                                                           ).only('accepted_assignment_real_quantity',
                                                                  'accepted_assignment_real_weight')

        percentage = KillHousePercentage.objects.filter(kill_house=kill_house).select_related('kill_house_for_killer',
                                                                                              'kill_house').first()
        if percentage:
            if percentage.kill_house_for_killer != None:
                place = percentage.kill_house_for_killer.name
            else:
                place = percentage.kill_house.name
        else:
            place = kill_house.name
        if kill_house.killer == True:
            killer += 1
            type = 'کشتارکن'
            if kill_house.type == 'public':
                killer_type = f'{type} عمومی '
                killer_type_public += 1
            else:
                killer_type = f' {type}  اختصاصی ({place})'
                killer_type_exclusive += 1

        else:
            type = 'کشتارگاه'
            killer_type = f'{type} '

        all_recive_date = set(kill_request.values_list('kill_request__recive_date__date', flat=True))
        kill_house_vet = KillHouseVet.objects.filter(kill_house=kill_house).first()

        if kill_house_vet:
            vet_fullname = kill_house_vet.vet.user.fullname
            vet_mobile = kill_house_vet.vet.user.mobile
        else:
            vet_fullname = '-'
            vet_mobile = '-'

        len_province_kill_request += len(province_kill_request)
        len_kill_request += len(kill_request)
        province_quantity = province_kill_request.aggregate(
            total=Sum('main_quantity'))[
                                'total'] or 0
        province_weight = province_kill_request.aggregate(
            total=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight')))[
                              'total'] or 0
        all_province_weight += int(province_weight)
        all_province_quantity += province_quantity
        kill_request_quantity = kill_request.aggregate(
            total=Sum('accepted_real_quantity'))[
                                    'total'] or 0
        kill_request_weight = kill_request.aggregate(
            total=Sum('accepted_real_weight'))[
                                  'total'] or 0

        kill_req_ware_house_confirmation = kill_request.filter(ware_house_confirmation=True, killhouse_user=kill_house)
        ware_house_accepted_real_quantity = kill_req_ware_house_confirmation.aggregate(
            total_quantity=Sum('ware_house_accepted_real_quantity')).get(
            'total_quantity') or 0

        ware_house_accepted_real_weight = kill_req_ware_house_confirmation.aggregate(
            total_quantity=Sum('ware_house_accepted_real_weight')).get(
            'total_quantity') or 0
        weight_loss1 = kill_req_ware_house_confirmation.aggregate(
            total_quantity=Sum('weight_loss')).get(
            'total_quantity') or 0
        weight_loss = weight_loss1 / len(kill_req_ware_house_confirmation) if len(
            kill_req_ware_house_confirmation) > 0 else 0

        all_len_kill_req1 += len(kill_req_ware_house_confirmation)

        all_ware_house_accepted_real_weight += ware_house_accepted_real_weight
        all_ware_house_accepted_real_quantity += ware_house_accepted_real_quantity
        all_weight_loss += int(weight_loss)

        all_kill_request_quantity += kill_request_quantity
        all_kill_request_weight += int(kill_request_weight)
        link = f'https://{base_url_sms}.rasadyaar.ir/pay/k{kill_house.kill_house_operator.user.user_gate_way_id}'
        hasnt_code = len(
            kill_request.filter(Q(assignment_state_archive='True') | Q(vet_state='accepted'),
                                clearance_code__isnull=True))
        percent_hasnt_code = round(hasnt_code * 100 / len(kill_request), 2) if len(
            kill_request) > 0 else 0
        has_code = len(
            kill_request.filter(vet_state='pending', assignment_state_archive='pending', clearance_code__isnull=False))
        percent_has_code = round(has_code * 100 / len(kill_request), 2) if len(
            kill_request) > 0 else 0

        has_assignment = len(
            kill_request.filter(Q(vet_state='accepted') | Q(assignment_state_archive='True')))
        percent_has_assignment = round(has_assignment * 100 / len(kill_request), 2) if len(
            kill_request) > 0 else 0
        hasnt_assignment = len(
            kill_request.filter(assignment_state_archive='pending', vet_state='pending'))
        percent_hasnt_assignment = round(hasnt_assignment * 100 / len(kill_request), 2) if len(
            kill_request) > 0 else 0
        evaluated_bar = len(
            kill_request.filter(bar_document_status__isnull=False))
        percent_evaluated_bar = round(evaluated_bar * 100 / has_assignment, 2) if has_assignment > 0 else 0

        accepeted_bar = len(
            kill_request.filter(bar_document_status__title='تایید شده'))
        percent_accepeted_bar = round(accepeted_bar * 100 / evaluated_bar, 2) if evaluated_bar > 0 else 0
        diffrent_bar = len(
            kill_request.filter(bar_document_status__title='مغایرت دارد'))
        percent_diffrent_bar = round(diffrent_bar * 100 / evaluated_bar, 2) if evaluated_bar > 0 else 0
        no_quality = len(
            kill_request.filter(bar_document_status__title='فاقد کیفیت'))
        percent_no_quality = round(no_quality * 100 / evaluated_bar, 2) if evaluated_bar > 0 else 0
        accepted_low_quality = len(
            kill_request.filter(bar_document_status__title='تایید شده بدون کیفیت'))
        percent_low_quality = round(accepted_low_quality * 100 / evaluated_bar, 2) if evaluated_bar > 0 else 0
        hand_write = len(
            kill_request.filter(bar_document_status__title='دست نویس'))
        percent_hand_write = round(hand_write * 100 / evaluated_bar, 2) if evaluated_bar > 0 else 0
        cancled = len(
            kill_request.filter(bar_document_status__title='باطل شده'))
        percent_cancled = round(cancled * 100 / evaluated_bar, 2) if evaluated_bar > 0 else 0
        list1 = [
            m,
            killer_type,
            kill_house.name,
            kill_house.kill_house_operator.user.fullname,
            kill_house.kill_house_operator.user.mobile,
            vet_fullname,
            vet_mobile,
            kill_house.kill_house_operator.user.city.name,
            place,
            len(province_kill_request),
            province_quantity,
            int(province_weight),
            len(kill_request),
            kill_request_quantity,
            int(kill_request_weight),
            round(kill_request_weight / kill_request_quantity, 1) if kill_request_weight > 0 else 0,
            len(kill_req_ware_house_confirmation),
            ware_house_accepted_real_quantity,
            int(ware_house_accepted_real_weight),
            f"{int(weight_loss)}%",
            link,
            hasnt_code,
            f'%{percent_hasnt_code}',
            has_code,
            f'%{percent_has_code}',
            has_assignment,
            f'%{percent_has_assignment}',
            evaluated_bar,
            f'%{percent_evaluated_bar}',

            accepeted_bar,
            f'%{percent_accepeted_bar}',
            diffrent_bar,
            f'%{percent_diffrent_bar}',
            no_quality,
            f'%{percent_no_quality}',
            accepted_low_quality,
            f'%{percent_low_quality}',
            hand_write,
            f'%{percent_hand_write}',
            cancled,
            f'%{percent_cancled}',
            hasnt_assignment,
            f'%{percent_hasnt_assignment}',
            (int(kill_request_weight / len(all_recive_date)) if len(all_recive_date) > 0 else 0),
            (int(kill_request_quantity / len(all_recive_date)) if len(all_recive_date) > 0 else 0),

        ]
        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)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            worksheet.column_dimensions[get_column_letter(item + 1)].width = 17.01

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

    # last_age=sorted(reversed(all_age))

    value_header_list2 = [
        len(kill_houses),
        killer,
        killer_type_public,
        killer_type_exclusive,
        len_province_kill_request,
        all_province_quantity,
        all_province_weight,
        len_kill_request,
        all_kill_request_quantity,
        all_kill_request_weight,
        all_len_kill_req1,
        all_ware_house_accepted_real_quantity,
        all_ware_house_accepted_real_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', vertical='center', wrap_text=True)
        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 bar_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 = 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:
        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if value != 'undefined' and value.strip():
                filtered_kill_reqs = filtered_kill_reqs.filter(
                    build_query(DashboardEnterLoadInformationFilterSet, value)
                )
    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')

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

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    if request.GET['role'] == 'KillHouse':
        name = filtered_kill_reqs.first()['killhouse_user__name']
        response[
            'Content-Disposition'] = f'attachment; filename="مدیریت بارهای کشتارگاه {name}.xlsx"'.encode(
            'utf-8')
    elif 'state' in request.GET:
        if request.GET['state'] == 'bar_pending':
            response[
                'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تکمیل نشده.xlsx"'.encode(
                'utf-8')
        else:
            response[
                'Content-Disposition'] = f'attachment; filename="مدیریت بارهای تکمیل شده.xlsx"'.encode(
                'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="مدیریت بارها.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def bar_excel_trash_true(request):
    filterset_class = KillHouseRequestFilterSet
    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_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(
        kill_request__recive_date__date__gte=date1,
        kill_request__recive_date__date__lte=date2,
        trash=True, temporary_trash=False, temporary_deleted=False).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', 'traffic_code',
                                              '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', 'message',
                                              'bar_remover', 'province_request__poultry_request__freezing',
                                              'killer__kill_house_operator__user__mobile',
                                              'killer__name',
                                              'killhouse_user__type',
                                              'killer', ).values('province_kill_request__kill_house_price',
                                                                 'killhouse_user',
                                                                 'province_request__poultry_request__freezing',
                                                                 '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',
                                                                 'message',
                                                                 'bar_remover',
                                                                 'traffic_code',
                                                                 'killer__kill_house_operator__user__mobile',
                                                                 'killer__name',
                                                                 'killhouse_user__type',
                                                                 'killer',

                                                                 )
    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__address__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__kill_house_operator__user=user)
            else:
                filtered_kill_reqs = filtered_kill_request
        else:
            filtered_kill_reqs = filtered_kill_request
    else:
        filtered_kill_reqs = filtered_kill_request
    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 = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'کشتار',
        'کدسفارش مرغدار',
        'مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        ' نژاد',
        'دامپزشک فارم',
        'تلفن دامپزشک فارم',
        ' ماهیت خریدار',
        'خریدار',
        ' تلفن خریدار',
        ' آدرس ',
        'کشتارکن اختصاصی',
        'تلفن کشتارکن اختصاصی',
        ' محل کشتار ',
        'دامپزشک کشتارگاه ',
        ' تلفن دامپزشک کشتارگاه ',
        'راننده',
        'موبایل راننده',
        'نوع خودرو',
        'کد بهداشتی حمل و نقل',
        'تعداد قطعه',
        'وزن بار',
        'کد رهگیری سامانه قرنطینه',
        'تعداد وارد شده در قرنطینه',
        'تاریخ حذف',
        'حذف کننده',
        'دلیل حذف',

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

    worksheet['B1'] = f'مدیریت بارهای حذف شده'
    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')
    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 = 3
    m = 1
    all_quantity = 0
    all_weighte = 0

    all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    killer_exclusive = 0
    if filtered_kill_reqs:
        for kill in filtered_kill_reqs:

            l += 1
            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()

            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 = 'کشتارگاه'

            if kill.get('kill_request__slaughter_house') is not None:
                kill_place = kill.get('kill_request__slaughter_house__name')
            else:
                kill_place = '-'

            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 '-'
            if kill['bar_remover'] is not None:
                date_remover = kill['bar_remover']['date'].split('-')
                bar_remover_date = jdatetime.date.fromgregorian(
                    day=int(date_remover[2]),
                    month=int(date_remover[1]),
                    year=int(date_remover[0])
                ) if date_remover else '-'
            else:
                bar_remover_date = '-'
            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'),
                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,
                str(bar_remover_date),
                kill['bar_remover']['full_name'] if kill['bar_remover'] != None else '-',
                kill['message'] if kill['message'] != 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)):
                    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)
    value_header_list = [
        len(filtered_kill_reqs),
        killer_exclusive,
        all_quantity,
        all_weighte,

    ]
    for item in range(len(value_header_list)):
        cell = worksheet.cell(row=3, column=item + 6, value=value_header_list[item])
        value = value_header_list[item]
        # Check if the value is a number before formatting
        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)
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        all_kill_request_quantity,
        all_weighte,
        '',
        '',
        '',
        '',
        '',

    ]
    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 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 kill_house_total_wage_excel(request):
    kill_house = KillHouse.objects.filter(trash=False)
    sheet_names2 = [
        'اطلاعات کلی',
        'بارهای روزانه',
        'تخصیص روزانه',
        'مرغ زنده',
        'لاشه',
    ]

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

    kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_house,

                                                                          archive_wage=False,
                                                                          trash=False).order_by('id')

    filtered_kill_reqs = KillHouseRequest.objects.filter(
        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('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__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',
                                              'killer__name',
                                              'killhouse_user__type', 'killer').values('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',
                                                                                       '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',
                                                                                       )

    province_kill_request = ProvinceKillRequest.objects.filter(
        state__in=('pending', 'accepted'),
        return_to_province=False,
        archive_wage=False,
        first_car_allocated_quantity=0,
        trash=False).order_by(
        'kill_request__recive_date')

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

        if sheet_name == 'بارهای روزانه':
            if 'date1' in request.GET:
                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
                filtered_kill_reqs = filtered_kill_reqs.filter(kill_request__recive_date__date__gte=date1,
                                                               kill_request__recive_date__date__lte=date2)
            else:
                filtered_kill_reqs = filtered_kill_reqs

            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'] or 0
            total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0
            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)

            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}'
            if 'date1' in request.GET:
                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
                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['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') or 0
            accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity') or 0

            all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity') or 0
            killer_exclusive = 0
            all_assignment_state_archive_state = 0
            len_weight_loss = 0
            all_state_ware_house_confirmation = 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')

                    else:
                        quantity = '-'
                    date_of_poultry_request = '-'
                    send_date = kill.get('province_request__poultry_request__send_date')
                    if send_date:
                        date_of_poultry_request = jdatetime.date.fromgregorian(
                            day=send_date.day,
                            month=send_date.month,
                            year=send_date.year
                        )
                    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'])
                        killer_exclusive += 1
                    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 = int(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 = '-'
                    weight = 0
                    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 '-'
                    if kill.get(
                            'province_kill_request__province_request__poultry_request__Index_weight'):
                        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 = 'ادغام'

                    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 = '-'
                    if kill.get('province_request__poultry_request__send_date') and kill.get(
                            'province_request__poultry_request__hatching__date'):
                        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 = 'فعال'
                        all_quantity += quantity
                        all_weighte += weight
                        all_real_quantity += real_quantity if real_quantity != '-' else 0
                        all_net_weighte += net_weighte if net_weighte != '-' else 0

                    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 weight_loss > 0:
                        len_weight_loss += 1
                    if kill['ware_house_confirmation'] == True:
                        state_ware_house_confirmation = 'ورود به انبار'
                        all_state_ware_house_confirmation += 1

                    else:
                        state_ware_house_confirmation = '-'
                    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'],
                        int(kill['accepted_real_weight']),
                        state_delete,
                        kill['document_status'] if kill['document_status'] else '-',
                        state_ware_house_confirmation,
                        ware_house_accepted_real_quantity,
                        int(ware_house_accepted_real_weight),
                        f'%{weight_loss}',

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

                        if isinstance(value, (int)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values
                        if list1[40] == 'بار حذف شده':
                            cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
                        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') or 0
            has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))
            all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight')).get(
                'total_quantity') or 0
            all_weight_loss = filtered_kill_reqs.aggregate(
                total_quantity=Sum('weight_loss')).get(
                'total_quantity') or 0
            all_weight_loss = round(int(all_weight_loss) / len_weight_loss, 2) if len_weight_loss > 0 else 0
            value_header_list = [
                len(filtered_kill_reqs),
                killer_exclusive,
                all_quantity,
                int(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,
                int(all_vet_accepted_real_weight),
                len(bar_complete),
                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_state_ware_house_confirmation,
                all_ware_house_accepted_real_quantity,
                int(all_ware_house_accepted_real_weight),
                f'%{all_weight_loss}'

            ]
            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)):
                    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,
                int(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)):
                    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,
                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),
                f'%{all_weight_loss}'

            ]
            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)):
                    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.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'تخصیص روزانه':
            worksheet['H3'] = 'در این قسمت تخصیصات فاقد بار نمایش داده میشود'
            merge_range1 = 'H3:K3'
            worksheet.merge_cells(merge_range1)
            worksheet['H3'].font = Font(color="C00000", bold=True)
            worksheet['H3'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            if 'date1' in request.GET:
                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
                province_kill_request = province_kill_request.filter(
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                ).order_by(
                    'kill_request__recive_date')
            else:
                province_kill_request = province_kill_request

            header_list = [
                'تعداد سفارشات',
                'تعداد کل',
                'وزن کل',
                'جمع کل سهم',
            ]
            for col_num, option in enumerate(header_list, 3):
                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="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[3].height = 20.8

            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)
            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
            l = 6
            m = 1
            for province_kill in province_kill_request:

                kill_date = jdatetime.date.fromgregorian(
                    year=province_kill.province_request.poultry_request.send_date.year,
                    month=province_kill.province_request.poultry_request.send_date.month,
                    day=province_kill.province_request.poultry_request.send_date.day
                ).strftime('%Y-%m-%d')
                reversed_date1 = reversed(kill_date.split("-"))
                separate = "-"
                kill_date_1 = separate.join(reversed_date1)

                if province_kill.kill_request.slaughter_house is not None:
                    kill_place = province_kill.kill_request.slaughter_house.name
                else:
                    kill_place = province_kill.kill_request.kill_house.name

                total_amount = province_kill.total_wage_amount

                list1 = [
                    m,
                    province_kill.province_request.poultry_request.order_code,
                    province_kill.province_request.poultry_request.poultry.unit_name,
                    province_kill.province_request.poultry_request.poultry.user.mobile,
                    province_kill.province_request.poultry_request.poultry.address.city.name,
                    str(kill_date_1),
                    kill_place,
                    province_kill.province_request.poultry_request.hatching.chicken_breed,
                    province_kill.total_killed_quantity,
                    province_kill.total_killed_weight,
                    province_kill.province_request.poultry_request.Index_weight,
                    province_kill.wage,
                    total_amount,

                ]
                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
                m += 1
            total_weight = \
                province_kill_request.aggregate(total=Sum('total_killed_weight'))[
                    'total'] or 0
            total_killed_quantity = \
                province_kill_request.aggregate(total=Sum('total_killed_quantity'))[
                    'total'] or 0
            total_wage_amount = \
                province_kill_request.aggregate(total=Sum('total_wage_amount'))[
                    'total'] or 0
            value_list = [
                m - 1,
                total_killed_quantity,
                total_weight,
                total_wage_amount,

            ]
            for item in range(len(value_list)):
                cell = worksheet.cell(row=4, column=item + 3, value=value_list[item])
                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

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')
        elif sheet_name == 'مرغ زنده':
            # type = request.GET['type']

            if 'date1' in request.GET:
                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_free_bar_info = kill_house_free_bar_info.filter(date__date__gte=date1,
                                                                           date__date__lte=date2, buy_type='live', )
            else:
                kill_house_free_bar_info = kill_house_free_bar_info.filter(buy_type='live')
            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 = [
                'تعداد خریداران',
                'تعداد کل',
                'وزن کل',
                'مبلغ کل',
            ]
            excel_options = [
                'ردیف',
                'نام خریدار',
                'تلفن خریدار',
                'نام فروشنده',
                'تلفن فروشنده',
                'شهر',
                'تعداد',
                'وزن',
                'تعرفه',
                'مبلغ کل',
            ]
            for col_num, option in enumerate(header_list, 4):
                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="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[3].height = 20.8

            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
            l = 6
            m = 1
            if kill_house_free_bar_info:
                for kill in kill_house_free_bar_info:

                    list1 = [
                        m,
                        kill.kill_house.name,
                        kill.kill_house.kill_house_operator.user.mobile,
                        kill.poultry_name,
                        kill.poultry_mobile,
                        kill.city,
                        kill.quantity,
                        kill.live_weight,
                        kill.wage,
                        kill.total_wage_amount,
                    ]
                    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
                    m += 1
            total_quantity = \
                kill_house_free_bar_info.aggregate(total=Sum('quantity'))[
                    'total'] or 0
            total_weight = \
                kill_house_free_bar_info.aggregate(total=Sum('live_weight'))[
                    'total'] or 0
            total_wage_amount = \
                kill_house_free_bar_info.aggregate(total=Sum('total_wage_amount'))[
                    'total'] or 0
            value_list = [
                m - 1,
                total_quantity,
                total_weight,
                total_wage_amount,

            ]
            for item in range(len(value_list)):
                cell = worksheet.cell(row=4, column=item + 4, value=value_list[item])
                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

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='center')
        elif sheet_name == 'لاشه':

            if 'date1' in request.GET:
                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_free_bar_info2 = kill_house_free_bar_info.filter(date__date__gte=date1,
                                                                            date__date__lte=date2, buy_type='carcass')
            else:
                kill_house_free_bar_info2 = kill_house_free_bar_info.filter(buy_type='carcass')
            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 = [
                'تعداد خریداران',
                'تعداد کل',
                'وزن کل',
                'مبلغ کل',
            ]
            excel_options = [
                'ردیف',
                'نام خریدار',
                'تلفن خریدار',
                'نام فروشنده',
                'تلفن فروشنده',
                'شهر',
                'تعداد',
                'وزن',
                'تعرفه',
                'مبلغ کل',
            ]
            for col_num, option in enumerate(header_list, 4):
                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="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[3].height = 20.8

            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
            l = 6
            m = 1
            if kill_house_free_bar_info2:
                for kill in kill_house_free_bar_info2:

                    list1 = [
                        m,
                        kill.kill_house.name,
                        kill.kill_house.kill_house_operator.user.mobile,
                        kill.poultry_name,
                        kill.poultry_mobile,
                        kill.city,
                        kill.quantity,
                        kill.live_weight,
                        kill.wage,
                        kill.total_wage_amount,
                    ]
                    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
                    m += 1
            total_quantity = \
                kill_house_free_bar_info2.aggregate(total=Sum('quantity'))[
                    'total'] or 0
            total_weight = \
                kill_house_free_bar_info2.aggregate(total=Sum('live_weight'))[
                    'total'] or 0
            total_wage_amount = \
                kill_house_free_bar_info2.aggregate(total=Sum('total_wage_amount'))[
                    'total'] or 0
            value_list = [
                m - 1,
                total_quantity,
                total_weight,
                total_wage_amount,

            ]
            for item in range(len(value_list)):
                cell = worksheet.cell(row=4, column=item + 4, value=value_list[item])
                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

                worksheet.row_dimensions[l + 1].height = 20
                cell.alignment = Alignment(horizontal='center', vertical='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 slaughterhouse_export_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 = KillHouseRequest.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 = KillHouseRequest.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 = KillRequest.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 export_kill_house_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
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    if request.GET['role'] == 'KillHouse':
        kill_house_operator = KillHouseOperator.objects.get(user=user, trash=False)
        kill_house = KillHouse.objects.filter(kill_house_operator=kill_house_operator, trash=False)

        querysets = KillRequest.objects.filter(kill_house__in=kill_house, recive_date__date__gte=date1,
                                               recive_date__date__lte=date2, poultry__isnull=False,
                                               export_status=True,
                                               ).order_by(
            'recive_date')
    else:
        querysets = KillRequest.objects.filter(kill_house__system_address__province=user.province,
                                               recive_date__date__gte=date1,
                                               recive_date__date__lte=date2, poultry__isnull=False,
                                               export_status=True,

                                               ).order_by(
            'recive_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)

    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} تا {to_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_accepted = 0
    all_rejected = 0
    all_deleted = 0
    all_weight = 0
    accepted_weight = 0
    deleted_weight = 0
    rejected_weight = 0
    for kill in querysets:

        l += 1
        create_date = jdatetime.date.fromgregorian(
            day=kill.create_date.day,
            month=kill.create_date.month,
            year=kill.create_date.year
        )
        kill_date = jdatetime.date.fromgregorian(
            day=kill.recive_date.day,
            month=kill.recive_date.month,
            year=kill.recive_date.year
        )
        if kill.accept_reject_date is not None:
            del_accept_date = jdatetime.date.fromgregorian(
                day=kill.accept_reject_date.day,
                month=kill.accept_reject_date.month,
                year=kill.accept_reject_date.year
            )
        else:
            del_accept_date = '-'

        if kill.slaughter_house is not None:
            kill_place = kill.slaughter_house.name
        else:
            kill_place = kill.kill_house.name
        Index_weight = round(kill.Index_weight, 1)

        if kill.export_state == 'accepted':
            type = 'تایید شده'
            all_accepted += 1
            accepted_weight += int(kill.kill_capacity * Index_weight)
        elif kill.export_state == 'rejected':
            type = 'رد شده'
            all_rejected += 1
            rejected_weight += int(kill.kill_capacity * Index_weight)
        elif kill.export_state == 'deleted':
            type = 'حذف شده'
            all_deleted += 1
            deleted_weight += int(kill.kill_capacity * Index_weight)
        else:
            type = 'در انتظار تایید'
        all_weight += int(kill.kill_capacity * Index_weight)
        list1 = [
            m,
            str(create_date),
            str(kill_date),
            kill.kill_house.name,
            kill.kill_house.kill_house_operator.user.mobile,
            kill_place,
            kill.export_country,
            kill.poultry.unit_name,
            kill.poultry.user.mobile,
            kill.kill_capacity,
            Index_weight,
            int(kill.kill_capacity * Index_weight),
            kill.direct_buying_code if kill.direct_buying_code else '-',
            type,
            str(del_accept_date),
            kill.direct_buying_message if kill.direct_buying_message 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)):
                if value != 0:
                    cell.number_format = '#,###'  # Apply general number format
            else:
                cell.value = value  # Keep as text for other values
            if list1[13] == 'رد شده':
                cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
            if list1[13] == 'حذف شده':
                cell.fill = PatternFill(start_color="F7A49B", fill_type="solid")

            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')
            )
            cell.alignment = Alignment(horizontal='center')

    export_quantity = querysets.aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity') or 0

    export_accepted_quantity = querysets.filter(export_state='accepted').aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity') or 0
    export_rejected_quantity = querysets.filter(export_state='rejected').aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity') or 0
    export_deleted_quantity = querysets.filter(export_state='deleted').aggregate(
        total_quantity=Sum('kill_capacity')).get(
        'total_quantity') or 0

    value_header_list = [
        all_accepted,
        export_accepted_quantity,
        accepted_weight,

        all_rejected,
        export_rejected_quantity,
        rejected_weight,

        all_deleted,
        export_deleted_quantity,
        deleted_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 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        export_quantity,
        '',
        all_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="گزارش درخواست های صادرات.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def monitor_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()
    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',
    ]

    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)

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

    ]

    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]

    excel_options1 = {
        'آمار کلی': [],
        'مدیریت بارها': [],
        'بارهای حذف شده': [],
        'فروش به خارج از استان': [],
        'بارهای زنجیره': [],
        'خرید زنده خارج از استان': [],
        'خرید لاشه خارج از استان': [],

    }

    output = BytesIO()
    workbook = Workbook()
    for name, options in excel_options1.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=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')

        if sheet_name == 'آمار کلی':
            filtered_kill_request = KillHouseRequest.objects.filter(
                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('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__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__kill_house_price',
                                                      'price',
                                                      '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',
                                                      'killer__name',
                                                      'killhouse_user__type', 'killer').values(
                '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',
                'province_kill_request__kill_house_price',
                'price',
                'killer',
                'province_request__poultry_request__Index_weight',
            )

            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__kill_house_operator__user=user)
            else:
                filtered_kill_reqs = filtered_kill_request

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

            elif request.GET['role'] == 'KillHouseVet':
                kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
                kill_house = kill_house_vets.values_list('kill_house', flat=True).distinct()

            else:
                kill_house = KillHouse.objects.filter(system_address__province=user.province, 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
            worksheet['H1'] = f'اطلاعات کل بارها'
            worksheet['H1'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['H1'].font = Font(color='FF0000', size=11)
            merge_range1 = 'H1:L1'
            worksheet.merge_cells(merge_range1)

            worksheet['H6'] = f'گزارش بارهای حذف شده'
            merge_range1 = 'H6:L6'
            worksheet.merge_cells(merge_range1)
            worksheet['H6'].font = Font(color='FF0000', size=11)
            worksheet['H6'].alignment = Alignment(horizontal='center', vertical='center')

            worksheet['H11'] = f'گزارش فروش به خارج از استان'
            worksheet['H11'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['H11'].font = Font(color='FF0000', size=11)
            merge_range1 = 'H11:L11'
            worksheet.merge_cells(merge_range1)

            worksheet['H16'] = f'گزارش کشتار شرکت های زنجیره ای'
            worksheet['H16'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['H16'].font = Font(color='FF0000', size=11)
            merge_range1 = 'H16:L16'
            worksheet.merge_cells(merge_range1)

            worksheet['H21'] = f'گزارش خرید زنده خارج از استان'
            worksheet['H21'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['H21'].font = Font(color='FF0000', size=11)
            merge_range1 = 'H21:L21'
            worksheet.merge_cells(merge_range1)

            worksheet['H26'] = f'گزارش خرید لاشه خارج از استان'
            worksheet['H26'].alignment = Alignment(horizontal='center', vertical='center')
            worksheet['H26'].font = Font(color='FF0000', size=11)
            merge_range1 = 'H26:L26'
            worksheet.merge_cells(merge_range1)

            for col_num, option in enumerate(header_list, 9):
                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="0070C0", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
                worksheet.column_dimensions[col_letter].width = 13
                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_list2, 6):
                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="00B050", fill_type="solid")
                cell.font = Font(size=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[2].height = 20.8
                worksheet.column_dimensions[col_letter].width = 13
                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, 9):
                col_letter = get_column_letter(col_num)
                cell = worksheet.cell(row=7, 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[7].height = 20.8
                worksheet.column_dimensions[col_letter].width = 13
                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_list2, 6):
                col_letter = get_column_letter(col_num)

                cell = worksheet.cell(row=7, 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[7].height = 20.8
                worksheet.column_dimensions[col_letter].width = 13
                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_reqs1 = filtered_kill_reqs.filter(trash=False)
            poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs1.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'] or 0
            total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0
            all_age = []
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_weighte1 = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs1.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs1.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity') or 0
            accepted_real_wight = filtered_kill_reqs1.aggregate(total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity') or 0

            all_quantity = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_quantity = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_weight = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity') or 0
            killer_exclusive = 0
            len_weight_loss = 0
            all_state_ware_house_confirmation = filtered_kill_reqs1.aggregate(
                total_quantity=Count('id', filter=Q(ware_house_confirmation=True))).get(
                'total_quantity') or 0
            if filtered_kill_reqs1:
                for kill in filtered_kill_reqs1:
                    if kill.get('killer') != None:
                        killer_exclusive += 1
                    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)
                    weight = kill.get('quantity') * kill.get(
                        'province_request__poultry_request__Index_weight')
                    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 = int(assignment.get('net_weight'))
                        real_quantity = assignment.get('real_quantity')

                        all_weighte += weight
                        all_real_quantity += real_quantity if real_quantity != '-' else 0
                        all_net_weighte += net_weighte if net_weighte != '-' else 0
                    all_weighte1 += weight
            all_age1 = sorted(all_age)
            has_code = len(filtered_kill_reqs1.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs1.aggregate(total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity') or 0
            has_qarantine = len(filtered_kill_reqs1.filter(quarantine_quantity__isnull=False))
            all_ware_house_accepted_real_quantity = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity', filter=Q(ware_house_confirmation=True))).get(
                'total_quantity') or 0
            all_ware_house_accepted_real_weight = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight', filter=Q(ware_house_confirmation=True))).get(
                'total_quantity', 0) or 0
            all_weight_loss = filtered_kill_reqs1.aggregate(
                total_quantity=Sum('weight_loss', filter=Q(ware_house_confirmation=True))).get(
                'total_quantity', 0) or 0
            all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation,
                                    2) if all_state_ware_house_confirmation > 0 else 0
            has_code1 = filtered_kill_reqs1.filter(clearance_code__isnull=False)
            all_quarantine_quantity_has_code = has_code1.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            hasnt_code = filtered_kill_reqs1.filter(clearance_code__isnull=True)
            all_quarantine_quantity_hasnt_code = hasnt_code.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            difference_bar = len(filtered_kill_reqs1.filter(
                Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity'))))

            header_list = [
                'تعداد بارهای تایید شده',
                'مجموع تعداد قطعه بارها',
                'مجموع وزن بارها',
                'کمترین سن مرغ',
                'بیشترین سن مرغ',
                'تعداد بارهای دارای کد قرنطینه',

            ]
            for col_num, option in enumerate(header_list, 8):
                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=9, bold=True, color='D9FFFFFF')
                worksheet.row_dimensions[12].height = 20.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')
                )

            value_header_list = [
                len(filtered_kill_reqs1),
                killer_exclusive,
                all_quantity,
                int(all_weighte1),
                round(all_weighte1 / all_quantity, 1) if all_weighte1 > 0 and all_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_code),
                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 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}'

            ]
            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)):
                    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,
                int(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)):
                    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)

            filtered_kill_reqs2 = filtered_kill_reqs.filter(trash=True)
            poultry_request = (PoultryRequest.objects.filter(trash=False, pk__in=filtered_kill_reqs2.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'] or 0
            total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0
            all_age = []
            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            all_vet_state_accepted = len(
                filtered_kill_reqs2.filter(vet_state='accepted'))
            bar_complete = filtered_kill_reqs2.filter(assignment_state_archive='True')
            accepted_real_quantity = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity') or 0
            accepted_real_wight = filtered_kill_reqs2.aggregate(total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity') or 0

            all_quantity = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_quantity = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_weight = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity') or 0
            killer_exclusive = 0
            len_weight_loss = 0
            all_state_ware_house_confirmation = 0
            if filtered_kill_reqs2:
                for kill in filtered_kill_reqs2:
                    if kill.get('killer') != None:
                        killer_exclusive += 1
                    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)
                    weight = int(kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight'))
                    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 = int(assignment.get('net_weight'))
                        real_quantity = assignment.get('real_quantity')

                        all_weighte += weight
                        all_real_quantity += real_quantity if real_quantity != '-' else 0
                        all_net_weighte += net_weighte if net_weighte != '-' else 0

            all_age1 = sorted(all_age)
            has_code = len(filtered_kill_reqs2.filter(clearance_code__isnull=False))
            all_quarantine_quantity = filtered_kill_reqs2.aggregate(total_quantity=Sum('quarantine_quantity')).get(
                'total_quantity') or 0
            has_qarantine = len(filtered_kill_reqs2.filter(quarantine_quantity__isnull=False))
            all_ware_house_accepted_real_quantity = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_ware_house_accepted_real_weight = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight')).get(
                'total_quantity', 0) or 0
            all_weight_loss = filtered_kill_reqs2.aggregate(
                total_quantity=Sum('weight_loss')).get(
                'total_quantity', 0) or 0
            all_weight_loss = round(int(all_weight_loss) / len_weight_loss, 2) if len_weight_loss > 0 else 0
            has_code1 = filtered_kill_reqs2.filter(clearance_code__isnull=False)
            all_quarantine_quantity_has_code = has_code1.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            hasnt_code = filtered_kill_reqs2.filter(clearance_code__isnull=True)
            all_quarantine_quantity_hasnt_code = hasnt_code.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            difference_bar = len(filtered_kill_reqs2.filter(
                Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity'))))
            value_header_list = [
                len(filtered_kill_reqs2),
                killer_exclusive,
                all_quantity,
                int(all_weighte),
                round(all_weighte / all_quantity, 1) if all_weighte > 0 and all_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_code),
                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 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}'

            ]
            for item in range(len(value_header_list)):
                cell = worksheet.cell(row=8, 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)):
                    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')
                )
            value_header_list2 = [
                len(poultry_request),
                total_requests_quantity,
                int(total_requests_weight)

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=8, 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)):
                    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')
                )

            state = 'accepted'
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            if request.GET['role'] == 'VetFarm':
                vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
                poultries = Poultry.objects.filter(
                    pk__in=vet_farms.values('poultry')
                )

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


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

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

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

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


            elif request.GET['role'] in ['ProvinceOperator', 'SuperAdmin', 'AdminX']:

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

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

            poultry_requests_accepted = poultry_requests.filter(province_state='accepted')

            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 = (datetime.datetime.now() - poultry_request.hatching.date).days + 1
                    all_age.append(age)
                    all_chicken_quantity += poultry_request.hatching.quantity

                    if poultry_request.quarantine_code:
                        has_code += 1

            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=13, column=item + 8, 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)
                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')
                )

            chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                               ).order_by('id')
            if request.GET['role'] == "ChainCompany":
                chain_allocations = chain_allocations.filter(chain_company__user=user,
                                                             state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                chain_allocations = chain_allocations.filter(poultry_hatching__poultry__address__city=user.city,
                                                             state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            elif request.GET['role'] == "CityOperator":
                city_operator = CityOperator.objects.get(user=user, trash=False)
                chain_allocations = chain_allocations.filter(
                    poultry_hatching__poultry__city_operator=city_operator.unit_name,
                    state__in=('accepted', 'pending'),
                    trash=False).order_by('-id')
            elif request.GET['role'] == "VetFarm":
                vet = Vet.objects.get(user=user, trash=False)
                poultry_ids = VetFarm.objects.filter(vet=vet, trash=False).select_related('poultry').only(
                    'poultry').values_list('poultry', flat=True).distinct()
                poultry = Poultry.objects.filter(id__in=poultry_ids)
                chain_allocations = chain_allocations.filter(poultry_hatching__poultry__in=poultry,
                                                             state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            else:
                chain_allocations = chain_allocations.filter(state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')

            header_list = [
                'تعداد بارها',
                'مجموع تعداد قطعه بارها',
                'مجموع وزن بارها',
                'کمترین سن مرغ',
                'بیشترین سن مرغ',
                'تعداد بارهای دارای کد قرنطینه',

            ]
            for col_num, option in enumerate(header_list, 8):
                cell = worksheet.cell(row=17, 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[17].height = 20.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')
                )

            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)

                    if chain_allocation.quarantine_code:
                        has_code += 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=18, column=item + 8, 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)
                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_list2 = [
                'تعداد بارها',
                ' تعداد بار های درانتظار تایید',
                'مجموع قطعه زنده در انتظار تایید',
                'مجموع وزن زنده (کیلوگرم) درانتظار تایید',
                'مجموع تعداد لاشه درانتظار تایید',
                'مجموع وزن لاشه (کیلوگرم) درانتظار تایید',

                ' تعداد بار های رد شده',
                'مجموع قطعه زنده رد شده',
                'مجموع وزن زنده (کیلوگرم) رد شده',
                'مجموع تعداد لاشه رد شده',
                'مجموع وزن لاشه (کیلوگرم) رد شده',

                ' تعداد بار های تایید شده',
                'مجموع قطعه زنده تایید شده',
                'مجموع وزن زنده (کیلوگرم) تایید شده',
                'مجموع تعداد لاشه تایید شده',
                'مجموع وزن لاشه (کیلوگرم) تایید شده',
                'حجم تایید شده دامپزشک',
                'وزن تایید شده دامپزشک',

            ]

            for col_num, option in enumerate(header_list2, 6):
                cell = worksheet.cell(row=22, 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
                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')
                )
            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                date__date__gte=date1,
                date__date__lte=date2,
                buy_type='live',
                trash=False).order_by('-date')

            bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending')
            bar_pending_quantity = bar_pending.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_pending_live_weight = bar_pending.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_pending_number_of_carcasses = bar_pending.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_pending_weight_of_carcasses = bar_pending.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected')
            bar_rejected_quantity = bar_rejected.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_rejected_live_weight = bar_rejected.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_rejected_number_of_carcasses = bar_rejected.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_rejected_weight_of_carcasses = bar_rejected.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted')
            bar_accepted_quantity = bar_accepted.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_accepted_live_weight = bar_accepted.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_accepted_number_of_carcasses = bar_accepted.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_accepted_weight_of_carcasses = bar_accepted.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate(
                total_quantity=Sum('kill_house_vet_quantity')).get(
                'total_quantity') or 0
            bar_accepted_kill_house_vet_weight = bar_accepted.aggregate(
                total_quantity=Sum('kill_house_vet_weight')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(kill_house_free_bar_info),
                len(bar_pending),
                int(bar_pending_quantity),
                int(bar_pending_live_weight),
                int(bar_pending_number_of_carcasses),
                int(bar_pending_weight_of_carcasses),

                len(bar_rejected),
                int(bar_rejected_quantity),
                int(bar_rejected_live_weight),
                int(bar_rejected_number_of_carcasses),
                int(bar_rejected_weight_of_carcasses),

                len(bar_accepted),
                int(bar_accepted_quantity),
                int(bar_accepted_live_weight),
                int(bar_accepted_number_of_carcasses),
                int(bar_accepted_weight_of_carcasses),
                int(bar_accepted_kill_house_vet_quantity),
                int(bar_accepted_kill_house_vet_weight)

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=23, 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)
                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_list2, 6):
                    cell = worksheet.cell(row=27, 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
                    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')
                    )
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    buy_type='carcass',
                    trash=False).order_by('-date')

                bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending')
                bar_pending_quantity = bar_pending.aggregate(
                    total_quantity=Sum('quantity')).get(
                    'total_quantity') or 0
                bar_pending_live_weight = bar_pending.aggregate(
                    total_quantity=Sum('live_weight')).get(
                    'total_quantity') or 0
                bar_pending_number_of_carcasses = bar_pending.aggregate(
                    total_quantity=Sum('number_of_carcasses')).get(
                    'total_quantity') or 0
                bar_pending_weight_of_carcasses = bar_pending.aggregate(
                    total_quantity=Sum('weight_of_carcasses')).get(
                    'total_quantity') or 0

                bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected')
                bar_rejected_quantity = bar_rejected.aggregate(
                    total_quantity=Sum('quantity')).get(
                    'total_quantity') or 0
                bar_rejected_live_weight = bar_rejected.aggregate(
                    total_quantity=Sum('live_weight')).get(
                    'total_quantity') or 0
                bar_rejected_number_of_carcasses = bar_rejected.aggregate(
                    total_quantity=Sum('number_of_carcasses')).get(
                    'total_quantity') or 0
                bar_rejected_weight_of_carcasses = bar_rejected.aggregate(
                    total_quantity=Sum('weight_of_carcasses')).get(
                    'total_quantity') or 0

                bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted')
                bar_accepted_quantity = bar_accepted.aggregate(
                    total_quantity=Sum('quantity')).get(
                    'total_quantity') or 0
                bar_accepted_live_weight = bar_accepted.aggregate(
                    total_quantity=Sum('live_weight')).get(
                    'total_quantity') or 0
                bar_accepted_number_of_carcasses = bar_accepted.aggregate(
                    total_quantity=Sum('number_of_carcasses')).get(
                    'total_quantity') or 0
                bar_accepted_weight_of_carcasses = bar_accepted.aggregate(
                    total_quantity=Sum('weight_of_carcasses')).get(
                    'total_quantity') or 0
                bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate(
                    total_quantity=Sum('kill_house_vet_quantity')).get(
                    'total_quantity') or 0
                bar_accepted_kill_house_vet_weight = bar_accepted.aggregate(
                    total_quantity=Sum('kill_house_vet_weight')).get(
                    'total_quantity') or 0

                value_header_list2 = [
                    len(kill_house_free_bar_info),
                    len(bar_pending),
                    int(bar_pending_quantity),
                    int(bar_pending_live_weight),
                    int(bar_pending_number_of_carcasses),
                    int(bar_pending_weight_of_carcasses),

                    len(bar_rejected),
                    int(bar_rejected_quantity),
                    int(bar_rejected_live_weight),
                    int(bar_rejected_number_of_carcasses),
                    int(bar_rejected_weight_of_carcasses),

                    len(bar_accepted),
                    int(bar_accepted_quantity),
                    int(bar_accepted_live_weight),
                    int(bar_accepted_number_of_carcasses),
                    int(bar_accepted_weight_of_carcasses),
                    int(bar_accepted_kill_house_vet_quantity),
                    int(bar_accepted_kill_house_vet_weight)

                ]
                for item in range(len(value_header_list2)):
                    cell = worksheet.cell(row=28, 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)
                    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')
                    )
        elif sheet_name == 'مدیریت بارها':
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'نوع کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

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

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

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

            ]

            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            create_header(worksheet, header_list, 9, 2, border_style='thin')
            create_header(worksheet, header_list2, 6, 2, border_style='thin')
            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('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__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',
                                                      'killer__name',
                                                      'province_kill_request__kill_house_price',
                                                      'price',
                                                      'killhouse_user__type', 'killer', 'entered_message',
                                                      'bar_document_status__title').values(
                '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',
                'province_kill_request__kill_house_price',
                'price',
                'killer', 'entered_message', 'bar_document_status__title'
            )

            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__kill_house_operator__user=user)
            else:
                filtered_kill_reqs = filtered_kill_request

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

            elif request.GET['role'] == 'KillHouseVet':
                kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
                kill_house = kill_house_vets.values_list('kill_house', flat=True).distinct()

            else:
                kill_house = KillHouse.objects.filter(system_address__province=user.province, 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
            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'] or 0
            total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0

            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['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_age = []
            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') or 0
            accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity') or 0

            all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity') or 0
            killer_exclusive = 0
            all_assignment_state_archive_state = 0
            len_weight_loss = 0
            all_state_ware_house_confirmation = 0
            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' 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')

                    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 = 'کشتارکن'
                    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'])
                        killer_exclusive += 1
                    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 = int(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 = 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

                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    if kill['message'] is not None:
                        state_delete = 'بار حذف شده'
                    else:
                        state_delete = 'فعال'
                        all_quantity += quantity
                        all_weighte += weight
                        all_real_quantity += real_quantity if real_quantity != '-' else 0
                        all_net_weighte += net_weighte if net_weighte != '-' else 0

                    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 weight_loss > 0:
                        len_weight_loss += 1
                    if kill['ware_house_confirmation'] == True:
                        if kill['entered_message'] is not None and kill[
                            'entered_message'] == 'ورود به انبار توسط سیستم':
                            state_ware_house_confirmation = 'ورود به انبار(سیستمی)'
                        else:
                            state_ware_house_confirmation = 'ورود به انبار(دستی)'
                        all_state_ware_house_confirmation += 1

                    else:
                        state_ware_house_confirmation = 'در انتظار ورود به انبار'

                    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__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_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_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'],
                        int(kill['accepted_real_weight']),
                        kill['bar_document_status__title'] if kill['bar_document_status__title'] != None else '-',
                        state_ware_house_confirmation,
                        ware_house_accepted_real_quantity,
                        int(ware_house_accepted_real_weight),
                        f'%{weight_loss}',
                        export_country,
                        kill['accepted_real_quantity'] - quarantine_quantity if kill[
                                                                'quarantine_quantity'] != None else quarantine_quantity

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

                        if isinstance(value, (int)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values
                        if list1[40] == 'بار حذف شده':
                            cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            all_age1 = sorted(all_age)
            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') or 0
            has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))
            all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight')).get(
                'total_quantity', 0) or 0
            all_weight_loss = filtered_kill_reqs.aggregate(
                total_quantity=Sum('weight_loss')).get(
                'total_quantity', 0) or 0
            all_weight_loss = round(int(all_weight_loss) / len_weight_loss, 2) if len_weight_loss > 0 else 0
            has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False)
            all_quarantine_quantity_has_code = has_code1.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            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') or 0
            difference_bar = len(filtered_kill_reqs.filter(
                Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity'))))

            value_header_list = [
                len(filtered_kill_reqs),
                killer_exclusive,
                all_quantity,
                int(all_weighte),
                round(all_weighte / all_quantity, 1) if all_weighte > 0 and all_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_code),
                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 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}'

            ]
            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)):
                    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,
                int(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)):
                    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,
                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),
                f'%{all_weight_loss}',
                '',
                '',

            ]
            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)):
                    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.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'بارهای حذف شده':
            excel_options = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'نوع کشتار',
                'کدسفارش مرغدار',
                'مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'فروش',

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

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

            ]

            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            filtered_kill_request = KillHouseRequest.objects.filter(trash=True,
                                                                    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('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__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',
                                                      'killer__name',
                                                      'province_kill_request__kill_house_price',
                                                      'price',
                                                      'killhouse_user__type', 'killer').values(
                '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',
                'province_kill_request__kill_house_price',
                'price',
                'killer',
            )

            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__kill_house_operator__user=user)
            else:
                filtered_kill_reqs = filtered_kill_request

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

            elif request.GET['role'] == 'KillHouseVet':
                kill_house_vets = KillHouseVet.objects.filter(vet__user=user, trash=False).select_related('kill_house')
                kill_house = kill_house_vets.values_list('kill_house', flat=True).distinct()

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

            if 'state' in request.GET:
                if request.GET['state'] == 'completed':
                    filtered_kill_reqs = filtered_kill_request.filter(assignment_state_archive='True')
                elif request.GET['state'] == 'bar_pending':
                    filtered_kill_reqs = filtered_kill_request.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_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'] or 0
            total_requests_weight = poultry_request.aggregate(total=Sum('total_weight'))['total'] or 0
            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

            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
            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['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_age = []
            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') or 0
            accepted_real_wight = filtered_kill_reqs.aggregate(total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity') or 0

            all_kill_request_quantity = filtered_kill_reqs.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_quantity = filtered_kill_reqs.aggregate(
                total_quantity=Sum('vet_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_vet_accepted_real_weight = filtered_kill_reqs.aggregate(
                total_quantity=Sum('vet_accepted_real_weight')).get(
                'total_quantity') or 0
            killer_exclusive = 0
            all_assignment_state_archive_state = 0
            len_weight_loss = 0
            all_state_ware_house_confirmation = 0
            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' 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')

                    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 = 'کشتارکن'
                    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'])
                        killer_exclusive += 1
                    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 = int(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 = 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

                    freez_state = 'منجمد' if kill['province_request__poultry_request__freezing'] == True else 'عادی'
                    if kill['message'] is not None:
                        state_delete = 'بار حذف شده'
                    else:
                        state_delete = 'فعال'
                        all_quantity += quantity
                        all_weighte += weight
                        all_real_quantity += real_quantity if real_quantity != '-' else 0
                        all_net_weighte += net_weighte if net_weighte != '-' else 0

                    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 weight_loss > 0:
                        len_weight_loss += 1
                    if kill['ware_house_confirmation'] == True:
                        state_ware_house_confirmation = 'ورود به انبار'
                        all_state_ware_house_confirmation += 1

                    else:
                        state_ware_house_confirmation = '-'

                    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__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_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_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'],
                        int(kill['accepted_real_weight']),
                        state_delete,
                        kill['document_status'] if kill['document_status'] else '-',
                        state_ware_house_confirmation,
                        ware_house_accepted_real_quantity,
                        int(ware_house_accepted_real_weight),
                        f'%{weight_loss}',
                        export_country,

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

                        if isinstance(value, (int)):
                            if value != 0:
                                cell.number_format = '#,###'  # Apply general number format
                        else:
                            cell.value = value  # Keep as text for other values
                        if list1[40] == 'بار حذف شده':
                            cell.fill = PatternFill(start_color="FCDFDC", fill_type="solid")
                        worksheet.row_dimensions[l + 1].height = 20
                        cell.alignment = Alignment(horizontal='center', vertical='center')

            all_age1 = sorted(all_age)
            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') or 0
            has_qarantine = len(filtered_kill_reqs.filter(quarantine_quantity__isnull=False))
            all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                'total_quantity') or 0
            all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight')).get(
                'total_quantity', 0) or 0
            all_weight_loss = filtered_kill_reqs.aggregate(
                total_quantity=Sum('weight_loss')).get(
                'total_quantity', 0) or 0
            all_weight_loss = round(int(all_weight_loss) / len_weight_loss, 2) if len_weight_loss > 0 else 0
            has_code1 = filtered_kill_reqs.filter(clearance_code__isnull=False)
            all_quarantine_quantity_has_code = has_code1.aggregate(total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            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') or 0
            difference_bar = len(filtered_kill_reqs.filter(
                Q(quantity__gt=F('quarantine_quantity')) | Q(quantity__lt=F('quarantine_quantity'))))
            value_header_list = [
                len(filtered_kill_reqs),
                killer_exclusive,
                all_quantity,
                int(all_weighte),
                round(all_weighte / all_quantity, 1) if all_weighte > 0 and all_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_code),
                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 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}'

            ]
            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)):
                    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,
                int(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)):
                    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,
                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),
                f'%{all_weight_loss}',
                '',
                '',
                '',

            ]
            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)):
                    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.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

        elif sheet_name == 'فروش به خارج از استان':

            state = 'accepted'
            user = SystemUserProfile.objects.get(key=request.GET['key'])
            name_bar = ''
            if request.GET['role'] == 'VetFarm':
                vet_farms = VetFarm.objects.filter(vet__user=user, trash=False)
                poultries = Poultry.objects.filter(
                    pk__in=vet_farms.values('poultry')
                )
                if state == 'pending':
                    poultry_requests = PoultryRequest.objects.filter(
                        Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                          wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                              wage_pay=False),
                        poultry__in=poultries, send_date__date__gte=date1,
                        send_date__date__lte=date2,
                        out_province_request_cancel=False,
                        trash=False).order_by('-send_date')
                elif state == 'accepted':
                    poultry_requests = PoultryRequest.objects.filter(
                        Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                          wage_pay=True) | Q(state_process='accepted', province_state='accepted', final_state='archive',
                                             has_wage=False, wage_pay=False),
                        poultry__in=poultries, send_date__date__gte=date1,
                        send_date__date__lte=date2,
                        out_province_request_cancel=False,
                        trash=False).order_by('-send_date')
                else:
                    poultry_requests = PoultryRequest.objects.filter(
                        Q(state_process='rejected', province_state='rejected', final_state='archive', has_wage=True,
                          wage_pay=False, out_province_request_cancel=False) | Q(state_process='rejected',
                                                                                 province_state='rejected',
                                                                                 final_state='archive',
                                                                                 has_wage=False, wage_pay=False,
                                                                                 out_province_request_cancel=False) | Q(
                            state_process='pending', province_state='pending', final_state='pending',
                            has_wage=False, wage_pay=False, out_province_request_cancel=True),
                        poultry__in=poultries, send_date__date__gte=date1,
                        send_date__date__lte=date2,
                        trash=False).order_by('-send_date')

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

                    poultry_requests = PoultryRequest.objects.filter(
                        Q(state_process='accepted', province_state='accepted', final_state='archive', has_wage=True,
                          wage_pay=False) | Q(state_process='pending', province_state='pending', final_state='pending',
                                              wage_pay=False),
                        poultry__city_operator=city_operator.unit_name,
                        send_date__date__gte=date1,
                        send_date__date__lte=date2,
                        out=True,
                        out_province_request_cancel=False,
                        trash=False).order_by('-send_date')
                    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']:
                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 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')

            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)

            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:
                    age = poultry_request.hatching.chicken_age
                    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 poultry_request.quarantine_code:
                        code = poultry_request.quarantine_code
                        has_code += 1
                    else:
                        code = '-'

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

        elif sheet_name == 'بارهای زنجیره':
            chain_allocations = ChainAllocation.objects.filter(date__date__gte=date1, date__date__lte=date2,
                                                               ).order_by('id')
            if request.GET['role'] == "ChainCompany":
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                chain_allocations = chain_allocations.filter(chain_company__user=user,
                                                             state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            elif request.GET['role'] in ['CityJahad', 'CityPoultry']:
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                chain_allocations = chain_allocations.filter(poultry_hatching__poultry__address__city=user.city,
                                                             state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            elif request.GET['role'] == "CityOperator":
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                city_operator = CityOperator.objects.get(user=user, trash=False)
                chain_allocations = chain_allocations.filter(
                    poultry_hatching__poultry__city_operator=city_operator.unit_name,
                    state__in=('accepted', 'pending'),
                    trash=False).order_by('-id')
            elif request.GET['role'] == "VetFarm":
                user = SystemUserProfile.objects.get(key=request.GET['key'])
                vet = Vet.objects.get(user=user, trash=False)
                poultry_ids = VetFarm.objects.filter(vet=vet, trash=False).select_related('poultry').only(
                    'poultry').values_list('poultry', flat=True).distinct()
                poultry = Poultry.objects.filter(id__in=poultry_ids)
                chain_allocations = chain_allocations.filter(poultry_hatching__poultry__in=poultry,
                                                             state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            else:
                chain_allocations = chain_allocations.filter(state__in=('accepted', 'pending'),
                                                             trash=False).order_by('-id')
            state1 = 'تایید شده'

            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)

            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, 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'] = 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_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,
                        age,
                    ]
                    m += 1
                    if state1 == 'تایید شده':
                        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)
                    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")

        elif sheet_name == 'خرید زنده خارج از استان':
            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'], trash=False)
            type = 'live'
            if request.GET['role'] in ['KillHouse', 'KillHouseVet']:
                if request.GET['role'] == 'KillHouse':
                    kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                else:
                    kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                          flat=True)
                    kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)

                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses,
                                                                                      date__date__gte=date1,
                                                                                      date__date__lte=date2,
                                                                                      buy_type=type,
                                                                                      trash=False).order_by('-date')
            else:
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    buy_type=type,
                    trash=False).order_by('-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)

            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_list2 = [
                ' تعداد بار های درانتظار تایید',
                'مجموع قطعه زنده ',
                'مجموع وزن زنده (کیلوگرم)',
                'مجموع وزن لاشه (کیلوگرم)',

            ]

            for col_num, option in enumerate(header_list2, 5):
                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
            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
            type = 'زنده' if type == 'live' else 'لاشه'
            worksheet['B1'] = f'گزارش بار {type} خرید از استان'

            if kill_house_free_bar_info.exists():
                name = kill_house_free_bar_info.first().kill_house.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

            if kill_house_free_bar_info:
                for kill in kill_house_free_bar_info:
                    l += 1

                    if kill.ware_house == True:
                        if kill.register_type == 'automatic':
                            state = 'ورود به انبار (سیستمی)'
                        else:
                            state = 'ورود به انبار (دستی)'
                    else:
                        if kill.register_type == 'automatic':
                            state = 'در انتظار ورود به انبار (سیستمی)'
                        else:
                            state = ' در انتظار ورود به انبار (دستی)'

                    if kill.buy_type == 'live':
                        buy_type = 'زنده'
                    else:
                        buy_type = 'لاشه'

                    date_of_buy = jdatetime.date.fromgregorian(
                        day=kill.date.day,
                        month=kill.date.month,
                        year=kill.date.year
                    )

                    if kill.date_of_accept_reject:
                        date_of_reject_accepted = jdatetime.date.fromgregorian(
                            day=kill.date_of_accept_reject.day,
                            month=kill.date_of_accept_reject.month,
                            year=kill.date_of_accept_reject.year
                        )
                    else:
                        date_of_reject_accepted = '-'
                    if kill.exclusive_killer:
                        killer_type = f'کشتارکن اختصاصی {kill.kill_house.name}'
                        kill_house_name = kill.exclusive_killer.name
                        kill_house_mobile = kill.exclusive_killer.kill_house_operator.user.mobile

                    elif kill.kill_house.killer == True and kill.kill_house.type == 'public':
                        killer_type = 'کشتارکن عمومی'
                        kill_house_name = kill.kill_house.name
                        kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile

                    else:
                        killer_type = 'کشتارگاه'
                        kill_house_name = kill.kill_house.name
                        kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile
                    bar_code = str(kill.bar_code) if kill.bar_code else '-'
                    list1 = [
                        m,
                        bar_code,
                        str(shamsi_date(kill.register_date, in_value=True)) if kill.register_date else '-',
                        str(date_of_buy),
                        killer_type,
                        kill_house_name,
                        kill_house_mobile,
                        kill.poultry_name,
                        kill.poultry_mobile,
                        buy_type,
                        f'{kill.province} / {kill.city}',
                        kill.car,
                        kill.driver_name,
                        kill.driver_mobile,
                        kill.bar_clearance_code,
                        kill.quantity,
                        kill.live_weight,
                        kill.number_of_carcasses,
                        kill.weight_of_carcasses,
                        state,

                    ]
                    m += 1
                    create_value(worksheet, list1, l + 1, 1, height=20, width=30)

            bar_pending = kill_house_free_bar_info
            bar_pending_quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_pending_live_weight = bar_pending.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0

            bar_pending_weight_of_carcasses = bar_pending.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected')

            bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted')

            bar_quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0

            bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('kill_house_vet_weight')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(kill_house_free_bar_info),
                int(bar_pending_quantity),
                int(bar_pending_live_weight),
                int(bar_pending_weight_of_carcasses),

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 5, 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 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                bar_quantity,
                bar_live_weight,
                bar_pending_quantity,
                bar_pending_weight_of_carcasses,
                '',

            ]
            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 = '#,###'  # 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 == 'خرید لاشه خارج از استان':
            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'], trash=False)
            type = 'carcass'
            if request.GET['role'] in ['KillHouse', 'KillHouseVet']:
                if request.GET['role'] == 'KillHouse':
                    kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                else:
                    kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                          flat=True)
                    kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)

                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses,
                                                                                      date__date__gte=date1,
                                                                                      date__date__lte=date2,
                                                                                      buy_type=type,
                                                                                      trash=False).order_by('-date')
            else:
                kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(
                    date__date__gte=date1,
                    date__date__lte=date2,
                    buy_type=type,
                    trash=False).order_by('-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)

            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_list2 = [
                'تعداد بارها',
                ' تعداد بار های درانتظار تایید',
                'مجموع قطعه زنده در انتظار تایید',
                'مجموع وزن زنده (کیلوگرم) درانتظار تایید',
                'مجموع تعداد لاشه درانتظار تایید',
                'مجموع وزن لاشه (کیلوگرم) درانتظار تایید',

                ' تعداد بار های رد شده',
                'مجموع قطعه زنده رد شده',
                'مجموع وزن زنده (کیلوگرم) رد شده',
                'مجموع تعداد لاشه رد شده',
                'مجموع وزن لاشه (کیلوگرم) رد شده',

                ' تعداد بار های تایید شده',
                'مجموع قطعه زنده تایید شده',
                'مجموع وزن زنده (کیلوگرم) تایید شده',
                'مجموع تعداد لاشه تایید شده',
                'مجموع وزن لاشه (کیلوگرم) تایید شده',
                'حجم تایید شده دامپزشک',
                'وزن تایید شده دامپزشک',

            ]

            for col_num, option in enumerate(header_list2, 5):
                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
            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
            type = 'زنده' if type == 'live' else 'لاشه'
            worksheet['B1'] = f'گزارش بار {type} خرید از استان'

            if kill_house_free_bar_info.exists():
                name = kill_house_free_bar_info.first().kill_house.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

            if kill_house_free_bar_info:
                for kill in kill_house_free_bar_info:
                    l += 1

                    if kill.kill_house_vet_state == 'accepted':
                        state = 'تایید شده'
                    elif kill.kill_house_vet_state == 'pending':
                        state = 'درانتظار تایید'
                    else:
                        state = 'رد شده'

                    if kill.buy_type == 'live':
                        buy_type = 'زنده'
                    else:
                        buy_type = 'لاشه'

                    date_of_buy = jdatetime.date.fromgregorian(
                        day=kill.date.day,
                        month=kill.date.month,
                        year=kill.date.year
                    )

                    if kill.date_of_accept_reject:
                        date_of_reject_accepted = jdatetime.date.fromgregorian(
                            day=kill.date_of_accept_reject.day,
                            month=kill.date_of_accept_reject.month,
                            year=kill.date_of_accept_reject.year
                        )
                    else:
                        date_of_reject_accepted = '-'

                    list1 = [
                        m,
                        state,
                        kill.kill_house.name,
                        kill.poultry_name,
                        buy_type,
                        f'{kill.province} / {kill.city}',
                        str(date_of_buy),
                        kill.vet_farm_name,
                        kill.vet_farm_mobile,
                        kill.car,
                        kill.driver_name,
                        kill.driver_mobile,
                        kill.bar_clearance_code,
                        kill.quantity,
                        kill.live_weight,
                        kill.number_of_carcasses,
                        kill.weight_of_carcasses,
                        kill.kill_house_vet_quantity,
                        kill.kill_house_vet_weight,
                        kill.acceptor_rejector,
                        str(date_of_reject_accepted)

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

                        if isinstance(value, (int)):
                            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')

            bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending')
            bar_pending_quantity = bar_pending.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_pending_live_weight = bar_pending.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_pending_number_of_carcasses = bar_pending.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_pending_weight_of_carcasses = bar_pending.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected')
            bar_rejected_quantity = bar_rejected.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_rejected_live_weight = bar_rejected.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_rejected_number_of_carcasses = bar_rejected.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_rejected_weight_of_carcasses = bar_rejected.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted')
            bar_accepted_quantity = bar_accepted.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_accepted_live_weight = bar_accepted.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_accepted_number_of_carcasses = bar_accepted.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_accepted_weight_of_carcasses = bar_accepted.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate(
                total_quantity=Sum('kill_house_vet_quantity')).get(
                'total_quantity') or 0
            bar_accepted_kill_house_vet_weight = bar_accepted.aggregate(
                total_quantity=Sum('kill_house_vet_weight')).get(
                'total_quantity') or 0

            bar_quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            bar_live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            bar_number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            bar_weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            bar_kill_house_vet_quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('kill_house_vet_quantity')).get(
                'total_quantity') or 0
            bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('kill_house_vet_weight')).get(
                'total_quantity') or 0

            value_header_list2 = [
                m - 1,
                len(bar_pending),
                int(bar_pending_quantity),
                int(bar_pending_live_weight),
                int(bar_pending_number_of_carcasses),
                int(bar_pending_weight_of_carcasses),

                len(bar_rejected),
                int(bar_rejected_quantity),
                int(bar_rejected_live_weight),
                int(bar_rejected_number_of_carcasses),
                int(bar_rejected_weight_of_carcasses),

                len(bar_accepted),
                int(bar_accepted_quantity),
                int(bar_accepted_live_weight),
                int(bar_accepted_number_of_carcasses),
                int(bar_accepted_weight_of_carcasses),
                int(bar_accepted_kill_house_vet_quantity),
                int(bar_accepted_kill_house_vet_weight)

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 5, 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 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                bar_quantity,
                bar_live_weight,
                int(bar_number_of_carcasses),
                int(bar_weight_of_carcasses),
                int(bar_kill_house_vet_quantity),
                bar_kill_house_vet_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)):
                    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.font = Font(bold=True)
                cell.fill = PatternFill(start_color="00B050", fill_type="solid")

    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 kill_house_free_bar_excel(request):
    filterset_class = KillHouseFreeBarInformationFilterSet
    filterset_fields = [
        'kill_house__name',
        'poultry_name',
        'poultry_mobile',
        'province',
        'city',
        'driver_name',
        'driver_mobile',
        'clearance_code',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',

    ]
    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'], trash=False)
    type = request.GET.get('type')
    date_type = request.GET.get('date_type')
    bar_state = request.GET.get('bar_state')
    kill_house_free_bar_info_list = []
    role = request.GET.get('role')
    kill_houses = None
    order_by_type = 'create_date'

    if role in ['KillHouse', 'KillHouseVet']:
        if role == 'KillHouse':
            kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
        else:
            kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                  flat=True)
            kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        if date_type == 'buy':

            filters = {
                'register_date__date__gte': date1,
                'register_date__date__lte': date2,
                'trash': False,
                'temporary_trash': False,
                'temporary_deleted': False,
                'calculate_status': True
            }
        else:
            order_by_type = '-date'
            filters = {
                'date__date__gte': date1,
                'date__date__lte': date2,
                'trash': False,
                'temporary_trash': False,
                'temporary_deleted': False,
                'calculate_status': True
            }

    else:
        filters = {
            'trash': False,
            'temporary_trash': False,
            'temporary_deleted': False,
            'calculate_status': True
        }

    if kill_houses is not None:
        filters['kill_house__in'] = kill_houses

    if type:
        filters['buy_type'] = type
        if type == 'live':
            if bar_state:
                if bar_state == 'entered':
                    filters['weight_of_carcasses__gt'] = 0
                else:
                    filters['weight_of_carcasses'] = 0

    kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(
        order_by_type)

    if 'search' in request.GET:
        if request.GET['search'] == 'filter':
            if request.GET['value'] != "" and request.GET['value'] != 'undefined':
                for item in filterset_fields:
                    query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                    if (filterset_class(
                            data=query,
                            queryset=kill_house_free_bar_info
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=kill_house_free_bar_info)
                        kill_house_free_bar_info_list = ps.filter()
                kill_house_free_bar_info = [] if len(
                    kill_house_free_bar_info_list) == 0 else kill_house_free_bar_info_list
    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_list2 = [
        ' تعداد بار های درانتظار تایید',
        'مجموع قطعه زنده ',
        'مجموع وزن زنده (کیلوگرم)',
        'مجموع وزن لاشه (کیلوگرم)',

    ]

    for col_num, option in enumerate(header_list2, 5):
        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
    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
    type = 'زنده' if request.GET['type'] == 'live' else 'لاشه'
    worksheet['B1'] = f'گزارش بار {type} خرید از استان'

    if kill_house_free_bar_info.exists():
        name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name \
            if kill_house_free_bar_info.first() else ''
        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

    if kill_house_free_bar_info:
        for kill in kill_house_free_bar_info:
            l += 1

            if kill.ware_house == True:
                if kill.register_type == 'automatic':
                    state = 'ورود به انبار (سیستمی)'
                else:
                    state = 'ورود به انبار (دستی)'
            else:
                if kill.register_type == 'automatic':
                    state = 'در انتظار ورود به انبار (سیستمی)'
                else:
                    state = ' در انتظار ورود به انبار (دستی)'

            if kill.buy_type == 'live':
                buy_type = 'زنده'
            else:
                buy_type = 'لاشه'

            # date_of_buy = jdatetime.date.fromgregorian(
            #     day=kill.date.day,
            #     month=kill.date.month,
            #     year=kill.date.year
            # )
            date_of_buy = jdatetime.date.fromgregorian(
                day=kill.create_date.day,
                month=kill.create_date.month,
                year=kill.create_date.year
            )

            if kill.date_of_accept_reject:
                date_of_reject_accepted = jdatetime.date.fromgregorian(
                    day=kill.date_of_accept_reject.day,
                    month=kill.date_of_accept_reject.month,
                    year=kill.date_of_accept_reject.year
                )
            else:
                date_of_reject_accepted = '-'
            if kill.exclusive_killer:
                killer_type = f'کشتارکن اختصاصی {kill.kill_house.name}'
                kill_house_name = kill.exclusive_killer.name
                kill_house_mobile = kill.exclusive_killer.kill_house_operator.user.mobile

            elif kill.kill_house.killer == True and kill.kill_house.type == 'public':
                killer_type = 'کشتارکن عمومی'
                kill_house_name = kill.kill_house.name
                kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile

            else:
                killer_type = 'کشتارگاه'
                kill_house_name = kill.kill_house.name
                kill_house_mobile = kill.kill_house.kill_house_operator.user.mobile
            bar_code = str(kill.bar_code) if kill.bar_code else '-'
            if kill.exclusive_killer:
                exclusive_killer = f'{kill.exclusive_killer.name}({kill.exclusive_killer.kill_house_operator.user.mobile})'
            else:
                exclusive_killer = '-'
            list1 = [
                m,
                bar_code,
                str(shamsi_date(kill.register_date, in_value=True)) if kill.register_date else '-',
                str(date_of_buy),
                killer_type,
                kill_house_name,
                kill_house_mobile,
                exclusive_killer,
                kill.poultry_name,
                kill.poultry_mobile,
                buy_type,
                f'{kill.province} / {kill.city}',
                kill.car,
                kill.driver_name,
                kill.driver_mobile,
                kill.bar_clearance_code,
                kill.quantity,
                kill.live_weight,
                kill.number_of_carcasses,
                kill.weight_of_carcasses,
                state,

            ]
            m += 1
            create_value(worksheet, list1, l + 1, 1, height=20, width=30)

    bar_pending = kill_house_free_bar_info.filter(kill_house_vet_state='pending')
    bar_pending_quantity = bar_pending.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    bar_pending_live_weight = bar_pending.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    bar_pending_number_of_carcasses = bar_pending.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    bar_pending_weight_of_carcasses = bar_pending.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    bar_rejected = kill_house_free_bar_info.filter(kill_house_vet_state='rejected')
    bar_rejected_quantity = bar_rejected.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    bar_rejected_live_weight = bar_rejected.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    bar_rejected_number_of_carcasses = bar_rejected.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    bar_rejected_weight_of_carcasses = bar_rejected.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    bar_accepted = kill_house_free_bar_info.filter(kill_house_vet_state='accepted')
    bar_accepted_quantity = bar_accepted.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    bar_accepted_live_weight = bar_accepted.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    bar_accepted_number_of_carcasses = bar_accepted.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    bar_accepted_weight_of_carcasses = bar_accepted.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0
    bar_accepted_kill_house_vet_quantity = bar_accepted.aggregate(
        total_quantity=Sum('kill_house_vet_quantity')).get(
        'total_quantity') or 0
    bar_accepted_kill_house_vet_weight = bar_accepted.aggregate(
        total_quantity=Sum('kill_house_vet_weight')).get(
        'total_quantity') or 0

    bar_quantity = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    bar_live_weight = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    bar_number_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    bar_weight_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0
    bar_kill_house_vet_quantity = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('kill_house_vet_quantity')).get(
        'total_quantity') or 0
    bar_kill_house_vet_weight = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('kill_house_vet_weight')).get(
        'total_quantity') or 0

    value_header_list2 = [
        len(kill_house_free_bar_info),
        int(bar_pending_quantity),
        int(bar_pending_live_weight),
        int(bar_pending_weight_of_carcasses),

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 5, 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 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        bar_quantity,
        bar_live_weight,
        bar_pending_quantity,
        bar_pending_weight_of_carcasses,
        '',

    ]
    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 = '#,###'  # 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 request.GET['role'] == 'KillHouse':
        name = kill_house_free_bar_info.first().kill_house.name
        response[
            'Content-Disposition'] = f'attachment; filename=" مدیریت بار  {type} کشتارگاه {name} خرید از استان.xlsx"'.encode(
            'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="مدیریت بار {type} خرید از استان.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def comprehensive_report_of_the_slaughterhouse_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

    from_date_1 = shamsi_date(date1)
    to_date_1 = shamsi_date(date2)
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    img = Image('assets/img/img-min.png')
    img.width = 180
    img.height = 160
    worksheet.add_image(img, 'M1')

    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    abc_list = []
    for letter in string.ascii_uppercase:
        abc_list.append(letter)
    a = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH']
    abc_list.extend(a)
    for abc in abc_list[8:18]:
        worksheet[f'{abc}14'].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')
        )
    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__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',
                                              'ware_house_accepted_real_weight', 'ware_house_accepted_real_quantity')

    if filtered_kill_reqs.exists():
        name = filtered_kill_reqs.first().killhouse_user.kill_house_operator.user.province.name
        worksheet[
            'E13'] = f'گزارش جامع خریداران در فرآیند کشتار مرغ گوشتی استان {name}    از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    else:
        worksheet[
            'E13'] = f'گزارش جامع خریداران در فرآیند کشتار مرغ گوشتی    از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    worksheet['I14'] = 'حجم کل بارهای ایجاد شده  ( زنده)'
    worksheet['K14'] = 'حجم کل بارهای تحویلی کشتارگاه( زنده)'
    worksheet['M14'] = 'وزن نهایی با افت 25%'
    worksheet['N14'] = 'ورودی به انبار کشتارگاه(لاشه)'
    worksheet['P14'] = 'درصد لاشه ورودی به انبار کشتارگاه نسبت به بار تحویلی کشتارگاه(با افت 25 %)'
    worksheet['R14'] = 'درصد بار تحویلی نسبت به بار ایجاد شده'
    worksheet['M10'] = 'سامانه رصدیار'
    if filtered_kill_reqs:
        first = filtered_kill_reqs.first().killhouse_user.kill_house_operator.user.province.name
        worksheet['M11'] = f'استان {first}'
        merge_range111 = 'M11:O11'
        worksheet.merge_cells(merge_range111)

    worksheet.row_dimensions[14].height = 42

    worksheet['E13'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['I14'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['K14'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['M14'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['N14'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['P14'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['R14'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['M11'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['M10'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    merge_range1 = 'E13:X13'
    merge_range2 = 'I14:J15'
    merge_range3 = 'K14:L15'
    merge_range4 = 'M14:M16'
    merge_range5 = 'N14:O15'
    merge_range6 = 'P14:Q15'
    merge_range7 = 'R14:S15'
    merge_range8 = 'M10:O10'

    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['E13'].font = Font(size=18, bold=True)
    worksheet['P14'].font = Font(size=9, bold=True)
    worksheet['M10'].font = Font(size=12, bold=True)

    worksheet['I14'].fill = PatternFill(start_color="FFFF00", fill_type="solid")
    worksheet['K14'].fill = PatternFill(start_color="FFFF00", fill_type="solid")
    worksheet['N14'].fill = PatternFill(start_color="FFFF00", fill_type="solid")
    worksheet['M14'].fill = PatternFill(start_color="FCE4D6", fill_type="solid")
    worksheet['P14'].fill = PatternFill(start_color="F8CBAD", fill_type="solid")
    worksheet['R14'].fill = PatternFill(start_color="F8CBAD", fill_type="solid")
    list1 = [' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن', ' تعداد', 'وزن']
    for item in range(4):
        cell = worksheet.cell(row=16, column=item + 9, value=list1[item])
        worksheet.row_dimensions[16].height = 24

        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')
        )
    for item in range(6):
        cell = worksheet.cell(row=16, column=item + 14, value=list1[item])
        worksheet.row_dimensions[16].height = 24

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

    all_kill_req_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity' or 0)

    weight = filtered_kill_reqs.aggregate(
        total_quantity=Sum(
            F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[
        'total_quantity']

    all_kill_req_quantity_reciver = filtered_kill_reqs.aggregate(
        total_quantity=Sum('accepted_real_quantity')).get(
        'total_quantity' or 0)
    all_kill_req_weight_reciver = filtered_kill_reqs.aggregate(
        total_quantity=Sum('accepted_real_weight')).get(
        'total_quantity' or 0)
    all_ware_house_accepted_real_quantity = filtered_kill_reqs.aggregate(
        total_quantity=Sum('ware_house_accepted_real_quantity')).get(
        'total_quantity' or 0)
    all_ware_house_accepted_real_weight = filtered_kill_reqs.aggregate(
        total_quantity=Sum('ware_house_accepted_real_weight')).get(
        'total_quantity' or 0)
    if all_kill_req_quantity:
        list_1 = [
            all_kill_req_quantity,
            weight,
            all_kill_req_quantity_reciver,
            all_kill_req_weight_reciver,
            (int(all_kill_req_weight_reciver) * 75) / 100,
            all_ware_house_accepted_real_quantity,
            all_ware_house_accepted_real_weight,
            f'{int(all_ware_house_accepted_real_quantity * 100 / all_kill_req_quantity_reciver)}%',
            f"{int(all_ware_house_accepted_real_weight * 100 / all_kill_req_weight_reciver)}%",
            f"{int(all_kill_req_quantity_reciver * 100 / all_kill_req_quantity)}%",
            f'{int((all_kill_req_weight_reciver * 100) / weight)}%'
        ]
        for item in range(len(list_1)):
            cell = worksheet.cell(row=17, column=item + 9, value=list_1[item])
            value = list_1[item]
            if isinstance(value, (int, float)):
                cell.number_format = '#,##0'
            else:
                cell.value = value

            cell.alignment = Alignment(horizontal='center', vertical='center', )
            cell.font = Font(size=10, bold=True)
            cell.font = Font(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')
            )

    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)

    worksheet.row_dimensions[21].height = 36
    for abc in abc_list[5:21]:
        worksheet[f'{abc}20'].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['F19'] = f'اطلاعات کلی توزیع و پخش مرغ گرم از تاریخ {tommorow_date_1} تا {tomorrow_date_2}'
    worksheet['F20'] = f'تعداد خریداران'
    worksheet['G20'] = f'کشتار داخل استان'
    worksheet['I20'] = f'خرید خارج از استان'
    worksheet['K20'] = f'جمع کل انبار'
    worksheet['M20'] = f'توزیع شده'
    worksheet['O20'] = f'توزیع / تحویل شده'
    worksheet['Q20'] = f'مانده انبار'
    worksheet['S20'] = f'درصد توزیع نسبت به وردی به انبار'
    worksheet['T20'] = f'تعداد مباشر تخصیص داده شده'
    worksheet['U20'] = f'تعداد صنف تخصیص داده شده'

    worksheet['F19'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['F20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['G20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['I20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['K20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['M20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['O20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['Q20'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['S20'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['T20'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['U20'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    merge_range = 'F19:U19'
    merge_range1 = 'F20:F22'
    merge_range2 = 'G20:H21'
    merge_range3 = 'I20:J21'
    merge_range4 = 'K20:L21'
    merge_range5 = 'M20:N21'
    merge_range6 = 'O20:P21'
    merge_range7 = 'Q20:R21'
    merge_range8 = 'S20:S22'
    merge_range9 = 'T20:T22'
    merge_range10 = 'U20:U22'

    worksheet.merge_cells(merge_range)
    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['F19'].font = Font(size=18, bold=True, color='FF0000')
    worksheet['F20'].font = Font(size=9)

    worksheet['F20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['G20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['I20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['K20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['M20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['O20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['Q20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['S20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['T20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    worksheet['U20'].fill = PatternFill(start_color="DDEBF7", fill_type="solid")
    for item in range(12):
        cell = worksheet.cell(row=22, column=item + 7, value=list1[item])
        worksheet.row_dimensions[22].height = 24

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

    filtered_kill_reqs_tommorow = 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__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',
                                              'ware_house_accepted_real_weight', 'ware_house_accepted_real_quantity',
                                              'killhouse_user__kill_house_operator__user__city__name')

    number_of_kill_house_tommorow = filtered_kill_reqs_tommorow.values(
        'killhouse_user').distinct().count() if filtered_kill_reqs_tommorow else 0

    kill_free_info_tommorow = KillHouseFreeBarInformation.objects.filter(trash=False, date__date__gte=tomorrow_date1,
                                                                         date__date__lte=tomorrow_date2).only(
        'weight_of_carcasses', 'number_of_carcasses')
    all_quantity_out_false_tommorow = filtered_kill_reqs_tommorow.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity' or 0)

    weight_tommorow = filtered_kill_reqs_tommorow.aggregate(
        total_quantity=Sum(
            F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[
        'total_quantity']
    all_quantity_out_true_tommorow = kill_free_info_tommorow.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity' or 0)
    all_weight_out_true_tomorow = kill_free_info_tommorow.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    kill_house_ware_houses_tommorow = KillHouseWareHouse.objects.filter(
        Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
            pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=tomorrow_date1,
        date__date__lte=tomorrow_date2, trash=False)
    final_total_number_of_carcasses_tommorow = \
        kill_house_ware_houses_tommorow.aggregate(total=Sum('final_total_number_of_carcasses'))[
            'total']
    final_total_weight_of_carcasses = \
        kill_house_ware_houses_tommorow.aggregate(total=Sum('final_total_weight_of_carcasses'))[
            'total']
    steward_allocations_tommorow = StewardAllocation.objects.filter(
        Q(type='manual') | Q(type='auto', system_registration_code=True),
        ware_house__in=kill_house_ware_houses_tommorow, receiver_state__in=('pending', 'accepted'),
        trash=False).order_by(
        'id')
    total_allocated_quantity = \
        steward_allocations_tommorow.aggregate(total=Sum('real_number_of_carcasses'))[
            'total']

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

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

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

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

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

    total_remain_weight = \
        kill_house_ware_houses_tommorow.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
            'total']
    steward_allocations_for_number_of_steward = steward_allocations_tommorow.filter(steward__isnull=False,
                                                                                    trash=False)
    number_of_steward = steward_allocations_for_number_of_steward.values(
        'steward').distinct().count() if steward_allocations_for_number_of_steward else 0

    guild_allocations_tommorow = steward_allocations_tommorow.filter(guilds__isnull=False, trash=False)
    number_of_guild = guild_allocations_tommorow.values(
        'guilds').distinct().count() if guild_allocations_tommorow else 0
    if filtered_kill_reqs_tommorow:
        list_1 = [
            number_of_kill_house_tommorow,
            all_quantity_out_false_tommorow if all_quantity_out_false_tommorow != None else 0,
            weight_tommorow,
            all_quantity_out_true_tommorow if all_quantity_out_true_tommorow != None else 0,
            all_weight_out_true_tomorow,
            final_total_number_of_carcasses_tommorow if final_total_number_of_carcasses_tommorow != 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,
            total_accepted_allocated_quantity,
            total_accepted_allocated_weight,
            total_remain_quantity if total_remain_quantity != None else 0,
            total_remain_weight if total_remain_weight != None else 0,
            f"{int((total_allocated_quantity * 100) / final_total_number_of_carcasses) if total_allocated_quantity and final_total_number_of_carcasses != None else 0}%",
            number_of_steward,
            number_of_guild,

        ]
        for item in range(len(list_1)):
            cell = worksheet.cell(row=23, column=item + 6, value=list_1[item])
            value = list_1[item]
            if isinstance(value, (int, float)):
                cell.number_format = '#,##0'
            else:
                cell.value = value

            cell.alignment = Alignment(horizontal='center', vertical='center', )
            cell.font = Font(size=10, bold=True)
            cell.font = Font(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')
            )

    for abc in abc_list:
        worksheet[f'{abc}27'].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.row_dimensions[27].height = 42
    for item in range(4):
        cell = worksheet.cell(row=29, column=item + 4, value=list1[item])
        worksheet.row_dimensions[29].height = 24

        cell.fill = PatternFill(start_color="92D050", 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')
        )

    for item in range(4):
        cell = worksheet.cell(row=29, column=item + 10, value=list1[item])
        worksheet.row_dimensions[29].height = 24

        cell.fill = PatternFill(start_color="92D050", 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')
        )
    for item in range(10):
        cell = worksheet.cell(row=29, column=item + 14, value=list1[item])
        worksheet.row_dimensions[29].height = 24

        cell.fill = PatternFill(start_color="9BC2E6", 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')
        )
    for item in range(2):
        cell = worksheet.cell(row=29, column=item + 27, value=list1[item])
        worksheet.row_dimensions[29].height = 24

        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')
        )
    for item in range(5):
        cell = worksheet.cell(row=29, column=item + 28, value=list1[item])
        worksheet.row_dimensions[29].height = 24

        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['I26'] = 'اطلاعات کلی بارها و توزیع خریداران '
    worksheet['A27'] = 'ردیف'
    worksheet['B27'] = 'خریدار'
    worksheet['C27'] = 'شهرستان'
    worksheet['D27'] = 'حجم کل بارهای ایجاد شده توسط کشتارگاه ( زنده)'
    worksheet['F27'] = 'حجم کل بارهای تحویلی توسط کشتارگاه( زنده)'
    worksheet['H27'] = 'وزن تحویلی با افت 25%'
    worksheet['I27'] = 'درصد تعداد قطعه بار ایجاد شده به تحویلی'
    worksheet['J27'] = 'ورودی به انبار کشتارگاه(لاشه)'
    worksheet['L27'] = 'درصد لاشه ورودی به انبار کشتارگاه نسبت به بارتحویلی کشتارگاه(با افت 25 %)'
    worksheet['N27'] = 'خرید خارج از استان'
    worksheet['P27'] = 'جمع کل انبار'
    worksheet['R27'] = 'توزیع شده'
    worksheet['T27'] = 'توزیع/تحویل شده'
    worksheet['V27'] = 'مانده انبار'
    worksheet['X27'] = 'درصد وزن مانده در انبار به ورودی انبار'
    worksheet['Y27'] = 'تعداد مباشر/ صنف '
    worksheet['Z27'] = 'بارهای تخلیه شده  و عدم تکمیل(تحویل)'
    worksheet['Z29'] = 'تعداد بار'
    worksheet['AC27'] = 'ورودی به انبار'
    worksheet['AC29'] = 'تعداد بار'
    worksheet['AD29'] = 'حجم بار'
    worksheet['AE29'] = 'وزن بار'
    worksheet['AF29'] = 'درصد افت'
    worksheet['AG27'] = 'بارهای فاقد قرنطینه و تخلیه شده'
    worksheet['AG29'] = 'تعداد بار'
    worksheet['AH29'] = 'درصد'
    worksheet['I27'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['A27'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['B27'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['C27'].alignment = Alignment(horizontal='center', vertical='center')
    worksheet['D27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['F27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['H27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['I27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['J27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['L27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['N27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['P27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['R27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['T27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['V27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['X27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['Y27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['Z27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['Z29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AF29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AE29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AD29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AC29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AC27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AG27'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AG29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    worksheet['AH29'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

    merge_range = 'A27:A29'
    merge_range1 = 'B27:B29'
    merge_range2 = 'C27:C29'
    merge_range3 = 'D27:E28'
    merge_range4 = 'F27:G28'
    merge_range5 = 'H27:H29'
    merge_range6 = 'I27:I29'
    merge_range7 = 'J27:K28'
    merge_range8 = 'L27:M28'
    merge_range9 = 'N27:O28'
    merge_range10 = 'P27:Q28'
    merge_range11 = 'R27:S28'
    merge_range12 = 'T27:U28'
    merge_range13 = 'V27:W28'
    merge_range14 = 'I26:R26'
    merge_range15 = 'X27:X29'
    merge_range16 = 'Y27:Y29'
    merge_range17 = 'Z27:AB28'
    merge_range18 = 'M1:O9'
    merge_range19 = 'AC27:AF28'
    merge_range20 = 'AG27:AH28'

    worksheet.merge_cells(merge_range)
    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.merge_cells(merge_range12)
    worksheet.merge_cells(merge_range13)
    worksheet.merge_cells(merge_range14)
    worksheet.merge_cells(merge_range15)
    worksheet.merge_cells(merge_range16)
    worksheet.merge_cells(merge_range17)
    worksheet.merge_cells(merge_range18)
    worksheet.merge_cells(merge_range19)
    worksheet.merge_cells(merge_range20)

    worksheet['A27'].fill = PatternFill(start_color="8EA9DB", fill_type="solid")
    worksheet['B27'].fill = PatternFill(start_color="8EA9DB", fill_type="solid")
    worksheet['C27'].fill = PatternFill(start_color="8EA9DB", fill_type="solid")
    worksheet['D27'].fill = PatternFill(start_color="FFE699", fill_type="solid")
    worksheet['F27'].fill = PatternFill(start_color="FFE699", fill_type="solid")
    worksheet['H27'].fill = PatternFill(start_color="FFE699", fill_type="solid")
    worksheet['I27'].fill = PatternFill(start_color="FFE699", fill_type="solid")
    worksheet['J27'].fill = PatternFill(start_color="FFE699", fill_type="solid")
    worksheet['L27'].fill = PatternFill(start_color="FFE699", fill_type="solid")
    worksheet['N27'].fill = PatternFill(start_color="C9C9C9", fill_type="solid")
    worksheet['P27'].fill = PatternFill(start_color="C9C9C9", fill_type="solid")
    worksheet['R27'].fill = PatternFill(start_color="C9C9C9", fill_type="solid")
    worksheet['T27'].fill = PatternFill(start_color="C9C9C9", fill_type="solid")
    worksheet['V27'].fill = PatternFill(start_color="C9C9C9", fill_type="solid")
    worksheet['X27'].fill = PatternFill(start_color="F8CBAD", fill_type="solid")
    worksheet['Y27'].fill = PatternFill(start_color="F8CBAD", fill_type="solid")
    worksheet['Z27'].fill = PatternFill(start_color="FFFF00", fill_type="solid")
    worksheet['Z29'].fill = PatternFill(start_color="FFD966", fill_type="solid")
    worksheet['AC29'].fill = PatternFill(start_color="FFD966", fill_type="solid")
    worksheet['AD29'].fill = PatternFill(start_color="FFD966", fill_type="solid")
    worksheet['AE29'].fill = PatternFill(start_color="FFD966", fill_type="solid")
    worksheet['AF29'].fill = PatternFill(start_color="FFD966", fill_type="solid")
    worksheet['AC27'].fill = PatternFill(start_color="92CDDC", fill_type="solid")
    worksheet['AG27'].fill = PatternFill(start_color="00B050", fill_type="solid")
    worksheet['AH29'].fill = PatternFill(start_color="FFD966", fill_type="solid")
    worksheet['AG29'].fill = PatternFill(start_color="FFD966", fill_type="solid")

    worksheet['L27'].font = Font(size=8)
    worksheet['X27'].font = Font(size=9)
    worksheet['I26'].font = Font(size=17)

    l = 30
    m = 1
    all_all_kill_req_quantity = 0
    all_weight = 0
    all_all_kill_req_quantity_reciver = 0
    all_all_kill_req_weight_reciver = 0
    all_twenty_five_percent = 0
    all_reciver_percent = 0
    all_final_total_number_of_carcasses = 0
    all_final_total_weight_of_carcasses = 0
    all_lashe_25_percent = 0
    all_weight_lashe_25_percent = 0
    all_all_quantity_out_true = 0
    all_all_weight_out_true = 0
    all_total_allocated_quantity = 0
    all_total_allocated_weight = 0
    all_total_accepted_allocated_quantity = 0
    all_total_accepted_allocated_weight = 0
    all_total_remain_quantity = 0
    all_total_remain_weight = 0
    all_all_num = 0
    all_remain_percent = 0
    all_len_tomorrow_kill_request_not_assigment = 0
    all_all_kill_req_quantity_not_assigment = 0
    all_all_kill_req_weight_not_assigment = 0
    all_all_ware_house_accepted_real_quantity = 0
    all_len_kill_req1 = 0
    all_ware_house_accepted_real_weight = 0
    all_ware_house_accepted_real_quantity = 0
    all_weight_loss = 0
    all_hasnt_code = 0
    all_percent_hasnt_code = 0
    kill_houses = KillHouse.objects.filter(trash=False).select_related('kill_house_operator__user__city').exclude(
        out_province=True)
    for kill_house in kill_houses:
        kill_free_information = kill_free_info_tommorow.filter(kill_house=kill_house)
        tomorrow_kill_request = filtered_kill_reqs_tommorow.filter(killhouse_user=kill_house)
        if tomorrow_kill_request:
            tomorrow_kill_request_not_assigment = tomorrow_kill_request.filter(assignment_state_archive='pending',
                                                                               vet_state='accepted')
            all_kill_req_quantity = tomorrow_kill_request.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity' or 0)
            all_len_tomorrow_kill_request_not_assigment += len(tomorrow_kill_request_not_assigment)
            all_all_kill_req_quantity += all_kill_req_quantity

            all_kill_req_quantity_reciver = tomorrow_kill_request.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity' or 0)
            all_all_kill_req_quantity_reciver += all_kill_req_quantity_reciver
            all_kill_req_weight_reciver = tomorrow_kill_request.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity' or 0)
            all_all_kill_req_weight_reciver += all_kill_req_weight_reciver
            all_ware_house_accepted_real_quantity = tomorrow_kill_request.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                'total_quantity' or 0)
            weight = tomorrow_kill_request.aggregate(
                total_quantity=Sum(
                    F('quantity') * F('province_kill_request__province_request__poultry_request__Index_weight')))[
                'total_quantity']
            all_weight += weight
            kill_house_ware_houses = KillHouseWareHouse.objects.filter(
                Q(weight_of_carcasses__gt=0) | Q(free_weight_of_carcasses__gt=0) | Q(
                    pre_cold_weight_of_carcasses_to_ware_house__gt=0), date__date__gte=tomorrow_date1,
                date__date__lte=tomorrow_date2, kill_house=kill_house, trash=False)

            steward_allocations = StewardAllocation.objects.filter(
                Q(type='manual') | Q(type='auto', system_registration_code=True),
                ware_house__in=kill_house_ware_houses, receiver_state__in=('pending', 'accepted'),
                trash=False).order_by(
                'id')
            total_allocated_quantity = \
                steward_allocations.aggregate(total=Sum('real_number_of_carcasses'))[
                    'total']
            all_total_allocated_quantity += total_allocated_quantity if total_allocated_quantity != None else 0
            total_allocated_weight = \
                steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                    'total']
            all_total_allocated_weight += total_allocated_weight if total_allocated_weight != None else 0
            total_accepted_allocated_quantity = \
                steward_allocations.aggregate(total=Sum('receiver_real_number_of_carcasses'))[
                    'total']
            all_total_accepted_allocated_quantity += total_accepted_allocated_quantity if total_accepted_allocated_quantity != None else 0
            total_accepted_allocated_weight = \
                steward_allocations.aggregate(total=Sum('receiver_real_weight_of_carcasses'))[
                    'total']
            all_total_accepted_allocated_weight += total_accepted_allocated_weight if total_accepted_allocated_weight != None else 0

            total_remain_quantity = \
                kill_house_ware_houses.aggregate(total=Sum('remain_total_number_of_carcasses'))[
                    'total']
            all_total_remain_quantity += total_remain_quantity if total_remain_quantity != None else 0
            total_remain_weight = \
                kill_house_ware_houses.aggregate(total=Sum('remain_total_weight_of_carcasses'))[
                    'total']
            all_total_remain_weight += total_remain_weight if total_remain_weight != None else 0
            final_total_number_of_carcasses = \
                kill_house_ware_houses.aggregate(total=Sum('final_total_number_of_carcasses'))[
                    'total'] or 0
            all_final_total_number_of_carcasses += final_total_number_of_carcasses if final_total_number_of_carcasses != None else 0

            final_total_weight_of_carcasses = \
                kill_house_ware_houses.aggregate(total=Sum('final_total_weight_of_carcasses'))[
                    'total'] or 0
            all_final_total_weight_of_carcasses += final_total_weight_of_carcasses if final_total_weight_of_carcasses != None 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

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

            all_kill_req_quantity_not_assigment = tomorrow_kill_request_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_quantity')).get(
                'total_quantity') or 0
            all_all_kill_req_quantity_not_assigment += all_kill_req_quantity_not_assigment if all_kill_req_quantity_not_assigment != None else 0
            all_kill_req_weight_not_assigment = tomorrow_kill_request_not_assigment.aggregate(
                total_quantity=Sum('accepted_real_weight')).get(
                'total_quantity') or 0
            all_all_kill_req_weight_not_assigment += all_kill_req_weight_not_assigment if all_kill_req_weight_not_assigment != None else 0
            all_quantity_out_true = kill_free_information.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            all_all_quantity_out_true += all_quantity_out_true if all_quantity_out_true != None else 0
            all_weight_out_true = kill_free_information.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity' or 0)
            all_all_weight_out_true += all_weight_out_true if all_weight_out_true != None else 0
            twenty_five_percent = (int(all_kill_req_weight_reciver) * 75) / 100
            all_twenty_five_percent += twenty_five_percent if twenty_five_percent > 0 else 0
            reciver_percent = (
                                      int(all_kill_req_quantity_reciver) * 100) / all_kill_req_quantity if all_kill_req_quantity_reciver != None else 0
            all_reciver_percent += reciver_percent if reciver_percent > 0 else 0
            lashe_25_percent = int(
                final_total_number_of_carcasses * 100 / all_kill_req_quantity_reciver) if final_total_number_of_carcasses != None else 0
            all_lashe_25_percent += lashe_25_percent if lashe_25_percent > 0 else 0
            weight_lashe_25_percent = int(
                final_total_weight_of_carcasses * 100 / all_kill_req_weight_reciver) if final_total_weight_of_carcasses != None else 0
            all_weight_lashe_25_percent += weight_lashe_25_percent if weight_lashe_25_percent > 0 else 0
            remain_percent = int((
                                         total_remain_quantity * 100) / all_ware_house_accepted_real_quantity) if total_remain_quantity != None and all_ware_house_accepted_real_quantity > 0 else 0
            all_remain_percent += remain_percent if remain_percent > 0 else 0
            all_num = number_of_steward + number_of_guild
            all_all_num += all_num if all_num > 0 else 0

            kill_req = filtered_kill_reqs_tommorow.filter(ware_house_confirmation=True,
                                                          killhouse_user=kill_house)
            all_len_kill_req1 += len(kill_req)
            ware_house_accepted_real_quantity = kill_req.aggregate(
                total_quantity=Sum('ware_house_accepted_real_quantity')).get(
                'total_quantity') or 0

            ware_house_accepted_real_weight = kill_req.aggregate(
                total_quantity=Sum('ware_house_accepted_real_weight')).get(
                'total_quantity') or 0
            weight_loss1 = kill_req.aggregate(
                total_quantity=Sum('weight_loss')).get(
                'total_quantity') or 0
            weight_loss = weight_loss1 / len(kill_req) if len(kill_req) > 0 else 0
            all_ware_house_accepted_real_weight += ware_house_accepted_real_weight
            all_ware_house_accepted_real_quantity += ware_house_accepted_real_quantity
            all_weight_loss += int(weight_loss1)
            all_all_ware_house_accepted_real_quantity += ware_house_accepted_real_quantity
            hasnt_code = len(tomorrow_kill_request.filter(assignment_state_archive='True', clearance_code__isnull=True))
            percent_hasnt_code = round(hasnt_code * 100 / len(tomorrow_kill_request)) if len(
                tomorrow_kill_request) > 0 else 0

            all_hasnt_code += hasnt_code
            all_percent_hasnt_code += percent_hasnt_code
            list_1 = [
                m,
                kill_house.name,
                kill_house.city_name,
                all_kill_req_quantity,
                weight,
                all_kill_req_quantity_reciver,
                all_kill_req_weight_reciver,
                twenty_five_percent,
                f'{int(reciver_percent)}%',
                final_total_number_of_carcasses,
                final_total_weight_of_carcasses,
                f'{lashe_25_percent}%',
                f"{weight_lashe_25_percent}%",
                all_quantity_out_true,
                all_weight_out_true,
                final_total_number_of_carcasses,
                final_total_weight_of_carcasses,
                total_allocated_quantity,
                total_allocated_weight,
                total_accepted_allocated_quantity,
                total_accepted_allocated_weight,
                total_remain_quantity if total_remain_quantity != None else 0,
                total_remain_weight if total_remain_weight != None else 0,
                f'{remain_percent}%',
                all_num,
                len(tomorrow_kill_request_not_assigment),
                all_kill_req_quantity_not_assigment,
                all_kill_req_weight_not_assigment,
                len(kill_req),
                ware_house_accepted_real_quantity,
                ware_house_accepted_real_weight,
                f"{int(weight_loss)}%",
                hasnt_code,
                f"{percent_hasnt_code}%",

            ]
            for item in range(len(list_1)):
                cell = worksheet.cell(row=l, column=item + 1, value=list_1[item])
                value = list_1[item]
                if isinstance(value, (int, float)):
                    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)
                cell.font = Font(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

    for abc in abc_list[:1]:
        worksheet[f'{abc}{l}'].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.row_dimensions[int(f'{l}')].height = 24

    worksheet[f'A{l}'] = 'جمع کل'

    worksheet[f'A{l}'].alignment = Alignment(horizontal='center', vertical='center')
    merge_range = f'A{l}:C{l}'
    worksheet[f'A{l}'].fill = PatternFill(start_color="FFFF00", fill_type="solid")
    all_reciver_percent2 = (
                                   int(all_all_kill_req_quantity_reciver) * 100) / all_all_kill_req_quantity if all_all_kill_req_quantity_reciver and all_all_kill_req_quantity > 0 else 0
    all_all_lashe_25_percent = int(
        all_final_total_number_of_carcasses * 100 / all_all_kill_req_quantity_reciver) if all_final_total_number_of_carcasses > 0 else 0
    all_all_weight_lashe_25_percent = int(
        all_final_total_weight_of_carcasses * 100 / all_all_kill_req_weight_reciver) if all_final_total_weight_of_carcasses > 0 else 0
    all_all_all_remain_percent = int((
                                             all_total_remain_quantity * 100) / all_all_ware_house_accepted_real_quantity) if all_total_remain_quantity > 0 and all_all_ware_house_accepted_real_quantity > 0 else 0
    worksheet.merge_cells(merge_range)
    list2 = [
        all_all_kill_req_quantity,
        all_weight,
        all_all_kill_req_quantity_reciver,
        all_all_kill_req_weight_reciver,
        all_twenty_five_percent,
        f'{int(all_reciver_percent2)}%',
        all_final_total_number_of_carcasses,
        all_final_total_weight_of_carcasses,
        f'{all_all_lashe_25_percent}%',
        f'{all_all_weight_lashe_25_percent}%',
        all_all_quantity_out_true,
        all_all_weight_out_true,
        all_final_total_number_of_carcasses,
        all_final_total_weight_of_carcasses,
        all_total_allocated_quantity,
        all_total_allocated_weight,
        all_total_accepted_allocated_quantity,
        all_total_accepted_allocated_weight,
        all_total_remain_quantity,
        all_total_remain_weight,
        f'{all_all_all_remain_percent}%',
        all_all_num,
        all_len_tomorrow_kill_request_not_assigment,
        all_all_kill_req_quantity_not_assigment,
        all_all_kill_req_weight_not_assigment,
        all_len_kill_req1,
        all_all_ware_house_accepted_real_quantity,
        all_ware_house_accepted_real_weight,
        f"{int(all_weight_loss / all_len_kill_req1 if all_len_kill_req1 > 0 else 0)}%",
        all_hasnt_code,
        f"{int(all_hasnt_code / all_len_kill_req1 if all_len_kill_req1 > 0 else 0)}%",

    ]
    for item in range(len(list2)):
        cell = worksheet.cell(row=l, column=item + 4, 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', vertical='center')
        cell.font = Font(bold=True)
        cell.fill = PatternFill(start_color="FFFF00", fill_type="solid")
        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.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 out_province_carcasses_buyer_kill_house_excel(request):
    filterset_class = OutProvinceCarcassesBuyerFilterSet
    filterset_fields = [
        'mobile',
        'first_name',
        'last_name',
        'fullname',
        'unit_name',

    ]
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    buyers = OutProvinceCarcassesBuyer.objects.filter(trash=False, Kill_house=kill_house).order_by('id')

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

    excel_options = [
        'ردیف',
        'خریدار',
        'تلفن خریدار',
        'نام واحد',
        'استان',
        'شهر',
        'تعداد درخواست ها',
        'حجم درخواست ها',
        'وزن درخواست ها',

    ]

    header_list = [
        'تعداد خریداران',
        'تعداد کل درخواست ها',
        'حجم کل درخواست ها',
        'وزن کل درخواست ها',

    ]

    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)

    excel_description(worksheet, 'A1', f' خریداران لاشه خارج استان کشتارگاه {kill_house.name}', color='red', row2='B1')

    if kill_house:
        province = kill_house.kill_house_operator.user.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 = 5
    m = 1
    free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, buyer__in=buyers)

    for buyer in buyers:
        free_sale = free_sales.filter(buyer=buyer)

        total_quantity = free_sale.aggregate(total=Sum('number_of_carcasses'))[
                             'total'] or 0
        total_weight = free_sale.aggregate(total=Sum('weight_of_carcasses'))[
                           'total'] or 0
        list1 = [
            m,
            buyer.fullname,
            buyer.mobile,
            buyer.unit_name,
            buyer.province,
            buyer.city,
            len(free_sale),
            total_quantity,
            total_weight

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

        m += 1
        l += 1

    free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, buyer__in=buyers)

    total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[
                         'total'] or 0
    total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[
                       'total'] or 0

    value_list = [
        len(buyers),
        len(free_sales),
        total_quantity,
        total_weight,
    ]
    create_value(worksheet, value_list, 3, 3)

    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        len(free_sales),
        total_quantity,
        total_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=" خریداران لاشه خارج استان کشتارگاه {kill_house.name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_free_sale_bar_information_for_excel_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
    filterset_class = OutProvinceCarcassesBuyerFilterSet
    filterset_fields = [
        'mobile',
        'first_name',
        'last_name',
        'fullname',
        'unit_name',

    ]
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False, date__date__gte=date1,
                                                            date__date__lte=date2).order_by('-date')
    len_buyers = []
    sheet_names2 = [
        'فروش لاشه خارج استان',
        'خریداران',

    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    for name in sheet_names2:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        if sheet_name == 'فروش لاشه خارج استان':
            value = request.GET.get('value')
            search = request.GET.get('filter')
            if value and search == 'search':
                if value != 'undefined' and value.strip():
                    buyers = buyers.filter(
                        build_query(filterset_class, value)
                    )

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

            ]

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

            ]

            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)

            excel_description(worksheet, 'A1', f'فروش لاشه خارج استان کشتارگاه {kill_house.name}', color='red',
                              row2='B1')
            from_date1 = shamsi_date(date1)
            from_date2 = shamsi_date(date2)
            excel_description(worksheet, 'A3', f'از تاریخ {from_date1} تا {from_date2}', color='red', row2='B3')

            if kill_house:
                province = kill_house.kill_house_operator.user.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 = 5
            m = 1

            for buyer in buyers:
                date = jdatetime.date.fromgregorian(
                    day=buyer.date.day,
                    month=buyer.date.month,
                    year=buyer.date.year
                )
                if buyer.buyer_name not in len_buyers:
                    len_buyers.append(buyer.buyer_name)
                list1 = [
                    m,
                    buyer.kill_house.name,
                    buyer.kill_house.kill_house_operator.user.mobile,
                    str(date),
                    buyer.buyer_name,
                    buyer.buyer_mobile,
                    buyer.buyer_name,
                    buyer.province,
                    buyer.city,
                    buyer.number_of_carcasses,
                    buyer.weight_of_carcasses,

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

                m += 1
                l += 1

            total_quantity = buyers.aggregate(total=Sum('number_of_carcasses'))[
                                 'total'] or 0
            total_weight = buyers.aggregate(total=Sum('weight_of_carcasses'))[
                               'total'] or 0

            value_list = [
                len(buyers),
                len(len_buyers),
                total_quantity,
                total_weight,
            ]
            create_value(worksheet, value_list, 3, 3)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                total_quantity,
                total_weight,

            ]
            create_value(worksheet, list2, l + 3, 1, color='green')

        else:
            out_buyers = OutProvinceCarcassesBuyer.objects.filter(Kill_house=kill_house, trash=False).order_by('id')
            excel_options = [
                'ردیف',
                'نام خریدار',
                'موبایل خریدار',
                'نام واحد',
                'استان',
                'شهر',
                'تعداد درخواست ها',
                'حجم تقریبی(قطعه)',
                'وزن(کلوگرم)',

            ]

            cell = worksheet.cell(row=1, column=1)
            cell.alignment = Alignment(horizontal='center', vertical='center')

            excel_description(worksheet, 'A1', f'خریداران کشتارگاه {kill_house.name}', color='red',
                              row2='B1')

            if kill_house:
                province = kill_house.kill_house_operator.user.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 = 5
            m = 1

            for buyer in out_buyers:
                free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, buyer=buyer)

                total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[
                                     'total'] or 0
                total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[
                                   'total'] or 0

                list1 = [
                    m,
                    buyer.buyer.fullname,
                    buyer.buyer.mobile,
                    buyer.buyer.unit_name,
                    buyer.buyer.province,

                    buyer.buyer.city,
                    len(free_sales),
                    total_quantity,
                    total_weight,

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

                m += 1
                l += 1

            # total_quantity = buyers.aggregate(total=Sum('number_of_carcasses'))[
            #                      'total'] or 0
            # total_weight = buyers.aggregate(total=Sum('weight_of_carcasses'))[
            #                    'total'] or 0

            # list2 = [
            #     'مجموع==>',
            #     '',
            #     '',
            #     '',
            #     '',
            #     '',
            #     '',
            #     '',
            #     total_quantity,
            #     total_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="فروش لاشه خارج استان کشتارگاه {kill_house.name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_free_sale_bar_information_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
    filterset_class = OutProvinceCarcassesBuyerFilterSet
    filterset_fields = [
        'mobile',
        'first_name',
        'last_name',
        'fullname',
        'unit_name',

    ]
    # user = SystemUserProfile.objects.get(key=request.GET['key'],trash=False)
    # kill_house = KillHouse.objects.filter(kill_house_operator__user=user,trash=False).first()
    buyers = KillHouseFreeSaleBarInformation.objects.filter(trash=False, date__date__gte=date1,
                                                            date__date__lte=date2).order_by('-date')

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

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

    ]

    header_list = [
        'تعداد کل لاشه',
        'حجم کل لاشه',
        'وزن کل لاشه',

    ]

    kill_houses = buyers.values_list('kill_house__name', flat=True).distinct()
    sheet_name = 'اطلاعات کلی'
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    worksheet = workbook.create_sheet(sheet_name)
    kill_houses = set(kill_houses)
    date_1 = shamsi_date(date1)
    date_2 = shamsi_date(date2)
    if sheet_name == 'اطلاعات کلی':
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)

        province = buyers.first().kill_house.kill_house_operator.user.province.name
        excel_description(worksheet, 'F2',
                          f'اطلاعات کلی فروش لاشه به خارج استان {province} از تاریخ {date_1} تا {date_2}', color='red',
                          row2='K2')
        excel_description(worksheet, 'E5', f'اطلاعات کلی', color='red', row2='F5')
        create_header(worksheet, header_list, 7, 5, height=21, width=16.01)
        total_quantity = buyers.aggregate(total=Sum('number_of_carcasses'))[
                             'total'] or 0
        total_weight = buyers.aggregate(total=Sum('weight_of_carcasses'))[
                           'total'] or 0
        general_list = [
            len(buyers),
            total_quantity,
            total_weight
        ]
        create_value(worksheet, general_list, 6, 7, border_style='thin')
        l = 10
        for kill_house in list(kill_houses):
            excel_description(worksheet, f'E{l}', f'کشتار گاه {kill_house}', color='red', row2=f'F{l}')
            create_header(worksheet, header_list, 7, l, height=21, width=16.01)
            free_sales = buyers.filter(trash=False, kill_house__name=kill_house)
            total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[
                                 'total'] or 0
            total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[
                               'total'] or 0
            general_list = [
                len(free_sales),
                total_quantity,
                total_weight
            ]
            create_value(worksheet, general_list, l + 1, 7, border_style='thin')
            l += 4

    for kill_house in list(kill_houses):
        sheet_name = kill_house
        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')
        create_header(worksheet, header_list, 3, 2, height=21, width=16.01)

        excel_description(worksheet, 'A1', f' فروش لاشه خارج استان کشتارگاه {kill_house} ', color='red', row2='B1')
        excel_description(worksheet, 'A3', f'از تاریخ {date_1} تا {date_2}', color='red', row2='B3')
        create_header_freez(worksheet, excel_options, 1, 5, 6, height=19, width=21.01)

        l = 5
        m = 1
        free_sales = buyers.filter(trash=False, kill_house__name=kill_house)

        for buyer in free_sales:
            date = jdatetime.date.fromgregorian(
                day=buyer.date.day,
                month=buyer.date.month,
                year=buyer.date.year
            )
            list1 = [
                m,
                buyer.kill_house.name,
                buyer.kill_house.kill_house_operator.user.mobile,
                str(date),
                buyer.buyer_name,
                buyer.buyer_mobile,
                buyer.buyer_name,
                buyer.province,
                buyer.city,
                buyer.number_of_carcasses,
                buyer.weight_of_carcasses,

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

            m += 1
            l += 1

        total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[
                             'total'] or 0
        total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[
                           'total'] or 0

        value_list = [
            len(free_sales),
            total_quantity,
            total_weight,
        ]
        create_value(worksheet, value_list, 3, 3)

        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            total_quantity,
            total_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 notentered_bars_for_kill_house_excel(request):
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
        'system_address__province').first()

    if 'date1' in request.GET and request.GET['date1']:

        date1 = datetime.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(killhouse_user=kill_house) | Q(killer=kill_house),
            kill_request__recive_date__date__gte=date1,
            kill_request__recive_date__date__lte=date2,
            ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
            '-kill_request__recive_date').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',
                                                  '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',
            'bar_document_status__title'
        )
    else:
        filtered_kill_reqs = KillHouseRequest.objects.filter(
            Q(killhouse_user=kill_house) | Q(killer=kill_house),
            ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
            '-kill_request__recive_date').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',
                                                  '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',
            'bar_document_status__title'
        )

    if 'search' in request.GET:
        filtered_kill_reqs = []
        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()
                filtered_kill_reqs = [] if len(filtered_kill_reqs) == 0 else filtered_kill_reqs

    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 = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'نوع کشتار',
        'کدسفارش مرغدار',
        'نام و نام خانوادگی مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'نام فارم',
        'فروش',

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

    ]

    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_CELL

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

    ]

    # برای بالای هدر
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    create_header(worksheet, header_list2, 6, 4, height=21.8, color='green')

    create_header(worksheet, header_list, 9, 4, height=21.8)

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

    ]
    create_header(worksheet, header_list2, 6, 1, height=21.8, color='FF0000')
    products = RolesProducts.objects.filter(kill_house=kill_house, trash=False)
    q = 2
    w = 1
    for product in products:
        value_header_list = [
            w,
            product.name,
            product.province_governmental_carcasses_weight,
            product.province_free_carcasses_weight,
            product.free_buying_carcasses_weight,
            product.total_carcasses_weight,
            product.real_allocated_weight,
            product.total_remain_weight,

        ]
        create_value(worksheet, value_header_list, q, 6)
        q += 1
        w += 1

    kill_house_name = ''
    if filtered_kill_reqs.exists():
        kill_house_name = filtered_kill_reqs.first()['killhouse_user__name']
    excel_description(worksheet, 'A1', f'بارهای {kill_house_name} در انتظار ورود به انبار (کشتار داخل استان)', size=11,
                      color='red', row2='E1')
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})', row2='C3')

    m = 1

    create_header_freez(worksheet, excel_options, 1, 7, 8, 20)
    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
    }
    l = 7
    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 '-'
            net_weighte, real_quantity, 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_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'],
                int(kill['accepted_real_weight']),
                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,

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

    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 entered_bars_for_kill_house_excel(request):
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
        'system_address__province').first()

    if 'date1' in request.GET and request.GET['date1']:

        date1 = datetime.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(killhouse_user=kill_house) | Q(killer=kill_house),
            kill_request__recive_date__date__gte=date1,
            kill_request__recive_date__date__lte=date2,
            ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
            '-kill_request__recive_date').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',
                                                  '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',
            'bar_document_status__title'
        )
    else:
        filtered_kill_reqs = KillHouseRequest.objects.filter(
            Q(killhouse_user=kill_house) | Q(killer=kill_house),
            ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
            '-kill_request__recive_date').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',
                                                  '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',
            'bar_document_status__title'
        )

    if 'search' in request.GET:
        filtered_kill_reqs = []
        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()
                filtered_kill_reqs = [] if len(filtered_kill_reqs) == 0 else filtered_kill_reqs

    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 = [
        'ردیف',
        'کد بار',
        ' تاریخ کشتار',
        'نوع کشتار',
        'کدسفارش مرغدار',
        'نام و نام خانوادگی مرغدار',
        'تلفن مرغدار',
        ' شهر مرغدار',
        'نام فارم',
        'فروش',

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

    ]

    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_CELL

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

    ]

    # برای بالای هدر
    header_list2 = [
        'تعداد درخواست مرغداران',
        ' مجموع تعداد قطعه درخواست مرغداران',
        ' مجموع وزن درخواست مرغداران',

    ]
    create_header(worksheet, header_list2, 6, 4, height=21.8, color='green')

    create_header(worksheet, header_list, 9, 4, height=21.8)

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

    ]
    create_header(worksheet, header_list2, 6, 1, height=21.8, color='FF0000')
    products = RolesProducts.objects.filter(kill_house=kill_house, trash=False)
    q = 2
    w = 1
    for product in products:
        value_header_list = [
            w,
            product.name,
            product.province_governmental_carcasses_weight,
            product.province_free_carcasses_weight,
            product.free_buying_carcasses_weight,
            product.total_carcasses_weight,
            product.real_allocated_weight,
            product.total_remain_weight,

        ]
        create_value(worksheet, value_header_list, q, 6)
        q += 1
        w += 1

    kill_house_name = ''
    if filtered_kill_reqs.exists():
        kill_house_name = filtered_kill_reqs.first()['killhouse_user__name']
    excel_description(worksheet, 'A1', f'بارهای {kill_house_name} وارد شده به انبار (کشتار داخل استان)', size=11,
                      color='red', row2='E1')
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})', row2='C3')

    m = 1

    create_header_freez(worksheet, excel_options, 1, 7, 8, 20)
    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
    }
    l = 7
    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 '-'
            net_weighte, real_quantity, 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_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'],
                int(kill['accepted_real_weight']),
                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,

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

    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_free_bar_entered_for_warehouse_excel(request):
    filterset_class = KillHouseFreeBarInformationFilterSet
    filterset_fields = [
        'kill_house__name',
        'poultry_name',
        'poultry_mobile',
        'province',
        'city',
        'driver_name',
        'driver_mobile',
        'clearance_code',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',

    ]

    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    type = request.GET.get('type')
    date_type = request.GET.get('date_type')
    bar_state = request.GET.get('bar_state')
    kill_house_free_bar_info_list = []
    role = request.GET.get('role')
    kill_houses = None
    order_by_type = '-create_date'

    if role in ['KillHouse', 'KillHouseVet']:
        if role == 'KillHouse':
            kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
        else:
            kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                  flat=True)
            kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if date_type:
            if date_type == 'buy':

                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
            else:
                order_by_type = '-date'
                filters = {
                    'date__date__gte': date1,
                    'date__date__lte': date2,
                    'trash': False,
                }
        else:
            filters = {
                'create_date__date__gte': date1,
                'create_date__date__lte': date2,
                'trash': False,
            }
    else:
        filters = {
            'trash': False
        }

    if kill_houses is not None:
        filters['kill_house__in'] = kill_houses

    if type:
        filters['buy_type'] = type
        if type == 'live':
            if bar_state:
                if bar_state == 'entered':
                    filters['weight_of_carcasses__gt'] = 0
                else:
                    filters['weight_of_carcasses'] = 0

    kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type)

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

    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)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    header_list2 = [
        'تعداد کل بار زنده',
        'حجم کل بار زنده',
        'وزن کل بار زنده',
        'تعداد کل بارهای وارد شده به انبار',
        'حجم کل بارهای  زنده وارد شده به انبار',
        'وزن کل بارهای زنده وارد شده به انبار',
        'وزن لاشه وارد شده به انبار',
        'کل بار وارد نشده به انبار',
        'حجم کل بار وارد نشده به انبار',
        'وزن کل بار وارد نشده به انبار',

    ]

    for col_num, option in enumerate(header_list2, 4):
        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
    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
    type = 'زنده' if request.GET['type'] == 'live' else 'لاشه'
    worksheet['B1'] = f'گزارش بار {type} خرید خارج از استان'

    if kill_house_free_bar_info.exists():
        name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name
        worksheet['A2'] = f'استان {name}'

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

    l = 5
    m = 1

    if kill_house_free_bar_info:
        for kill in kill_house_free_bar_info:
            l += 1

            if kill.kill_house_vet_state == 'accepted':
                state = 'تایید شده'
            elif kill.kill_house_vet_state == 'pending':
                state = 'درانتظار تایید'
            else:
                state = 'رد شده'

            if kill.buy_type == 'live':
                buy_type = 'زنده'
            else:
                buy_type = 'لاشه'

            date_of_buy = jdatetime.date.fromgregorian(
                day=kill.create_date.day,
                month=kill.create_date.month,
                year=kill.create_date.year
            )

            if kill.date_of_accept_reject:
                date_of_reject_accepted = jdatetime.date.fromgregorian(
                    day=kill.date_of_accept_reject.day,
                    month=kill.date_of_accept_reject.month,
                    year=kill.date_of_accept_reject.year
                )
            else:
                date_of_reject_accepted = '-'
            date_of_enter = jdatetime.date.fromgregorian(
                day=kill.date.day,
                month=kill.date.month,
                year=kill.date.year
            )
            list1 = [
                m,
                kill.kill_house.name,
                kill.poultry_name,
                buy_type,
                f'{kill.province} / {kill.city}',
                str(date_of_buy),
                kill.bar_clearance_code,
                kill.quantity,
                kill.live_weight,
                str(date_of_enter),
                kill.number_of_carcasses,
                int(kill.weight_of_carcasses),

                kill.weight_loss,

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

                if isinstance(value, (int)):
                    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')

    quantity = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    live_weight = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    number_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    weight_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0
    # if type == 'live':
    quantity = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    live_weight = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    number_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    weight_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

    entered_quantity = entered_bars.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    entered_live_weight = entered_bars.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    entered_number_of_carcasses = entered_bars.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    entered_weight_of_carcasses = entered_bars.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

    not_entered_quantity = not_entered_bars.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    not_entered_live_weight = not_entered_bars.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    not_entered_number_of_carcasses = not_entered_bars.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    not_entered_weight_of_carcasses = not_entered_bars.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    value_header_list2 = [
        len(kill_house_free_bar_info),
        quantity,
        live_weight,

        len(entered_bars),

        entered_quantity,
        entered_live_weight,
        weight_of_carcasses,
        len(not_entered_bars),
        not_entered_quantity,
        not_entered_live_weight,

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 4, 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 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        quantity,
        live_weight,
        '',
        number_of_carcasses,
        weight_of_carcasses,
        '',

    ]
    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 = '#,###'  # 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 kill_house_free_bar_info.exists():
        if request.GET['role'] == 'KillHouse':
            name = kill_house_free_bar_info.first().kill_house.name
            response[
                'Content-Disposition'] = f'attachment; filename=" مدیریت بار  {type} کشتارگاه {name} خرید از استان.xlsx"'.encode(
                'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="مدیریت بار {type} خرید از استان.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def kill_house_free_bar_carcasses_for_warehouse_excel(request):
    filterset_class = KillHouseFreeBarInformationFilterSet
    filterset_fields = [
        'kill_house__name',
        'poultry_name',
        'poultry_mobile',
        'province',
        'city',
        'driver_name',
        'driver_mobile',
        'clearance_code',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__kill_house_operator__user__fullname',

    ]

    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    type = request.GET.get('type')
    date_type = request.GET.get('date_type')
    bar_state = request.GET.get('bar_state')
    kill_house_free_bar_info_list = []
    role = request.GET.get('role')
    kill_houses = None
    order_by_type = '-create_date'

    if role in ['KillHouse', 'KillHouseVet']:
        if role == 'KillHouse':
            kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
        else:
            kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                  flat=True)
            kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

        if date_type:
            if date_type == 'buy':

                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
            else:
                order_by_type = '-date'
                filters = {
                    'date__date__gte': date1,
                    'date__date__lte': date2,
                    'trash': False,
                }
        else:
            filters = {
                'create_date__date__gte': date1,
                'create_date__date__lte': date2,
                'trash': False,
            }
    else:
        filters = {
            'trash': False
        }

    if kill_houses is not None:
        filters['kill_house__in'] = kill_houses

    if type:
        filters['buy_type'] = type
        if type == 'live':
            if bar_state:
                if bar_state == 'entered':
                    filters['weight_of_carcasses__gt'] = 0
                else:
                    filters['weight_of_carcasses'] = 0

    kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type)

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

    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)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    header_list2 = [
        'تعداد کل بار',
        'حجم لاشه',
        'وزن لاشه',

    ]

    for col_num, option in enumerate(header_list2, 4):
        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
    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
    type = 'زنده' if request.GET['type'] == 'live' else 'لاشه'
    worksheet['B1'] = f'گزارش بار {type} خرید خارج از استان'

    if kill_house_free_bar_info.exists():
        name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name
        worksheet['A2'] = f'استان {name}'

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

    l = 5
    m = 1

    if kill_house_free_bar_info:
        for kill in kill_house_free_bar_info:
            l += 1

            if kill.kill_house_vet_state == 'accepted':
                state = 'تایید شده'
            elif kill.kill_house_vet_state == 'pending':
                state = 'درانتظار تایید'
            else:
                state = 'رد شده'

            if kill.buy_type == 'live':
                buy_type = 'زنده'
            else:
                buy_type = 'لاشه'

            date_of_buy = jdatetime.date.fromgregorian(
                day=kill.create_date.day,
                month=kill.create_date.month,
                year=kill.create_date.year
            )

            if kill.date_of_accept_reject:
                date_of_reject_accepted = jdatetime.date.fromgregorian(
                    day=kill.date_of_accept_reject.day,
                    month=kill.date_of_accept_reject.month,
                    year=kill.date_of_accept_reject.year
                )
            else:
                date_of_reject_accepted = '-'
            date_of_enter = jdatetime.date.fromgregorian(
                day=kill.date.day,
                month=kill.date.month,
                year=kill.date.year
            )
            list1 = [
                m,
                kill.kill_house.name,
                kill.poultry_name,
                buy_type,
                f'{kill.province} / {kill.city}',
                str(date_of_buy),
                kill.bar_clearance_code,
                str(date_of_enter),
                kill.number_of_carcasses,
                int(kill.weight_of_carcasses),

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

                if isinstance(value, (int)):
                    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')

    quantity = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    live_weight = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    number_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    weight_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0
    # if type == 'live':
    quantity = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    live_weight = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    number_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    weight_of_carcasses = kill_house_free_bar_info.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

    entered_quantity = entered_bars.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    entered_live_weight = entered_bars.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    entered_number_of_carcasses = entered_bars.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    entered_weight_of_carcasses = entered_bars.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

    not_entered_quantity = not_entered_bars.aggregate(
        total_quantity=Sum('quantity')).get(
        'total_quantity') or 0
    not_entered_live_weight = not_entered_bars.aggregate(
        total_quantity=Sum('live_weight')).get(
        'total_quantity') or 0
    not_entered_number_of_carcasses = not_entered_bars.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    not_entered_weight_of_carcasses = not_entered_bars.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0

    value_header_list2 = [
        len(kill_house_free_bar_info),
        number_of_carcasses,
        weight_of_carcasses,

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 4, 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 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        number_of_carcasses,
        weight_of_carcasses,

    ]
    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 = '#,###'  # 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 kill_house_free_bar_info.exists():
        if request.GET['role'] == 'KillHouse':
            name = kill_house_free_bar_info.first().kill_house.name
            response[
                'Content-Disposition'] = f'attachment; filename=" مدیریت بار  {type} کشتارگاه {name} خرید از استان.xlsx"'.encode(
                'utf-8')
    else:
        response[
            'Content-Disposition'] = f'attachment; filename="مدیریت بار {type} خرید از استان.xlsx"'.encode(
            'utf-8')
    response.write(output.getvalue())
    return response


def steward_allocation_for_warehouse_excel(request):
    filterset_class = StewardAllocationFilterSet
    filterset_fields = [
        'guilds__user__first_name',
        'guilds__user__last_name',
        'guilds__user__fullname',
        'guilds__user__mobile',
        'steward__user__first_name',
        'steward__user__last_name',
        'steward__user__fullname',
        'steward__user__mobile',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__name',
        'to_guilds__user__first_name',
        'to_guilds__user__last_name',
        'to_guilds__user__fullname',
        'to_guilds__user__mobile',
        'to_steward__user__first_name',
        'to_steward__user__last_name',
        'to_steward__user__fullname',
        'to_steward__user__mobile',
        'to_kill_house__kill_house_operator__user__first_name',
        'to_kill_house__kill_house_operator__user__last_name',
        'to_kill_house__kill_house_operator__user__fullname',
        'to_kill_house__kill_house_operator__user__mobile',
        'to_kill_house__name',
    ]

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

    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()

    if 'date1' in request.GET and request.GET['date1']:

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

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

        allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                                                       trash=False, date__date__gte=date1,
                                                       date__date__lte=date2).order_by('id')
    else:
        allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                                                       trash=False).order_by('id')

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

    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)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    header_list2 = [
        'تعداد تخصیصات',
        'قیمت کل',
        'حجم تخصیصی',
        'وزن تخصیصی',
        'حجم تایید شده',
        'وزن تایید شده',

    ]

    for col_num, option in enumerate(header_list2, 5):
        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
    create_header_freez(worksheet, excel_options, 1, 6, 7, 20)

    kill_house_name = ''
    if allocations.exists():
        kill_house_name = allocations.first().kill_house.name
    excel_description(worksheet, 'A1', f'تخصیصات داخل استان کشتارگاه {kill_house_name}', size=11, color='red',
                      row2='D1')

    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

    if allocations:
        for allocation in allocations:
            l += 1

            if allocation.allocation_type == 'killhouse_steward':
                allocation_type = 'کشتارگاه به مباشر'
                buyer_name = allocation.to_steward.guilds_name
                buyer_mobile = allocation.to_steward.user.mobile
            elif allocation.allocation_type == 'killhouse_guild':
                allocation_type = 'کشتارگاه به صنف'
                buyer_name = allocation.to_guilds.guilds_name
                buyer_mobile = allocation.to_guilds.user.mobile
            else:
                allocation_type = ''
                buyer_name = ''
                buyer_mobile = ''

            if allocation.sell_type == 'exclusive':
                sell_type = 'اختصاصی'
            else:
                sell_type = ''
            system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده'
            state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده'
            list1 = [
                m,
                str(shamsi_date((allocation.date))),
                allocation_type,
                buyer_name,
                buyer_mobile,
                sell_type,
                allocation.amount,
                allocation.total_amount,
                allocation.number_of_carcasses,
                allocation.weight_of_carcasses,
                allocation.receiver_real_number_of_carcasses,
                allocation.receiver_real_weight_of_carcasses,
                allocation.registration_code,
                system_registration_code,
                state,

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

                if isinstance(value, (int)):
                    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')

    total_amount_allocations = allocations.aggregate(
        total_quantity=Sum('total_amount')).get(
        'total_quantity') or 0
    number_of_carcasses_allocations = allocations.aggregate(
        total_quantity=Sum('number_of_carcasses')).get(
        'total_quantity') or 0
    weight_of_carcasses_allocations = allocations.aggregate(
        total_quantity=Sum('weight_of_carcasses')).get(
        'total_quantity') or 0
    receiver_real_number_of_carcasses_allocations = allocations.aggregate(
        total_quantity=Sum('receiver_real_number_of_carcasses')).get(
        'total_quantity') or 0
    receiver_real_weight_of_carcasses_allocations = allocations.aggregate(
        total_quantity=Sum('receiver_real_weight_of_carcasses')).get(
        'total_quantity') or 0

    value_header_list2 = [
        len(allocations),
        total_amount_allocations,
        number_of_carcasses_allocations,
        weight_of_carcasses_allocations,
        receiver_real_number_of_carcasses_allocations,
        receiver_real_weight_of_carcasses_allocations,

    ]
    for item in range(len(value_header_list2)):
        cell = worksheet.cell(row=3, column=item + 5, 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 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        total_amount_allocations,
        number_of_carcasses_allocations,
        weight_of_carcasses_allocations,
        receiver_real_number_of_carcasses_allocations,
        receiver_real_weight_of_carcasses_allocations,
        '',
        '',
        '',

    ]
    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 = '#,###'  # 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="تخصیصات صورت گرفته داخل استان کشتارگاه {kill_house_name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


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

    kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
    sheet_names2 = [
        'اطلاعات کلی',
        'بارهای در انتظار ورود به انبار',
        'بارهای وارد شده به انبار',
        'فروش  به داخل استان',
        'فروش  به خارج استان',
        'خریداران(خارج استان)',
        'بار زنده (خرید خارج استان)',
        'بار لاشه (خرید خارج استان)',

    ]

    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    for name in sheet_names2:
        sheet_name = name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        if sheet_name == 'اطلاعات کلی':
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                from1 = shamsi_date(date1)
                from2 = shamsi_date(date2)
                excel_description(worksheet, 'A7',
                                  f'گزارش جامع انبار کشتارگاه {kill_house.name} از تاریخ {from1} تا تاریخ {from2}',
                                  size=11, color='red', row2='C9')
            else:
                excel_description(worksheet, 'A7', f'گزارش جامع انبار کشتارگاه {kill_house.name}',
                                  size=11, color='red', row2='C8')
            excel_description(worksheet, 'D2', f'مدیریت انبار',
                              size=11, color='red', row2='G2')
            header_list2 = [
                'ردیف',
                'نام محصول',
                'وزن خریدهای دولتی داخل استان(کیلوگرم)',
                'وزن خریدهای آزاد داخل استان(کیلوگرم)',
                'وزن خریدهای خارج استان(کیلوگرم)',
                'کل ورودی به انبار(کیلوگرم)',
                'کل فروش(کیلوگرم)',
                'مانده انبار(کیلوگرم)',

            ]
            create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='FF0000', border_style='thin')
            products = RolesProducts.objects.filter(kill_house=kill_house, trash=False)
            q = 4
            w = 1
            for product in products:
                value_header_list = [
                    w,
                    product.name,
                    product.province_governmental_carcasses_weight,
                    product.province_free_carcasses_weight,
                    product.free_buying_carcasses_weight,
                    product.total_carcasses_weight,
                    product.real_allocated_weight,
                    product.total_remain_weight,

                ]
                create_value(worksheet, value_header_list, q, 3, border_style='thin')
                q += 1
                w += 1

            excel_description(worksheet, 'D6', f'اطلاعات پخش',
                              size=11, color='red', row2='G6')
            header_list2 = [
                'فروش و توزیع داخل استان(کیلوگرم)',
                'فروش و توزیع خارج استان(کیلوگرم)',

            ]
            create_header(worksheet, header_list2, 5, 7, height=21.8, width=20, color='C00000', border_style='thin')
            user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            steward_allocations = StewardAllocation.objects.filter(kill_house=kill_house,
                                                                   receiver_state__in=('pending', 'accepted'),
                                                                   calculate_status=True, trash=False)
            steward_allocations_weight = \
                steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0

            free_sales = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
                                                                        calculate_status=True)
            free_sales_weight = free_sales.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0
            value_header_list = [
                steward_allocations_weight,
                free_sales_weight,

            ]
            create_value(worksheet, value_header_list, 8, 5, border_style='thin')

            excel_description(worksheet, 'D11', f'بارهای در انتظار ورود به انبار',
                              size=11, color='red', row2='G11')
            header_list = [
                'تعداد بار',
                'حجم بار',
                'وزن بار',
                'میانگین وزن ',

                'تعداد بارهای تکمیل شده',

            ]

            # برای بالای هدر
            # header_list2 = [
            #     'تعداد درخواست مرغداران',
            #     ' مجموع تعداد قطعه درخواست مرغداران',
            #     ' مجموع وزن درخواست مرغداران',
            #
            # ]
            # create_header(worksheet, header_list2, 1, 12, height=21.8, color='green',border_style='thin')

            create_header(worksheet, header_list, 3, 12, height=21.8, border_style='thin')
            if 'date1' in request.GET and request.GET['date1']:

                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(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )
            else:
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )

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

            )

            bar_complete = filtered_kill_reqs.filter(assignment_state_archive='True')

            all_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0

            hasnt_code1 = filtered_kill_reqs.filter(clearance_code__isnull=True)

            all_age = []

            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            kill_keys = [kill.get('key') for kill in filtered_kill_reqs]
            assignments = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key__in=kill_keys, trash=False
            ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key')
            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:
                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)

                    key = kill.get('key')
                    net_weighte, real_quantity, 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

                    weight = int(kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight'))

                    if kill['message'] is not None:
                        state_delete = 'بار حذف شده'
                    else:
                        all_weighte += weight

            value_header_list = [

                len(filtered_kill_reqs),

                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,

                len(bar_complete),

            ]
            create_value(worksheet, value_header_list, 13, 3, border_style='thin')

            excel_description(worksheet, 'D15', f'بارهای وارد شده به انبار',
                              size=11, color='red', row2='G15')
            header_list = [
                'تعداد بارهای ایجاد شده',

                'مجموع حجم بارها',
                'مجموع وزن بارها',
                'میانگین وزن ',

                ' افت در لحظه',
                ' افت لاشه ورود به انبار',

            ]

            # برای بالای هدر
            # header_list2 = [
            #     'تعداد درخواست مرغداران',
            #     ' مجموع تعداد قطعه درخواست مرغداران',
            #     ' مجموع وزن درخواست مرغداران',
            #
            # ]
            # create_header(worksheet, header_list2, 1, 16, height=21.8, color='green', border_style='thin')

            create_header(worksheet, header_list, 3, 16, height=21.8, border_style='thin')
            if 'date1' in request.GET and request.GET['date1']:

                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(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )
            else:
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )

            all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True))

            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_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0

            all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0

            all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation,
                                    2) if all_state_ware_house_confirmation > 0 else 0
            all_age = []

            all_real_quantity = 0
            all_net_weighte = 0
            all_weighte = 0
            kill_keys = [kill.get('key') for kill in filtered_kill_reqs]
            assignments = KillHouseAssignmentInformation.objects.filter(
                kill_house_request__key__in=kill_keys, trash=False
            ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key')
            assignment_mapping = {
                assignment.kill_house_request.key: (
                    int(assignment.net_weight), assignment.real_quantity, assignment.create_date)
                for assignment in assignments
            }
            all_total_weight_loss = 0
            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)

                    key = kill.get('key')
                    net_weighte, real_quantity, 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

                    weight = int(kill.get('quantity') * kill.get(
                        'province_kill_request__province_request__poultry_request__Index_weight'))

                    if kill['message'] is not None:
                        state_delete = 'بار حذف شده'
                    else:
                        all_weighte += 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 kill[
                                                                                                   'accepted_real_weight'] != 0 else 0
                    all_total_weight_loss += total_weight_loss
            all_total_weight_loss = all_total_weight_loss / len(filtered_kill_reqs) if len(
                filtered_kill_reqs) > 0 else 0
            value_header_list = [
                len(filtered_kill_reqs),

                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,

                f'%{int(all_total_weight_loss)}',
                f'%{all_weight_loss}',

            ]
            create_value(worksheet, value_header_list, 17, 3, border_style='thin')

            excel_description(worksheet, 'D19', f'فروش به داخل استان',
                              size=11, color='red', row2='G19')
            if 'date1' in request.GET and request.GET['date1']:

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

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

                allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                                                               trash=False, date__date__gte=date1,
                                                               date__date__lte=date2).order_by('id')
            else:
                allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                                                               trash=False).order_by('id')

            header_list2 = [
                'تعداد تخصیصات',
                'قیمت کل',
                'حجم تخصیصی',
                'وزن تخصیصی',
                'حجم تایید شده',
                'وزن تایید شده',

            ]
            create_header(worksheet, header_list2, 4, 20, height=21, width=16.01, border_style='thin')
            total_amount_allocations = allocations.aggregate(
                total_quantity=Sum('total_amount')).get(
                'total_quantity') or 0
            number_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            receiver_real_number_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('receiver_real_number_of_carcasses')).get(
                'total_quantity') or 0
            receiver_real_weight_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('receiver_real_weight_of_carcasses')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(allocations),
                total_amount_allocations,
                number_of_carcasses_allocations,
                weight_of_carcasses_allocations,
                receiver_real_number_of_carcasses_allocations,
                receiver_real_weight_of_carcasses_allocations,

            ]
            create_value(worksheet, value_header_list2, 21, 4, border_style='thin')

            excel_description(worksheet, 'D23', f'فروش  به خارج استان',
                              size=11, color='red', row2='G23')
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                                   '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                                   '%Y-%m-%d').date()
                buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
                                                                        date__date__gte=date1,
                                                                        date__date__lte=date2).order_by('-date')
            else:
                buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
                                                                        ).order_by('-date')

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

            ]

            create_header(worksheet, header_list, 4, 24, height=21, width=16.01, border_style='thin')

            total_quantity = buyers.aggregate(total=Sum('number_of_carcasses'))[
                                 'total'] or 0
            total_weight = buyers.aggregate(total=Sum('weight_of_carcasses'))[
                               'total'] or 0
            len_buyers = []
            for buyer in buyers:

                if buyer.buyer_name not in len_buyers:
                    len_buyers.append(buyer.buyer_name)
            value_list = [
                len(buyers),
                len(len_buyers),
                total_quantity,
                total_weight,
            ]
            create_value(worksheet, value_list, 25, 4, border_style='thin')

            excel_description(worksheet, 'D27', f'بار زنده (خرید خارج استان)',
                              size=11, color='red', row2='G27')

            type = 'live'
            kill_houses = None

            role = request.GET.get('role')
            order_by_type = '-create_date'
            if role in ['KillHouse', 'KillHouseVet']:
                if role == 'KillHouse':
                    kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                else:
                    kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                          flat=True)
                    kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
            else:
                filters = {
                    'trash': False
                }
            if kill_houses is not None:
                filters['kill_house__in'] = kill_houses
            filters['buy_type'] = type
            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters, calculate_status=True,
                                                                                  temporary_trash=False,
                                                                                  temporary_deleted=False).order_by(
                order_by_type)
            header_list2 = [
                'تعداد کل بار زنده',
                'حجم کل بار زنده',
                'وزن کل بار زنده',
                'تعداد کل بارهای وارد شده به انبار',
                'حجم کل بارهای  زنده وارد شده به انبار',
                'وزن کل بارهای زنده وارد شده به انبار',
                'وزن لاشه وارد شده به انبار',
                'کل بار وارد نشده به انبار',
                'حجم کل بار وارد نشده به انبار',
                'وزن کل بار وارد نشده به انبار',

            ]
            create_header(worksheet, header_list2, 2, 28, height=21, width=16.01, border_style='thin')

            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0

            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

            entered_quantity = entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            entered_live_weight = entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0

            not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

            not_entered_quantity = not_entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            not_entered_live_weight = not_entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(kill_house_free_bar_info),
                quantity,
                live_weight,

                len(entered_bars),

                entered_quantity,
                entered_live_weight,
                weight_of_carcasses,
                len(not_entered_bars),
                not_entered_quantity,
                not_entered_live_weight,

            ]
            create_value(worksheet, value_header_list2, 29, 2, border_style='thin')

            excel_description(worksheet, 'D31', f'بار لاشه (خرید خارج استان)',
                              size=11, color='red', row2='G31')
            type = 'carcasses'
            bar_state = 'entered'
            kill_house_free_bar_info_list = []
            role = request.GET.get('role')
            kill_houses = None
            order_by_type = '-create_date'

            if role in ['KillHouse', 'KillHouseVet']:
                if role == 'KillHouse':
                    kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                else:
                    kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                          flat=True)
                    kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
            else:
                filters = {
                    'trash': False
                }

            if kill_houses is not None:
                filters['kill_house__in'] = kill_houses

            if type:
                filters['buy_type'] = type
                if type == 'live':
                    if bar_state:
                        if bar_state == 'entered':
                            filters['weight_of_carcasses__gt'] = 0
                        else:
                            filters['weight_of_carcasses'] = 0

            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters, calculate_status=True,
                                                                                  temporary_trash=False,
                                                                                  temporary_deleted=False).order_by(
                order_by_type)
            header_list2 = [
                'تعداد کل بار',
                'حجم لاشه',
                'وزن لاشه',

            ]
            create_header(worksheet, header_list2, 5, 32, height=21, width=16.01, border_style='thin')

            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

            value_header_list2 = [
                len(kill_house_free_bar_info),
                number_of_carcasses,
                weight_of_carcasses,

            ]
            create_value(worksheet, value_header_list2, 33, 5, border_style='thin')
        elif 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',
            ]
            user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
                'system_address__province').first()

            if 'date1' in request.GET and request.GET['date1']:

                date1 = datetime.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(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )
            else:
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )

            if 'search' in request.GET:
                filtered_kill_reqs = []
                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()
                        filtered_kill_reqs = [] if len(filtered_kill_reqs) == 0 else filtered_kill_reqs

            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 = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'نوع کشتار',
                'کدسفارش مرغدار',
                'نام و نام خانوادگی مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'نام فارم',
                'فروش',

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

            ]

            cell = worksheet.cell(row=1, column=1)
            cell.alignment = Alignment(horizontal='center', vertical='center')

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

            ]

            # برای بالای هدر
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            create_header(worksheet, header_list2, 6, 4, height=21.8, color='green')

            create_header(worksheet, header_list, 9, 4, height=21.8)

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

            ]
            create_header(worksheet, header_list2, 6, 1, height=21.8, color='FF0000')
            products = RolesProducts.objects.filter(kill_house=kill_house, trash=False)
            q = 2
            w = 1
            for product in products:
                value_header_list = [
                    w,
                    product.name,
                    product.province_governmental_carcasses_weight,
                    product.province_free_carcasses_weight,
                    product.free_buying_carcasses_weight,
                    product.total_carcasses_weight,
                    product.real_allocated_weight,
                    product.total_remain_weight,

                ]
                create_value(worksheet, value_header_list, q, 6)
                q += 1
                w += 1

            kill_house_name = ''
            if filtered_kill_reqs.exists():
                kill_house_name = filtered_kill_reqs.first()['killhouse_user__name']
            excel_description(worksheet, 'A1', f'بارهای {kill_house_name} در انتظار ورود به انبار (کشتار داخل استان)',
                              size=11, color='red', row2='E1')
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                from_date_1 = shamsi_date(date1)
                to_date_1 = shamsi_date(date2)
                excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})', row2='C3')

            m = 1

            create_header_freez(worksheet, excel_options, 1, 7, 8, 20)
            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
            }
            l = 7
            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 '-'
                    net_weighte, real_quantity, 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_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'],
                        int(kill['accepted_real_weight']),
                        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,

                    ]
                    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))
            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 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, 5, 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 == 'بارهای وارد شده به انبار':
            filterset_class = KillHouseRequestFilterSet
            filterset_fields = [
                'killhouse_user__kill_house_operator__user__fullname',
                'killhouse_user__kill_house_operator__user__mobile',
                'province_request__poultry_request__poultry__user__fullname',
                'province_request__poultry_request__poultry__user__mobile',
                'province_request__poultry_request__order_code',
                'province_request__poultry_request__order_code',
                'bar_code',
            ]
            user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).select_related(
                'system_address__province').first()

            if 'date1' in request.GET and request.GET['date1']:

                date1 = datetime.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(killhouse_user=kill_house) | Q(killer=kill_house),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )
            else:
                filtered_kill_reqs = KillHouseRequest.objects.filter(
                    Q(killhouse_user=kill_house) | Q(killer=kill_house),
                    ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
                    '-kill_request__recive_date').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',
                                                          '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',
                    'bar_document_status__title'
                )

            if 'search' in request.GET:
                filtered_kill_reqs = []
                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()
                        filtered_kill_reqs = [] if len(filtered_kill_reqs) == 0 else filtered_kill_reqs

            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 = [
                'ردیف',
                'کد بار',
                ' تاریخ کشتار',
                'نوع کشتار',
                'کدسفارش مرغدار',
                'نام و نام خانوادگی مرغدار',
                'تلفن مرغدار',
                ' شهر مرغدار',
                'نام فارم',
                'فروش',

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

            ]

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

            ]

            # برای بالای هدر
            header_list2 = [
                'تعداد درخواست مرغداران',
                ' مجموع تعداد قطعه درخواست مرغداران',
                ' مجموع وزن درخواست مرغداران',

            ]
            create_header(worksheet, header_list2, 6, 4, height=21.8, color='green')

            create_header(worksheet, header_list, 9, 4, height=21.8)

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

            ]
            create_header(worksheet, header_list2, 6, 1, height=21.8, color='FF0000')
            products = RolesProducts.objects.filter(kill_house=kill_house, trash=False)
            q = 2
            w = 1
            for product in products:
                value_header_list = [
                    w,
                    product.name,
                    product.province_governmental_carcasses_weight,
                    product.province_free_carcasses_weight,
                    product.free_buying_carcasses_weight,
                    product.total_carcasses_weight,
                    product.real_allocated_weight,
                    product.total_remain_weight,

                ]
                create_value(worksheet, value_header_list, q, 6)
                q += 1
                w += 1

            kill_house_name = ''
            if filtered_kill_reqs.exists():
                kill_house_name = filtered_kill_reqs.first()['killhouse_user__name']
            excel_description(worksheet, 'A1', f'بارهای {kill_house_name} وارد شده به انبار (کشتار داخل استان)',
                              size=11, color='red', row2='E1')
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                from_date_1 = shamsi_date(date1)
                to_date_1 = shamsi_date(date2)
                excel_description(worksheet, 'A3', f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})', row2='C3')

            m = 1

            create_header_freez(worksheet, excel_options, 1, 7, 8, 20)
            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
            }
            l = 7
            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 '-'
                    net_weighte, real_quantity, 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 kill[
                                                                                                   'accepted_real_weight'] != 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_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'],
                        int(kill['accepted_real_weight']),
                        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,

                    ]
                    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_state_ware_house_confirmation > 0 else 0

            all_age1 = sorted(all_age)
            has_code = len(filtered_kill_reqs.filter(clearance_code__isnull=False))
            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 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, 5, 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 == 'فروش  به داخل استان':
            filterset_class = StewardAllocationFilterSet
            filterset_fields = [
                'guilds__user__first_name',
                'guilds__user__last_name',
                'guilds__user__fullname',
                'guilds__user__mobile',
                'steward__user__first_name',
                'steward__user__last_name',
                'steward__user__fullname',
                'steward__user__mobile',
                'kill_house__kill_house_operator__user__first_name',
                'kill_house__kill_house_operator__user__last_name',
                'kill_house__kill_house_operator__user__fullname',
                'kill_house__kill_house_operator__user__mobile',
                'kill_house__name',
                'to_guilds__user__first_name',
                'to_guilds__user__last_name',
                'to_guilds__user__fullname',
                'to_guilds__user__mobile',
                'to_steward__user__first_name',
                'to_steward__user__last_name',
                'to_steward__user__fullname',
                'to_steward__user__mobile',
                'to_kill_house__kill_house_operator__user__first_name',
                'to_kill_house__kill_house_operator__user__last_name',
                'to_kill_house__kill_house_operator__user__fullname',
                'to_kill_house__kill_house_operator__user__mobile',
                'to_kill_house__name',
            ]

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

            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()

            if 'date1' in request.GET and request.GET['date1']:

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

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

                allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                                                               trash=False, date__date__gte=date1,
                                                               date__date__lte=date2).order_by('id')
            else:
                allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                                                               trash=False).order_by('id')

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

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

            ]

            red_font = Font(color="C00000", bold=True)
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                from_date_1 = shamsi_date(date1)
                to_date_1 = shamsi_date(date2)
                worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
            header_list2 = [
                'تعداد تخصیصات',
                'قیمت کل',
                'حجم تخصیصی',
                'وزن تخصیصی',
                'حجم تایید شده',
                'وزن تایید شده',

            ]

            for col_num, option in enumerate(header_list2, 5):
                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
            create_header_freez(worksheet, excel_options, 1, 6, 7, 20)

            kill_house_name = ''
            if allocations.exists():
                kill_house_name = allocations.first().kill_house.name
            excel_description(worksheet, 'A1', f'تخصیصات داخل استان کشتارگاه {kill_house_name}', size=11, color='red',
                              row2='D1')

            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

            if allocations:
                for allocation in allocations:
                    l += 1

                    if allocation.allocation_type == 'killhouse_steward':
                        allocation_type = 'کشتارگاه به مباشر'
                        buyer_name = allocation.to_steward.guilds_name if allocation.to_steward else '-'
                        buyer_mobile = allocation.to_steward.user.mobile if allocation.to_steward else '-'
                    elif allocation.allocation_type == 'killhouse_guild':
                        allocation_type = 'کشتارگاه به صنف'
                        buyer_name = allocation.to_guilds.guilds_name if allocation.to_guilds else '-'
                        buyer_mobile = allocation.to_guilds.user.mobile if allocation.to_guilds else '-'
                    else:
                        allocation_type = ''
                        buyer_name = ''
                        buyer_mobile = ''

                    if allocation.sell_type == 'exclusive':
                        sell_type = 'اختصاصی'
                    else:
                        sell_type = ''
                    system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده'
                    state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده'
                    list1 = [
                        m,
                        str(shamsi_date(allocation.date, in_value=True)),
                        allocation_type,
                        buyer_name,
                        buyer_mobile,
                        allocation.interface_number or '-',
                        sell_type,
                        allocation.amount,
                        allocation.total_amount,
                        allocation.number_of_carcasses,
                        allocation.weight_of_carcasses,
                        allocation.receiver_real_number_of_carcasses,
                        allocation.receiver_real_weight_of_carcasses,
                        str(allocation.logged_registration_code or '-'),
                        system_registration_code,
                        "دولتی" if allocation.quota == 'governmental' else 'آزاد',
                        "دولتی" if allocation.approved_price_status == True else 'آزاد',
                        state,

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

                        if isinstance(value, (int)):
                            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')

            total_amount_allocations = allocations.aggregate(
                total_quantity=Sum('total_amount')).get(
                'total_quantity') or 0
            number_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            receiver_real_number_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('receiver_real_number_of_carcasses')).get(
                'total_quantity') or 0
            receiver_real_weight_of_carcasses_allocations = allocations.aggregate(
                total_quantity=Sum('receiver_real_weight_of_carcasses')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(allocations),
                total_amount_allocations,
                number_of_carcasses_allocations,
                weight_of_carcasses_allocations,
                receiver_real_number_of_carcasses_allocations,
                receiver_real_weight_of_carcasses_allocations,

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 5, 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 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                total_amount_allocations,
                number_of_carcasses_allocations,
                weight_of_carcasses_allocations,
                receiver_real_number_of_carcasses_allocations,
                receiver_real_weight_of_carcasses_allocations,
                '',
                '',
                '',
                '',
                '',

            ]
            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 = '#,###'  # 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 == 'فروش  به خارج استان':

            filterset_class = OutProvinceCarcassesBuyerFilterSet
            filterset_fields = [
                'mobile',
                'first_name',
                'last_name',
                'fullname',
                'unit_name',

            ]
            user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                                   '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                                   '%Y-%m-%d').date()
                buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
                                                                        date__date__gte=date1,
                                                                        date__date__lte=date2).order_by('-date')
            else:
                buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
                                                                        ).order_by('-date')
            len_buyers = []

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

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

            ]

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

            ]

            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)

            excel_description(worksheet, 'A1', f'فروش لاشه خارج استان کشتارگاه {kill_house.name}', color='red',
                              row2='B1')

            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']),
                                                   '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']),
                                                   '%Y-%m-%d').date()
                from_date1 = shamsi_date(date1)
                from_date2 = shamsi_date(date2)
                excel_description(worksheet, 'A3', f'از تاریخ {from_date1} تا {from_date2}', color='red', row2='B3')

            if kill_house:
                province = kill_house.kill_house_operator.user.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 = 5
            m = 1

            for buyer in buyers:
                date = jdatetime.date.fromgregorian(
                    day=buyer.date.day,
                    month=buyer.date.month,
                    year=buyer.date.year
                )
                if buyer.buyer_name not in len_buyers:
                    len_buyers.append(buyer.buyer_name)
                list1 = [
                    m,
                    buyer.kill_house.name,
                    buyer.kill_house.kill_house_operator.user.mobile,
                    str(date),
                    buyer.buyer_name,
                    buyer.buyer_mobile,
                    buyer.buyer_name,
                    buyer.province,
                    buyer.city,
                    buyer.number_of_carcasses,
                    buyer.weight_of_carcasses,

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

                m += 1
                l += 1

            total_quantity = buyers.aggregate(total=Sum('number_of_carcasses'))[
                                 'total'] or 0
            total_weight = buyers.aggregate(total=Sum('weight_of_carcasses'))[
                               'total'] or 0

            value_list = [
                len(buyers),
                len(len_buyers),
                total_quantity,
                total_weight,
            ]
            create_value(worksheet, value_list, 3, 3)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                total_quantity,
                total_weight,

            ]
            create_value(worksheet, list2, l + 3, 1, color='green')
        elif sheet_name == 'خریداران(خارج استان)':
            out_buyers = OutProvinceCarcassesBuyer.objects.filter(Kill_house=kill_house, trash=False).order_by(
                'id')
            excel_options = [
                'ردیف',
                'نام خریدار',
                'موبایل خریدار',
                'نام واحد',
                'استان',
                'شهر',
                'تعداد درخواست ها',
                'حجم تقریبی(قطعه)',
                'وزن(کلوگرم)',

            ]

            excel_description(worksheet, 'A1', f'خریداران کشتارگاه {kill_house.name}', color='red',
                              row2='B1')

            if kill_house:
                province = kill_house.kill_house_operator.user.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 = 5
            m = 1

            for buyer in out_buyers:
                free_sales = KillHouseFreeSaleBarInformation.objects.filter(trash=False, buyer=buyer)

                total_quantity = free_sales.aggregate(total=Sum('number_of_carcasses'))[
                                     'total'] or 0
                total_weight = free_sales.aggregate(total=Sum('weight_of_carcasses'))[
                                   'total'] or 0

                list1 = [
                    m,
                    buyer.buyer.fullname,
                    buyer.buyer.mobile,
                    buyer.buyer.unit_name,
                    buyer.buyer.province,

                    buyer.buyer.city,
                    len(free_sales),
                    total_quantity,
                    total_weight,

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

                m += 1
                l += 1
        elif sheet_name == 'بار زنده (خرید خارج استان)':
            filterset_class = KillHouseFreeBarInformationFilterSet
            filterset_fields = [
                'kill_house__name',
                'poultry_name',
                'poultry_mobile',
                'province',
                'city',
                'driver_name',
                'driver_mobile',
                'clearance_code',
                'kill_house__kill_house_operator__user__mobile',
                'kill_house__kill_house_operator__user__fullname',

            ]

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

            role = request.GET.get('role')
            order_by_type = '-create_date'
            if role in ['KillHouse', 'KillHouseVet']:
                if role == 'KillHouse':
                    kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                else:
                    kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                          flat=True)
                    kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
            else:
                filters = {
                    'trash': False
                }
            if kill_houses is not None:
                filters['kill_house__in'] = kill_houses
            filters['buy_type'] = type
            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters, calculate_status=True,
                                                                                  temporary_trash=False,
                                                                                  temporary_deleted=False).order_by(
                order_by_type)

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

            ]

            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                from_date_1 = shamsi_date(date1)
                to_date_1 = shamsi_date(date2)
                worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
            header_list2 = [
                'تعداد کل بار زنده',
                'حجم کل بار زنده',
                'وزن کل بار زنده',
                'تعداد کل بارهای وارد شده به انبار',
                'حجم کل بارهای  زنده وارد شده به انبار',
                'وزن کل بارهای زنده وارد شده به انبار',
                'وزن لاشه وارد شده به انبار',
                'کل بار وارد نشده به انبار',
                'حجم کل بار وارد نشده به انبار',
                'وزن کل بار وارد نشده به انبار',

            ]

            for col_num, option in enumerate(header_list2, 4):
                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
            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['B1'] = f'گزارش بار زنده خرید خارج از استان'

            if kill_house_free_bar_info.exists():
                name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name
                worksheet['A2'] = f'استان {name}'

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

            l = 5
            m = 1

            if kill_house_free_bar_info:
                for kill in kill_house_free_bar_info:
                    l += 1

                    if kill.weight_of_carcasses > 0:
                        state = 'ورود به انبار'
                    else:
                        state = 'در انظار ورود به انبار'

                    if kill.buy_type == 'live':
                        buy_type = 'زنده'
                    else:
                        buy_type = 'لاشه'

                    date_of_buy = jdatetime.date.fromgregorian(
                        day=kill.create_date.day,
                        month=kill.create_date.month,
                        year=kill.create_date.year
                    )

                    if kill.date_of_accept_reject:
                        date_of_reject_accepted = jdatetime.date.fromgregorian(
                            day=kill.date_of_accept_reject.day,
                            month=kill.date_of_accept_reject.month,
                            year=kill.date_of_accept_reject.year
                        )
                    else:
                        date_of_reject_accepted = '-'
                    date_of_enter = jdatetime.date.fromgregorian(
                        day=kill.date.day,
                        month=kill.date.month,
                        year=kill.date.year
                    )
                    list1 = [
                        m,
                        state,
                        kill.kill_house.name,
                        kill.poultry_name,
                        buy_type,
                        f'{kill.province} / {kill.city}',
                        str(date_of_buy),
                        kill.bar_clearance_code,
                        kill.quantity,
                        kill.live_weight,
                        str(date_of_enter),
                        kill.number_of_carcasses,
                        int(kill.weight_of_carcasses),

                        kill.weight_loss,

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

                        if isinstance(value, (int)):
                            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')

            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            # if type == 'live':
            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

            entered_quantity = entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            entered_live_weight = entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            entered_number_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            entered_weight_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

            not_entered_quantity = not_entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            not_entered_live_weight = not_entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            not_entered_number_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            not_entered_weight_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(kill_house_free_bar_info),
                quantity,
                live_weight,

                len(entered_bars),

                entered_quantity,
                entered_live_weight,
                weight_of_carcasses,
                len(not_entered_bars),
                not_entered_quantity,
                not_entered_live_weight,

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 4, 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 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                quantity,
                live_weight,
                '',
                number_of_carcasses,
                weight_of_carcasses,
                '',

            ]
            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 = '#,###'  # 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 == 'بار لاشه (خرید خارج استان)':
            filterset_class = KillHouseFreeBarInformationFilterSet
            filterset_fields = [
                'kill_house__name',
                'poultry_name',
                'poultry_mobile',
                'province',
                'city',
                'driver_name',
                'driver_mobile',
                'clearance_code',
                'kill_house__kill_house_operator__user__mobile',
                'kill_house__kill_house_operator__user__fullname',

            ]

            user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
            type = 'carcasses'
            bar_state = 'entered'
            kill_house_free_bar_info_list = []
            role = request.GET.get('role')
            kill_houses = None
            order_by_type = '-create_date'

            if role in ['KillHouse', 'KillHouseVet']:
                if role == 'KillHouse':
                    kill_houses = KillHouse.objects.filter(kill_house_operator__user=user, trash=False)
                else:
                    kill_house_ids = KillHouseVet.objects.filter(vet__user=user, trash=False).values_list('kill_house',
                                                                                                          flat=True)
                    kill_houses = KillHouse.objects.filter(id__in=kill_house_ids, trash=False)
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                filters = {
                    'create_date__date__gte': date1,
                    'create_date__date__lte': date2,
                    'trash': False,
                }
            else:
                filters = {
                    'trash': False
                }

            if kill_houses is not None:
                filters['kill_house__in'] = kill_houses

            if type:
                filters['buy_type'] = type
                if type == 'live':
                    if bar_state:
                        if bar_state == 'entered':
                            filters['weight_of_carcasses__gt'] = 0
                        else:
                            filters['weight_of_carcasses'] = 0

            kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters, calculate_status=True,
                                                                                  temporary_trash=False,
                                                                                  temporary_deleted=False).order_by(
                order_by_type)

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

            excel_options = [
                'ردیف',
                'کشتارگاه',
                'فروشنده',
                'نوع خرید',
                'استان/شهر',
                'تاریخ خرید',
                'کدقرنطینه',

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

            ]

            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
                from_date_1 = shamsi_date(date1)
                to_date_1 = shamsi_date(date2)
                worksheet['B3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
            header_list2 = [
                'تعداد کل بار',
                'حجم لاشه',
                'وزن لاشه',

            ]

            for col_num, option in enumerate(header_list2, 4):
                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
            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['B1'] = f'گزارش بار لاشه خرید خارج از استان'

            if kill_house_free_bar_info.exists():
                name = kill_house_free_bar_info.first().kill_house.kill_house_operator.user.province.name
                worksheet['A2'] = f'استان {name}'

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

            l = 5
            m = 1

            if kill_house_free_bar_info:
                for kill in kill_house_free_bar_info:
                    l += 1

                    if kill.kill_house_vet_state == 'accepted':
                        state = 'تایید شده'
                    elif kill.kill_house_vet_state == 'pending':
                        state = 'درانتظار تایید'
                    else:
                        state = 'رد شده'

                    if kill.buy_type == 'live':
                        buy_type = 'زنده'
                    else:
                        buy_type = 'لاشه'

                    date_of_buy = jdatetime.date.fromgregorian(
                        day=kill.create_date.day,
                        month=kill.create_date.month,
                        year=kill.create_date.year
                    )

                    if kill.date_of_accept_reject:
                        date_of_reject_accepted = jdatetime.date.fromgregorian(
                            day=kill.date_of_accept_reject.day,
                            month=kill.date_of_accept_reject.month,
                            year=kill.date_of_accept_reject.year
                        )
                    else:
                        date_of_reject_accepted = '-'
                    date_of_enter = jdatetime.date.fromgregorian(
                        day=kill.date.day,
                        month=kill.date.month,
                        year=kill.date.year
                    )
                    list1 = [
                        m,
                        kill.kill_house.name,
                        kill.poultry_name,
                        buy_type,
                        f'{kill.province} / {kill.city}',
                        str(date_of_buy),
                        kill.bar_clearance_code,
                        str(date_of_enter),
                        kill.number_of_carcasses,
                        int(kill.weight_of_carcasses),

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

                        if isinstance(value, (int)):
                            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')

            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0
            # if type == 'live':
            quantity = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            live_weight = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            number_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            weight_of_carcasses = kill_house_free_bar_info.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)

            entered_quantity = entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            entered_live_weight = entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            entered_number_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            entered_weight_of_carcasses = entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)

            not_entered_quantity = not_entered_bars.aggregate(
                total_quantity=Sum('quantity')).get(
                'total_quantity') or 0
            not_entered_live_weight = not_entered_bars.aggregate(
                total_quantity=Sum('live_weight')).get(
                'total_quantity') or 0
            not_entered_number_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('number_of_carcasses')).get(
                'total_quantity') or 0
            not_entered_weight_of_carcasses = not_entered_bars.aggregate(
                total_quantity=Sum('weight_of_carcasses')).get(
                'total_quantity') or 0

            value_header_list2 = [
                len(kill_house_free_bar_info),
                number_of_carcasses,
                weight_of_carcasses,

            ]
            for item in range(len(value_header_list2)):
                cell = worksheet.cell(row=3, column=item + 4, 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 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                number_of_carcasses,
                weight_of_carcasses,

            ]
            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 = '#,###'  # 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="گزارش انبار کشتارگاه {kill_house.name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def all_kill_house_inventory_data(request):
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).order_by('id').annotate(
        allocation_count=Count(
            'kill_house_steward_allocation',
            filter=Q(kill_house_steward_allocation__receiver_state__in=['pending', 'accepted'])
        )
    ).order_by(
        '-allocation_count'
    )
    sheet_name = 'اطلاعات کلی'
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    worksheet = workbook.create_sheet(sheet_name)
    if sheet_name == 'اطلاعات کلی':
        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)

        #

        serializer = KillHouseForProvinceWareHouseDashboardSerializer(kill_houses, many=True,
                                                                      context={'request': request}).data
        header_list2 = [
            'ردیف',
            'خریدار',
            'تلفن خریدار',
            'ماهیت',
            'شهر',
            'مانده انبار فعلی',
            'کل وزن ورودی به انبار',
            'کل وزن فروش رفته',
            'حجم تخصیصات بدون ماشین',
            'تعداد بار درون استان',
            'حجم بار درون استان',
            'وزن بار درون استان',
            'تعداد بار زنده خارج استان',
            'حجم بار زنده خارج استان',
            'وزن بار زنده خارج استان',
            'تعداد بار لاشه خارج استان',
            'حجم بار لاشه خارج استان',
            'وزن بار لاشه خارج استان',
            'تعداد کل بارها',
            'حجم کل بارها',
            'وزن کل بارها',
            'تعداد بار وارد شده به انبار',
            'تعداد بار وارد نشده به انبار',
            'حجم بار وارد نشده به انبار',
            'وزن بار وارد نشده به انبار',
            'وزن فروش داخل استان',
            'وزن فروش خارج استان',

        ]
        create_header(worksheet, header_list2, 1, 12, height=21.8, width=20, border_style='thin')
        excel_description(worksheet, 'A2', f'اطلاعات جامع انبار',
                          size=11, color='red', row2='B4')
        if serializer:
            l = 13
            m = 1

            for data in serializer:
                list1 = [
                    m,
                    data.get('name', ''),
                    data.get('kill_house_operator', {}).get('user', {}).get('mobile', ''),
                    'کشتارگاه' if not data.get('killer', False) else 'کشتارکن',
                    data.get('kill_house_operator', {}).get('user', {}).get('city', {}).get('name', ''),
                    data.get('ware_house_info', {}).get('product_remain_weight', 0),
                    data.get('ware_house_info', {}).get('warehouse_total_entered_carcasses_weight', 0),
                    data.get('ware_house_info', {}).get('total_sell', 0),
                    data.get('ware_house_info', {}).get('province_kill_requests_quantity', 0),
                    data.get('ware_house_info', {}).get('total_province_bars', 0),
                    data.get('ware_house_info', {}).get('total_province_bars_quantity', 0),
                    data.get('ware_house_info', {}).get('total_province_bars_weight', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_bar', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_quantity', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_weight', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_carcasses_bar', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses_weight', 0),
                    data.get('ware_house_info', {}).get('total_bars', 0),
                    data.get('ware_house_info', {}).get('warehouse_total_quantity', 0),
                    data.get('ware_house_info', {}).get('warehouse_total_weight', 0),
                    int(data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0)),
                    data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars', 0),
                    data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0),
                    data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_allocations_weight', 0),
                    data.get('ware_house_info', {}).get('total_kill_house_free_sale__bar_carcasses_weight', 0),

                ]

                create_value(worksheet, list1, l, 1, border_style='thin', m=m)
                m += 1
                l += 1
            header_list2 = [
                'حجم کل بارها',
                'وزن کل بارها',
                'وزن وارد شده به انبار',
                'وزن توزیع شده داخل استان',
                'وزن توزیع شده خارج استان',
                'مانده انبار',

            ]
            create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='C00000', border_style='thin')
            products = RolesProducts.objects.filter(kill_house__in=kill_houses, trash=False)
            product_remain_weight = products.aggregate(total=Sum('total_remain_weight'))[
                                        'total'] or 0
            if date1:
                date1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date()
                shamsi_date1 = shamsi_date(date1)
                shamsi_date2 = shamsi_date(date2)
                excel_description(worksheet, 'A2',
                                  f' اطلاعات جامع انبار از تاریخ {shamsi_date1} تا تاریخ {shamsi_date2}',
                                  size=11, color='red', row2='B4')

            else:
                excel_description(worksheet, 'A2', f'اطلاعات جامع انبار',
                                  size=11, color='red', row2='B4')
            if 'date1' in request.GET:
                date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
                date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()

                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses),
                    kill_request__recive_date__date__gte=date1,
                    kill_request__recive_date__date__lte=date2,
                    temporary_trash=False,
                    temporary_deleted=False,
                    trash=False, calculate_status=True)

                kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter(Q(date__date__gte=date1,
                                                                                                date__date__lte=date2,
                                                                                                buy_type='carcass') | Q(
                    create_date__date__gte=date1, create_date__date__lte=date2, buy_type='live'),
                                                                                              kill_house__in=kill_houses,
                                                                                              trash=False,
                                                                                              temporary_trash=False,
                                                                                              temporary_deleted=False,
                                                                                              calculate_status=True)
                kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter(
                    kill_house__in=kill_houses,
                    date__date__gte=date1,
                    date__date__lte=date2,
                    trash=False,
                    temporary_trash=False,
                    temporary_deleted=False,
                    calculate_status=True)
                kill_house_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False,
                                                                          receiver_state__in=('pending', 'accepted'),
                                                                          date__date__gte=date1,
                                                                          date__date__lte=date2,
                                                                          temporary_trash=False,
                                                                          temporary_deleted=False,
                                                                          to_cold_house__isnull=True,
                                                                          calculate_status=True)
            else:
                kill_house_requests = KillHouseRequest.objects.filter(
                    Q(killhouse_user__in=kill_houses) | Q(killer__in=kill_houses),
                    temporary_trash=False,
                    temporary_deleted=False,
                    trash=False, calculate_status=True)

                kill_house_free_bar_informations = KillHouseFreeBarInformation.objects.filter(
                    kill_house__in=kill_houses,
                    trash=False,
                    temporary_trash=False,
                    temporary_deleted=False,
                    calculate_status=True)
                kill_house_free_Sale_bar_informations = KillHouseFreeSaleBarInformation.objects.filter(
                    kill_house__in=kill_houses,
                    trash=False,
                    temporary_trash=False,
                    temporary_deleted=False,
                    calculate_status=True)
                kill_house_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False,
                                                                          receiver_state__in=('pending', 'accepted'),
                                                                          temporary_trash=False,
                                                                          temporary_deleted=False,
                                                                          to_cold_house__isnull=True,
                                                                          calculate_status=True)
            total_kill_house_requests_quantity = kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[
                                                     'total'] or 0
            total_kill_house_requests_weight = kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                                                   'total'] or 0
            total_entered_kill_house_requests_carcasses_weight = \
                kill_house_requests.filter(ware_house_confirmation=True).aggregate(
                    total=Sum('ware_house_accepted_real_weight'))[
                    'total'] or 0
            kill_house_free_bar_informations_live = kill_house_free_bar_informations.filter(buy_type='live')
            kill_house_free_bar_informations_carcasses = kill_house_free_bar_informations.filter(buy_type='carcass')
            total_kill_house_free_bar_quantity = \
                kill_house_free_bar_informations_live.aggregate(total=Sum('quantity'))['total'] or 0
            total_kill_house_free_bar_weight = \
                kill_house_free_bar_informations_live.aggregate(total=Sum('live_weight'))['total'] or 0
            total_kill_house_free_bar_carcasses = \
                kill_house_free_bar_informations_carcasses.aggregate(total=Sum('number_of_carcasses'))[
                    'total'] or 0
            total_kill_house_free_bar_carcasses_weight = \
                kill_house_free_bar_informations_carcasses.aggregate(total=Sum('weight_of_carcasses'))[
                    'total'] or 0
            total_entered_kill_house_free_bar_carcasses_weight = \
                kill_house_free_bar_informations.aggregate(total=Sum('weight_of_carcasses'))[
                    'total'] or 0

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

            total_kill_house_allocations_weight = \
                kill_house_allocations.aggregate(total=Sum('real_weight_of_carcasses'))[
                    'total'] or 0

            warehouse_total_weight = total_kill_house_requests_weight + total_kill_house_free_bar_weight + total_kill_house_free_bar_carcasses_weight
            warehouse_total_entered_carcasses_weight = total_entered_kill_house_requests_carcasses_weight + total_entered_kill_house_free_bar_carcasses_weight

            result = {
                "product_remain_weight": int(warehouse_total_entered_carcasses_weight - (
                        total_kill_house_allocations_weight + total_kill_house_free_sale__bar_carcasses_weight)),
                "warehouse_total_quantity": int(
                    total_kill_house_requests_quantity + total_kill_house_free_bar_quantity + total_kill_house_free_bar_carcasses),
                "warehouse_total_weight": int(warehouse_total_weight),
                "warehouse_total_entered_carcasses_weight": int(warehouse_total_entered_carcasses_weight),
                "total_kill_house_allocations_weight": int(total_kill_house_allocations_weight),
                "total_kill_house_free_sale_bar_carcasses_weight": int(
                    total_kill_house_free_sale__bar_carcasses_weight),

            }

            value_header_list = [
                result['warehouse_total_quantity'],  # حجم کل بارها
                result['warehouse_total_weight'],  # وزن کل بارها
                result['warehouse_total_entered_carcasses_weight'],  # وزن وارد شده به انبار
                result['total_kill_house_allocations_weight'],  # وزن توزیع شده داخل استان
                result['total_kill_house_free_sale_bar_carcasses_weight'],
                result['product_remain_weight']  # مانده انبار
            ]
            create_value(worksheet, value_header_list, 4, 3, border_style='thin')

            # محاسبه مجموع هر یک از فیلدها
            sum_product_remain_weight = sum(
                data.get('ware_house_info', {}).get('product_remain_weight', 0) for data in serializer)
            sum_previous_product_remain_weight = sum(
                data.get('ware_house_info', {}).get('previous_product_remain_weight', 0) for data in serializer)
            sum_province_kill_requests_quantity = sum(
                data.get('ware_house_info', {}).get('province_kill_requests_quantity', 0) for data in serializer)
            sum_total_province_bars = sum(
                data.get('ware_house_info', {}).get('total_province_bars', 0) for data in serializer)
            sum_total_province_bars_quantity = sum(
                data.get('ware_house_info', {}).get('total_province_bars_quantity', 0) for data in serializer)
            sum_total_province_bars_weight = sum(
                data.get('ware_house_info', {}).get('total_province_bars_weight', 0) for data in serializer)
            sum_total_kill_house_free_bar = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_bar', 0) for data in serializer)
            sum_total_kill_house_free_live_bar_quantity = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_quantity', 0) for data in
                serializer)
            sum_total_kill_house_free_live_bar_weight = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_live_bar_weight', 0) for data in serializer)
            sum_total_kill_house_free_carcasses_bar = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_carcasses_bar', 0) for data in serializer)
            sum_total_kill_house_free_bar_carcasses = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses', 0) for data in serializer)
            sum_total_kill_house_free_bar_carcasses_weight = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_bar_carcasses_weight', 0) for data in
                serializer)
            sum_total_bars = sum(data.get('ware_house_info', {}).get('total_bars', 0) for data in serializer)
            sum_warehouse_total_quantity = sum(
                data.get('ware_house_info', {}).get('warehouse_total_quantity', 0) for data in serializer)
            sum_warehouse_total_weight = sum(
                data.get('ware_house_info', {}).get('warehouse_total_weight', 0) for data in serializer)
            sum_warehouse_total_entered_bars = sum(
                int(data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0)) for data in serializer)
            sum_warehouse_total_entered_carcasses_weight = sum(
                data.get('ware_house_info', {}).get('warehouse_total_entered_carcasses_weight', 0) for data in
                serializer)
            sum_warehouse_total_not_entered_bars = sum(
                data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars', 0) for data in serializer)
            sum_warehouse_total_not_entered_bars_quantity = sum(
                data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0) for data in
                serializer)
            sum_warehouse_total_not_entered_bars_weight = sum(
                data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0) for data in
                serializer)
            sum_total_kill_house_allocations_weight = sum(
                data.get('ware_house_info', {}).get('total_kill_house_allocations_weight', 0) for data in serializer)
            sum_total_kill_house_free_sale__bar_carcasses_weight = sum(
                data.get('ware_house_info', {}).get('total_kill_house_free_sale__bar_carcasses_weight', 0) for data in
                serializer)
            sum_total_sell = sum(
                data.get('ware_house_info', {}).get('total_sell', 0) for data in
                serializer)
            sum_warehouse_total_entered_bars = sum(
                data.get('ware_house_info', {}).get('warehouse_total_entered_bars', 0) for data in
                serializer)

            # ایجاد لیست نهایی برای ردیف مجموع
            summary_list = [
                'جمع کل==>',
                '',
                '',
                '',
                '',
                sum_product_remain_weight,
                sum_warehouse_total_entered_bars,
                sum_total_sell,
                sum_province_kill_requests_quantity,
                sum_total_province_bars,
                sum_total_province_bars_quantity,
                sum_total_province_bars_weight,
                sum_total_kill_house_free_bar,
                sum_total_kill_house_free_live_bar_quantity,
                sum_total_kill_house_free_live_bar_weight,
                sum_total_kill_house_free_carcasses_bar,
                sum_total_kill_house_free_bar_carcasses,
                sum_total_kill_house_free_bar_carcasses_weight,
                sum_total_bars,
                sum_warehouse_total_quantity,
                sum_warehouse_total_weight,
                sum_warehouse_total_entered_bars,
                sum_warehouse_total_not_entered_bars,
                sum_warehouse_total_not_entered_bars_quantity,
                sum_warehouse_total_not_entered_bars_weight,
                sum_total_kill_house_allocations_weight,
                sum_total_kill_house_free_sale__bar_carcasses_weight
            ]

            # اضافه کردن ردیف مجموع به اکسل
            create_value(worksheet, summary_list, l + 1, 1, color='green')

    # for kill_house in kill_houses:
    #     sheet_name = kill_house.name
    #     worksheet = workbook.create_sheet(sheet_name)
    #     worksheet.sheet_view.rightToLeft = True
    #     worksheet.insert_rows(1)
    #
    #
    #     if 'date1' in request.GET:
    #         date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    #         date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    #         from1 = shamsi_date(date1)
    #         from2 = shamsi_date(date2)
    #         excel_description(worksheet, 'A7',
    #                           f'گزارش جامع انبار کشتارگاه {kill_house.name} از تاریخ {from1} تا تاریخ {from2}',
    #                           size=11, color='red', row2='C9')
    #     else:
    #         excel_description(worksheet, 'A7', f'گزارش جامع انبار کشتارگاه {kill_house.name}',
    #                           size=11, color='red', row2='C8')
    #
    #     excel_description(worksheet, 'D2', f'مدیریت انبار',
    #                       size=11, color='red', row2='G2')
    #     header_list2 = [
    #         'ردیف',
    #         'نام محصول',
    #         'وزن خریدهای دولتی داخل استان(کیلوگرم)',
    #         'وزن خریدهای آزاد داخل استان(کیلوگرم)',
    #         'وزن خریدهای خارج استان(کیلوگرم)',
    #         'کل ورودی به انبار(کیلوگرم)',
    #         'کل فروش(کیلوگرم)',
    #         'مانده انبار(کیلوگرم)',
    #
    #     ]
    #     create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='FF0000', border_style='thin')
    #     products = RolesProducts.objects.filter(kill_house=kill_house, trash=False)
    #     q = 4
    #     w = 1
    #     for product in products:
    #         value_header_list = [
    #             w,
    #             product.name,
    #             product.province_governmental_carcasses_weight,
    #             product.province_free_carcasses_weight,
    #             product.free_buying_carcasses_weight,
    #             product.total_carcasses_weight,
    #             product.real_allocated_weight,
    #             product.total_remain_weight,
    #
    #         ]
    #         create_value(worksheet, value_header_list, q, 3, border_style='thin')
    #         q += 1
    #         w += 1
    #
    #     excel_description(worksheet, 'D6', f'اطلاعات پخش',
    #                       size=11, color='red', row2='G6')
    #     header_list2 = [
    #         'فروش و توزیع داخل استان(کیلوگرم)',
    #         'فروش و توزیع خارج استان(کیلوگرم)',
    #
    #     ]
    #     create_header(worksheet, header_list2, 5, 7, height=21.8, width=20, color='C00000', border_style='thin')
    #
    #     steward_allocations = StewardAllocation.objects.filter(kill_house=kill_house,
    #                                                            receiver_state__in=('pending', 'accepted'),
    #                                                            calculate_status=True, trash=False)
    #     steward_allocations_weight = \
    #         steward_allocations.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0
    #
    #     free_sales = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
    #                                                                                            temporary_trash=False,
    #                                                                                            temporary_deleted=False,
    #                                                                                            calculate_status=True)
    #     free_sales_weight = free_sales.aggregate(total=Sum('real_weight_of_carcasses'))['total'] or 0
    #     value_header_list = [
    #         steward_allocations_weight,
    #         free_sales_weight,
    #
    #     ]
    #     create_value(worksheet, value_header_list, 8, 5, border_style='thin')
    #
    #     excel_description(worksheet, 'D11', f'بارهای در انتظار ورود به انبار',
    #                       size=11, color='red', row2='G11')
    #     data = KillHouseForProvinceWareHouseDashboardSerializer(kill_house, context={'request': request}).data
    #
    #     header_list = [
    #         'تعداد بار',
    #         'حجم بار',
    #         'وزن بار',
    #         'میانگین وزن ',
    #
    #     ]
    #
    #     # برای بالای هدر
    #     # header_list2 = [
    #     #     'تعداد درخواست مرغداران',
    #     #     ' مجموع تعداد قطعه درخواست مرغداران',
    #     #     ' مجموع وزن درخواست مرغداران',
    #     #
    #     # ]
    #     # create_header(worksheet, header_list2, 1, 12, height=21.8, color='green',border_style='thin')
    #
    #     create_header(worksheet, header_list, 3, 12, height=21.8, border_style='thin')
    #     if 'date1' in request.GET and request.GET['date1']:
    #
    #         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(killhouse_user=kill_house) | Q(killer=kill_house),
    #             kill_request__recive_date__date__gte=date1,
    #             kill_request__recive_date__date__lte=date2,
    #             ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
    #             '-kill_request__recive_date').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',
    #                                                   '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',
    #             'bar_document_status__title'
    #         )
    #     else:
    #         filtered_kill_reqs = KillHouseRequest.objects.filter(
    #             Q(killhouse_user=kill_house) | Q(killer=kill_house),
    #             ware_house_confirmation=False, trash=False, calculate_status=True).order_by(
    #             '-kill_request__recive_date').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',
    #                                                   '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',
    #             'bar_document_status__title'
    #         )
    #
    #
    #
    #
    #
    #     all_age = []
    #
    #     all_real_quantity = 0
    #     all_net_weighte = 0
    #     all_weighte = 0
    #     kill_keys = [kill.get('key') for kill in filtered_kill_reqs]
    #     assignments = KillHouseAssignmentInformation.objects.filter(
    #         kill_house_request__key__in=kill_keys, trash=False
    #     ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key')
    #     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:
    #         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)
    #
    #             key = kill.get('key')
    #             net_weighte, real_quantity, 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
    #
    #             weight = int(kill.get('quantity') * kill.get(
    #                 'province_kill_request__province_request__poultry_request__Index_weight'))
    #
    #             if kill['message'] is not None:
    #                 state_delete = 'بار حذف شده'
    #             else:
    #                 all_weighte += weight
    #
    #     value_header_list = [
    #
    #         data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars', 0),
    #         data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0),
    #         data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0),
    #         round(data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0) / data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0),
    #               1) if data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_weight', 0) > 0 and data.get('ware_house_info', {}).get('warehouse_total_not_entered_bars_quantity', 0) > 0 else 0,
    #
    #     ]
    #     create_value(worksheet, value_header_list, 13, 3, border_style='thin')
    #
    #     excel_description(worksheet, 'D15', f'بارهای وارد شده به انبار',
    #                       size=11, color='red', row2='G15')
    #     header_list = [
    #         'تعداد بارهای ایجاد شده',
    #
    #         'مجموع حجم بارها',
    #         'مجموع وزن بارها',
    #         'میانگین وزن ',
    #
    #         ' افت در لحظه',
    #         ' افت لاشه ورود به انبار',
    #
    #     ]
    #
    #     # برای بالای هدر
    #     # header_list2 = [
    #     #     'تعداد درخواست مرغداران',
    #     #     ' مجموع تعداد قطعه درخواست مرغداران',
    #     #     ' مجموع وزن درخواست مرغداران',
    #     #
    #     # ]
    #     # create_header(worksheet, header_list2, 1, 16, height=21.8, color='green', border_style='thin')
    #
    #     create_header(worksheet, header_list, 3, 16, height=21.8, border_style='thin')
    #     if 'date1' in request.GET and request.GET['date1']:
    #
    #         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(killhouse_user=kill_house) | Q(killer=kill_house),
    #             kill_request__recive_date__date__gte=date1,
    #             kill_request__recive_date__date__lte=date2,
    #             ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
    #             '-kill_request__recive_date').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',
    #                                                   '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',
    #             'bar_document_status__title'
    #         )
    #     else:
    #         filtered_kill_reqs = KillHouseRequest.objects.filter(
    #             Q(killhouse_user=kill_house) | Q(killer=kill_house),
    #             ware_house_confirmation=True, trash=False, calculate_status=True).order_by(
    #             '-kill_request__recive_date').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',
    #                                                   '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',
    #             'bar_document_status__title'
    #         )
    #
    #     all_state_ware_house_confirmation = len(filtered_kill_reqs.filter(ware_house_confirmation=True))
    #
    #     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_kill_request_quantity = aggregate_filtered_kill_reqs['total_quantity'] or 0
    #
    #     all_weight_loss = aggregate_filtered_kill_reqs['total_weight_loss'] or 0
    #
    #     all_weight_loss = round(int(all_weight_loss) / all_state_ware_house_confirmation,
    #                             2) if all_weight_loss > 0 else 0
    #     all_age = []
    #
    #     all_real_quantity = 0
    #     all_net_weighte = 0
    #     all_weighte = 0
    #     kill_keys = [kill.get('key') for kill in filtered_kill_reqs]
    #     assignments = KillHouseAssignmentInformation.objects.filter(
    #         kill_house_request__key__in=kill_keys, trash=False
    #     ).only('create_date', 'net_weight', 'real_quantity', 'kill_house_request__key')
    #     assignment_mapping = {
    #         assignment.kill_house_request.key: (
    #             int(assignment.net_weight), assignment.real_quantity, assignment.create_date)
    #         for assignment in assignments
    #     }
    #     all_total_weight_loss = 0
    #     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)
    #
    #             key = kill.get('key')
    #             net_weighte, real_quantity, 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
    #
    #             weight = int(kill.get('quantity') * kill.get(
    #                 'province_kill_request__province_request__poultry_request__Index_weight'))
    #
    #             if kill['message'] is not None:
    #                 state_delete = 'بار حذف شده'
    #             else:
    #                 all_weighte += 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 kill['accepted_real_weight'] > 0 else 0
    #             all_total_weight_loss += total_weight_loss
    #     all_total_weight_loss = all_total_weight_loss / len(filtered_kill_reqs) if len(filtered_kill_reqs) > 0 else 0
    #     value_header_list = [
    #         data.get('ware_house_info', {}).get('total_bars', 0),
    #         data.get('ware_house_info', {}).get('warehouse_total_quantity', 0),
    #         data.get('ware_house_info', {}).get('warehouse_total_weight', 0),
    #         round(data.get('ware_house_info', {}).get('warehouse_total_weight', 0) / data.get('ware_house_info', {}).get('warehouse_total_quantity', 0),
    #               1) if data.get('ware_house_info', {}).get('warehouse_total_weight', 0) > 0 and data.get('ware_house_info', {}).get('warehouse_total_quantity', 0) > 0 else 0,
    #
    #         f'%{int(all_total_weight_loss)}',
    #         f'%{all_weight_loss}',
    #
    #     ]
    #     create_value(worksheet, value_header_list, 17, 3, border_style='thin')
    #
    #     excel_description(worksheet, 'D19', f'فروش به داخل استان',
    #                       size=11, color='red', row2='G19')
    #     if 'date1' in request.GET and request.GET['date1']:
    #
    #         date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    #
    #         date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    #
    #         allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
    #                                                        trash=False, date__date__gte=date1,
    #                                                        date__date__lte=date2).order_by('id')
    #     else:
    #         allocations = StewardAllocation.objects.filter(Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
    #                                                        trash=False).order_by('id')
    #
    #     header_list2 = [
    #         'تعداد تخصیصات',
    #         'قیمت کل',
    #         'حجم تخصیصی',
    #         'وزن تخصیصی',
    #         'حجم تایید شده',
    #         'وزن تایید شده',
    #
    #     ]
    #     create_header(worksheet, header_list2, 4, 20, height=21, width=16.01, border_style='thin')
    #     total_amount_allocations = allocations.aggregate(
    #         total_quantity=Sum('total_amount')).get(
    #         'total_quantity') or 0
    #     number_of_carcasses_allocations = allocations.aggregate(
    #         total_quantity=Sum('number_of_carcasses')).get(
    #         'total_quantity') or 0
    #     weight_of_carcasses_allocations = allocations.aggregate(
    #         total_quantity=Sum('weight_of_carcasses')).get(
    #         'total_quantity') or 0
    #     receiver_real_number_of_carcasses_allocations = allocations.aggregate(
    #         total_quantity=Sum('receiver_real_number_of_carcasses')).get(
    #         'total_quantity') or 0
    #     receiver_real_weight_of_carcasses_allocations = allocations.aggregate(
    #         total_quantity=Sum('receiver_real_weight_of_carcasses')).get(
    #         'total_quantity') or 0
    #
    #     value_header_list2 = [
    #         len(allocations),
    #         total_amount_allocations,
    #         number_of_carcasses_allocations,
    #         weight_of_carcasses_allocations,
    #         receiver_real_number_of_carcasses_allocations,
    #         receiver_real_weight_of_carcasses_allocations,
    #
    #     ]
    #     create_value(worksheet, value_header_list2, 21, 4, border_style='thin')
    #
    #     excel_description(worksheet, 'D23', f'فروش  به خارج استان',
    #                       size=11, color='red', row2='G23')
    #     if 'date1' in request.GET:
    #         date1 = datetime.datetime.strptime(str(request.GET['date1']),
    #                                            '%Y-%m-%d').date()
    #         date2 = datetime.datetime.strptime(str(request.GET['date2']),
    #                                            '%Y-%m-%d').date()
    #         buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
    #                                                                 date__date__gte=date1,
    #                                                                 date__date__lte=date2).order_by('-date')
    #     else:
    #         buyers = KillHouseFreeSaleBarInformation.objects.filter(kill_house=kill_house, trash=False,
    #                                                                 ).order_by('-date')
    #
    #     header_list = [
    #         'تعداد کل فروش',
    #         'تعداد خریداران',
    #         'حجم لاشه(تقریبی)',
    #         'وزن لاشه(کیلوگرم)',
    #
    #     ]
    #
    #     create_header(worksheet, header_list, 4, 24, height=21, width=16.01, border_style='thin')
    #
    #     total_quantity = buyers.aggregate(total=Sum('number_of_carcasses'))[
    #                          'total'] or 0
    #     total_weight = buyers.aggregate(total=Sum('weight_of_carcasses'))[
    #                        'total'] or 0
    #     len_buyers = []
    #     for buyer in buyers:
    #
    #         if buyer.buyer_name not in len_buyers:
    #             len_buyers.append(buyer.buyer_name)
    #     value_list = [
    #         len(buyers),
    #         len(len_buyers),
    #         total_quantity,
    #         total_weight,
    #     ]
    #     create_value(worksheet, value_list, 25, 4, border_style='thin')
    #
    #     excel_description(worksheet, 'D27', f'بار زنده (خرید خارج استان)',
    #                       size=11, color='red', row2='G27')
    #
    #     type = 'live'
    #
    #     role = request.GET.get('role')
    #     order_by_type = '-create_date'
    #
    #     if 'date1' in request.GET:
    #         date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    #         date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    #
    #         filters = {
    #             'create_date__date__gte': date1,
    #             'create_date__date__lte': date2,
    #             'trash': False,
    #         }
    #     else:
    #         filters = {
    #             'trash': False
    #         }
    #
    #     filters['buy_type'] = type
    #
    #     kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type)
    #     header_list2 = [
    #         'تعداد کل بار زنده',
    #         'حجم کل بار زنده',
    #         'وزن کل بار زنده',
    #         'تعداد کل بارهای وارد شده به انبار',
    #         'حجم کل بارهای  زنده وارد شده به انبار',
    #         'وزن کل بارهای زنده وارد شده به انبار',
    #         'وزن لاشه وارد شده به انبار',
    #         'کل بار وارد نشده به انبار',
    #         'حجم کل بار وارد نشده به انبار',
    #         'وزن کل بار وارد نشده به انبار',
    #
    #     ]
    #     create_header(worksheet, header_list2, 2, 28, height=21, width=16.01, border_style='thin')
    #
    #     quantity = kill_house_free_bar_info.aggregate(
    #         total_quantity=Sum('quantity')).get(
    #         'total_quantity') or 0
    #     live_weight = kill_house_free_bar_info.aggregate(
    #         total_quantity=Sum('live_weight')).get(
    #         'total_quantity') or 0
    #
    #     weight_of_carcasses = kill_house_free_bar_info.aggregate(
    #         total_quantity=Sum('weight_of_carcasses')).get(
    #         'total_quantity') or 0
    #
    #     entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses__gt=0)
    #
    #     entered_quantity = entered_bars.aggregate(
    #         total_quantity=Sum('quantity')).get(
    #         'total_quantity') or 0
    #     entered_live_weight = entered_bars.aggregate(
    #         total_quantity=Sum('live_weight')).get(
    #         'total_quantity') or 0
    #
    #     not_entered_bars = kill_house_free_bar_info.filter(weight_of_carcasses=0)
    #
    #     not_entered_quantity = not_entered_bars.aggregate(
    #         total_quantity=Sum('quantity')).get(
    #         'total_quantity') or 0
    #     not_entered_live_weight = not_entered_bars.aggregate(
    #         total_quantity=Sum('live_weight')).get(
    #         'total_quantity') or 0
    #
    #     value_header_list2 = [
    #         len(kill_house_free_bar_info),
    #         quantity,
    #         live_weight,
    #
    #         len(entered_bars),
    #
    #         entered_quantity,
    #         entered_live_weight,
    #         weight_of_carcasses,
    #         len(not_entered_bars),
    #         not_entered_quantity,
    #         not_entered_live_weight,
    #
    #     ]
    #     create_value(worksheet, value_header_list2, 29, 2, border_style='thin')
    #
    #     excel_description(worksheet, 'D31', f'بار لاشه (خرید خارج استان)',
    #                       size=11, color='red', row2='G31')
    #     type = 'carcasses'
    #     bar_state = 'entered'
    #
    #     kill_houses = None
    #     order_by_type = '-create_date'
    #
    #     if 'date1' in request.GET:
    #         date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    #         date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    #
    #         filters = {
    #             'create_date__date__gte': date1,
    #             'create_date__date__lte': date2,
    #             'trash': False,
    #         }
    #     else:
    #         filters = {
    #             'trash': False
    #         }
    #
    #     if kill_houses is not None:
    #         filters['kill_house__in'] = kill_houses
    #
    #     if type:
    #         filters['buy_type'] = type
    #         if type == 'live':
    #             if bar_state:
    #                 if bar_state == 'entered':
    #                     filters['weight_of_carcasses__gt'] = 0
    #                 else:
    #                     filters['weight_of_carcasses'] = 0
    #
    #     kill_house_free_bar_info = KillHouseFreeBarInformation.objects.filter(**filters).order_by(order_by_type)
    #     header_list2 = [
    #         'تعداد کل بار',
    #         'حجم لاشه',
    #         'وزن لاشه',
    #
    #     ]
    #     create_header(worksheet, header_list2, 5, 32, height=21, width=16.01, border_style='thin')
    #
    #     number_of_carcasses = kill_house_free_bar_info.aggregate(
    #         total_quantity=Sum('number_of_carcasses')).get(
    #         'total_quantity') or 0
    #     weight_of_carcasses = kill_house_free_bar_info.aggregate(
    #         total_quantity=Sum('weight_of_carcasses')).get(
    #         'total_quantity') or 0
    #
    #     value_header_list2 = [
    #         len(kill_house_free_bar_info),
    #         number_of_carcasses,
    #         weight_of_carcasses,
    #
    #     ]
    #     create_value(worksheet, value_header_list2, 33, 5, border_style='thin')

    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 cold_house_excel(request):
    filterset_class = StewardAllocationFilterSet
    filterset_fields = [
        'guilds__user__first_name',
        'guilds__user__last_name',
        'guilds__user__fullname',
        'guilds__user__mobile',
        'steward__user__first_name',
        'steward__user__last_name',
        'steward__user__fullname',
        'steward__user__mobile',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__name',
        'to_guilds__user__first_name',
        'to_guilds__user__last_name',
        'to_guilds__user__fullname',
        'to_guilds__user__mobile',
        'to_steward__user__first_name',
        'to_steward__user__last_name',
        'to_steward__user__fullname',
        'to_steward__user__mobile',
        'to_kill_house__kill_house_operator__user__first_name',
        'to_kill_house__kill_house_operator__user__last_name',
        'to_kill_house__kill_house_operator__user__fullname',
        'to_kill_house__kill_house_operator__user__mobile',
        'to_kill_house__name',
    ]

    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).first()
        cold_house = ColdHouse.objects.filter(key=request.GET['cold_house_key'], trash=False).first()

    else:
        cold_house = ColdHouse.objects.filter(live_stock_support__isnull=False, trash=False).first()

    if request.GET['type'] == 'output':
        type = 'بارهای خارج شده'
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        # cold_house = ColdHouse.objects.get(key=request.GET['cold_house_key'], trash=False)

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

            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if 'cold_house' in request.GET:
                cold_house = ColdHouse.objects.get(kill_house=kill_house, trash=False)
                allocations = StewardAllocation.objects.filter(to_cold_house=cold_house,
                                                               trash=False, date__date__gte=date1,
                                                               date__date__lte=date2).order_by('-date')

            else:
                allocations = StewardAllocation.objects.filter(
                    Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                    trash=False, date__date__gte=date1,
                    date__date__lte=date2).order_by('id')
        else:
            if 'cold_house' in request.GET:
                cold_house = ColdHouse.objects.get(key=request.GET['cold_house_key'], trash=False)
                allocations = StewardAllocation.objects.filter(to_cold_house=cold_house,
                                                               trash=False).order_by('-date')

            else:
                allocations = StewardAllocation.objects.filter(
                    Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                    trash=False).order_by('id')
    else:
        type = 'بارهای وارد شده'
        user = SystemUserProfile.objects.get(key=request.GET['key'])
        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        # cold_house = ColdHouse.objects.get(key=request.GET['cold_house_key'], trash=False)

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

            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            if 'cold_house' in request.GET:
                cold_house = ColdHouse.objects.filter(kill_house=kill_house, trash=False).first()
                allocations = StewardAllocation.objects.filter(to_cold_house=cold_house,
                                                               trash=False, date__date__gte=date1,
                                                               date__date__lte=date2).order_by('-date')

            else:
                allocations = StewardAllocation.objects.filter(
                    Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                    trash=False, date__date__gte=date1,
                    date__date__lte=date2).order_by('id')
        else:
            if 'cold_house' in request.GET:
                cold_house = ColdHouse.objects.filter(key=request.GET['cold_house_key'], trash=False).first()
                allocations = StewardAllocation.objects.filter(to_cold_house=cold_house,
                                                               trash=False).order_by('-date')

            else:
                allocations = StewardAllocation.objects.filter(
                    Q(kill_house=kill_house) | Q(to_kill_house=kill_house),
                    trash=False).order_by('id')
    if 'search' in request.GET:
        if request.GET['search'] == 'filter':
            if request.GET['value'] != "" and request.GET['value'] != 'undefined':
                for item in filterset_fields:
                    query = QueryDict('{0}__contains={1}'.format(item, request.GET['value']))
                    if (filterset_class(
                            data=query,
                            queryset=allocations
                    )
                    ).filter():
                        ps = filterset_class(data=query, queryset=allocations)
                        allocations = ps.filter()
                allocations = [] if len(
                    allocations) == 0 else allocations

    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)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    excel_description(worksheet, 'A5', type, color='red', row2='C5')
    header_list2 = [
        'وزن کل',
        'وزن خارج شده',
        'وزن باقیمانده',
        'تعداد کل بار وارد شده',
        'وزن کل بار وارد شده',
        'تعداد کل بار خارج شده',
        'وزن کل بار خارج شده',

    ]

    create_header(worksheet, header_list2, 5, 2, height=20.8, border_style='thin')
    cell_color_changer(worksheet, 2, 5, 8, 'FF0000')
    create_header_freez(worksheet, excel_options, 1, 6, 7, 20)

    kill_house_name = ''
    if allocations.exists():
        kill_house_name = allocations.first().kill_house.name
    excel_description(worksheet, 'A1', f'سردخانه  {kill_house_name}', size=11, color='red',
                      row2='D1')

    worksheet['A3'].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 = 'A3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['A3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1

    if allocations:
        for allocation in allocations:
            l += 1

            if allocation.allocation_type == 'killhouse_steward':
                allocation_type = 'کشتارگاه به مباشر'
                buyer_name = allocation.to_steward.guilds_name
                buyer_mobile = allocation.to_steward.user.mobile
            elif allocation.allocation_type == 'killhouse_guild':
                allocation_type = 'کشتارگاه به صنف'
                buyer_name = allocation.to_guilds.guilds_name
                buyer_mobile = allocation.to_guilds.user.mobile
            elif allocation.allocation_type == 'ColdHouse':
                allocation_type = 'کشتارگاه به سردخانه'
                if allocation.to_cold_house.kill_house:
                    buyer_name = allocation.to_cold_house.kill_house.name
                    buyer_mobile = allocation.to_cold_house.kill_house.kill_house_operator.user.mobile
                else:
                    buyer_name = allocation.to_cold_house.live_stock_support.user.name
                    buyer_mobile = allocation.to_cold_house.live_stock_support.user.mobile
            elif allocation.allocation_type == 'killhouse_killhouse':
                allocation_type = 'کشتارگاه به کشتارگاه'
                buyer_name = allocation.to_kill_house.kill_house.name
                buyer_mobile = allocation.to_kill_house.kill_house_operator.user.mobile
            else:
                allocation_type = '-'
                buyer_name = '-'
                buyer_mobile = '-'

            if allocation.sell_type == 'exclusive':
                sell_type = 'اختصاصی'
            else:
                sell_type = 'آزاد'
            system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده'
            state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده'
            list1 = [
                m,
                str(shamsi_date((allocation.date))),
                allocation_type,
                buyer_name,
                buyer_mobile,
                sell_type,
                allocation.amount,
                allocation.total_amount,
                allocation.number_of_carcasses,
                allocation.weight_of_carcasses,
                allocation.receiver_real_number_of_carcasses,
                allocation.receiver_real_weight_of_carcasses,
                # allocation.registration_code,
                # system_registration_code,
                state,

            ]
            m += 1

            create_value(worksheet, list1, l + 1, 1)
    total_input_bars_weight = allocations.aggregate(
        total=Sum('real_weight_of_carcasses'))['total'] or 0
    total_number_of_carcasses = allocations.aggregate(
        total=Sum('number_of_carcasses'))['total'] or 0
    total_weight_of_carcasses = allocations.aggregate(
        total=Sum('weight_of_carcasses'))['total'] or 0
    total_receiver_real_number_of_carcasses = allocations.aggregate(
        total=Sum('receiver_real_number_of_carcasses'))['total'] or 0
    total_receiver_real_weight_of_carcasses = allocations.aggregate(
        total=Sum('receiver_real_weight_of_carcasses'))['total'] or 0

    value_header_list2 = [
        cold_house.total_input_weight,
        cold_house.total_allocated_weight,
        cold_house.total_remain_weight,
        len(allocations),
        total_input_bars_weight,
        0,
        0,

    ]

    create_value(worksheet, value_header_list2, 3, 5, border_style='thin')
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        total_number_of_carcasses,
        total_weight_of_carcasses,
        total_receiver_real_number_of_carcasses,
        total_receiver_real_weight_of_carcasses,
        # '',
        # '',
        '',

    ]
    # 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 = '#,###'  # 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")
    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="سردخانه  {kill_house_name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def management_cold_house_excel(request):
    filterset_class = StewardAllocationFilterSet
    filterset_fields = [
        'guilds__user__first_name',
        'guilds__user__last_name',
        'guilds__user__fullname',
        'guilds__user__mobile',
        'steward__user__first_name',
        'steward__user__last_name',
        'steward__user__fullname',
        'steward__user__mobile',
        'kill_house__kill_house_operator__user__first_name',
        'kill_house__kill_house_operator__user__last_name',
        'kill_house__kill_house_operator__user__fullname',
        'kill_house__kill_house_operator__user__mobile',
        'kill_house__name',
        'to_guilds__user__first_name',
        'to_guilds__user__last_name',
        'to_guilds__user__fullname',
        'to_guilds__user__mobile',
        'to_steward__user__first_name',
        'to_steward__user__last_name',
        'to_steward__user__fullname',
        'to_steward__user__mobile',
        'to_kill_house__kill_house_operator__user__first_name',
        'to_kill_house__kill_house_operator__user__last_name',
        'to_kill_house__kill_house_operator__user__fullname',
        'to_kill_house__kill_house_operator__user__mobile',
        'to_kill_house__name',
    ]

    excel_options = [
        'ردیف',
        'نام سردخانه',
        'شهر',
        'آدرس',
        'وزن کل',
        'وزن خارج شده',
        'وزن باقیمانده',
        'وضعیت',
        'اجازه پخش',
        'اجازه جابه جایی',
        'ظرفیت',

    ]
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    sheet_name = 'اطلاعات کلی'
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)
    worksheet = workbook.create_sheet(sheet_name)

    if sheet_name == 'اطلاعات کلی':
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)

        header_list2 = [
            'ردیف',
            'نام کشتارگاه',
            'نام مالک',
            'موبایل',
            'شهر',
            'تعداد سرد خانه ها',
            'وزن وارد شده',
            'وزن خارج شده',
            'وزن باقیمانده',

        ]

        create_header(worksheet, header_list2, 3, 8, height=25.8, border_style='thin', width=15)

        header_list3 = [
            'تعداد کل سردخانه',
            'تعداد کل سردخانه کشتارگاه',
            'تعداد کل سردخانه مباشرین',
            'کل وزن وارد شده',
            'کل وزن خارج شده',
            'کل وزن باقیمانده',

        ]
        create_header(worksheet, header_list3, 5, 3, height=25.8, border_style='thin', width=15, color='FF0000')
        cold_houses = ColdHouse.objects.filter(trash=False)
        kill_house_cold_houses = cold_houses.filter(kill_house__isnull=False)
        steward_cold_houses = cold_houses.filter(steward__isnull=False)
        total_input_weight = cold_houses.aggregate(
            total=Sum('total_input_weight'))['total'] or 0

        total_allocated_weight = cold_houses.aggregate(
            total=Sum('total_allocated_weight'))['total'] or 0

        total_remain_weight = cold_houses.aggregate(
            total=Sum('total_remain_weight'))['total'] or 0

        result = {
            "total_cold_houses": len(cold_houses),
            "total_kill_house_cold_house": len(kill_house_cold_houses),
            "total_steward_cold_house": len(steward_cold_houses),
            "total_input_weight": total_input_weight,
            "total_allocated_weight": total_allocated_weight,
            "total_remain_weight": total_remain_weight,
        }

        list1 = [
            len(cold_houses),
            len(kill_house_cold_houses),
            len(steward_cold_houses),
            total_input_weight,
            total_allocated_weight,
            total_remain_weight,

        ]
        create_header(worksheet, list1, 5, 4, height=25.8, border_style='thin', color='D9D9D9', text_color='000000')

        excel_description(worksheet, 'A3', f'مدیریت سرد خانه ها', color='red', row2='C4')

        l = 8
        m = 1
        for kill_house in kill_houses:
            cold_houses = ColdHouse.objects.filter(kill_house=kill_house, trash=False)
            if cold_houses:
                total_input_weight = cold_houses.aggregate(total=Sum('total_input_weight'))[
                                         'total'] or 0
                total_allocated_weight = cold_houses.aggregate(total=Sum('total_allocated_weight'))[
                                             'total'] or 0
                total_remain_weight = cold_houses.aggregate(total=Sum('total_remain_weight'))[
                                          'total'] or 0
                list1 = [
                    m,
                    kill_house.name,
                    kill_house.kill_house_operator.user.fullname,
                    kill_house.kill_house_operator.user.mobile,
                    kill_house.kill_house_operator.user.city.name,
                    len(cold_houses),
                    total_input_weight,
                    total_allocated_weight,
                    total_remain_weight,

                ]
                m += 1
                l += 1
                create_header(worksheet, list1, 3, l, height=25.8, border_style='thin', color='B8CCE4',
                              text_color='000000')

    for kill_house in kill_houses:
        cold_houses = ColdHouse.objects.filter(kill_house=kill_house, trash=False)
        if cold_houses:
            sheet_name = kill_house.name
            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')

            header_list2 = [
                'تعداد سرد خانه',
                'وزن وارد شده',
                'وزن خارج شده',
                'وزن باقیمانده',

            ]

            create_header(worksheet, header_list2, 5, 2, height=20.8, border_style='thin')

            total_input_weight = cold_houses.aggregate(total=Sum('total_input_weight'))[
                                     'total'] or 0
            total_allocated_weight = cold_houses.aggregate(total=Sum('total_allocated_weight'))[
                                         'total'] or 0
            total_remain_weight = cold_houses.aggregate(total=Sum('total_remain_weight'))[
                                      'total'] or 0

            value_header_list2 = [
                len(cold_houses),
                total_input_weight,
                total_allocated_weight,
                total_remain_weight,

            ]

            create_value(worksheet, value_header_list2, 3, 5, border_style='thin')

            create_header_freez(worksheet, excel_options, 1, 6, 7, 20)
            excel_description(worksheet, 'A5', f'سردخانه های {kill_house.name}', color='red', row2='C5')
            l = 5
            m = 1
            for cold_house in cold_houses:
                l += 1

                status = 'فعال' if cold_house.active == True else 'غیر فعال'
                broadcast = 'دارد' if cold_house.broadcast == True else 'ندارد'
                relocate = 'دارد' if cold_house.relocate == True else 'ندارد'

                list1 = [
                    m,
                    cold_house.name,
                    cold_house.city,
                    cold_house.address,
                    cold_house.total_input_weight,
                    cold_house.total_allocated_weight,
                    cold_house.total_remain_weight,
                    status,
                    broadcast,
                    relocate,
                    cold_house.capacity

                ]
                m += 1

                create_value(worksheet, list1, l + 1, 1)
            total_input_weight = cold_houses.aggregate(
                total=Sum('total_input_weight'))['total'] or 0
            total_allocated_weight = cold_houses.aggregate(
                total=Sum('total_allocated_weight'))['total'] or 0
            total_remain_weight = cold_houses.aggregate(
                total=Sum('total_remain_weight'))['total'] or 0
            capacity = cold_houses.aggregate(
                total=Sum('capacity'))['total'] or 0
            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                total_input_weight,
                total_allocated_weight,
                total_remain_weight,
                '',
                '',
                '',
                capacity

            ]

            create_value(worksheet, list2, l + 3, 1, color='yellow')

    # 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 'date1' in request.GET:
    #     date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
    #     date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
    #     from_date_1 = shamsi_date(date1)
    #     to_date_1 = shamsi_date(date2)
    #     worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'

    # header_list2 = [
    #     'وزن کل',
    #     'وزن خارج شده',
    #     'وزن باقیمانده',
    #     'تعداد کل بار وارد شده',
    #     'وزن کل بار وارد شده',
    #     'تعداد کل بار خارج شده',
    #     'وزن کل بار خارج شده',
    #
    # ]
    #
    # create_header(worksheet, header_list2, 5, 2, height=20.8, border_style='thin')
    # cell_color_changer(worksheet, 2, 5, 8, 'FF0000')
    # create_header_freez(worksheet, excel_options, 1, 6, 7, 20)
    #
    # kill_house_name = ''
    # if allocations.exists():
    #     kill_house_name = allocations.first().kill_house.name
    # excel_description(worksheet, 'A1', f'سردخانه  {kill_house_name}', size=11, color='red',
    #                   row2='D1')
    #
    # worksheet['A3'].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 = 'A3:D3'
    # worksheet.merge_cells(merge_range1)
    # worksheet.merge_cells(merge_range)
    # worksheet.merge_cells(merge_range2)
    # worksheet['B1'].font = red_font
    # worksheet['A3'].font = Font(size=11)
    # worksheet['B2'].font = Font(size=10, bold=True, color="C00000")
    #
    # l = 5
    # m = 1
    #
    # if allocations:
    #     for allocation in allocations:
    #         l += 1
    #
    #         if allocation.allocation_type == 'killhouse_steward':
    #             allocation_type = 'کشتارگاه به مباشر'
    #             buyer_name = allocation.to_steward.guilds_name
    #             buyer_mobile = allocation.to_steward.user.mobile
    #         elif allocation.allocation_type == 'killhouse_guild':
    #             allocation_type = 'کشتارگاه به صنف'
    #             buyer_name = allocation.to_guilds.guilds_name
    #             buyer_mobile = allocation.to_guilds.user.mobile
    #         elif allocation.allocation_type == 'ColdHouse':
    #             allocation_type = 'کشتارگاه به سردخانه'
    #             if allocation.to_cold_house.kill_house:
    #                 buyer_name = allocation.to_cold_house.kill_house.name
    #                 buyer_mobile = allocation.to_cold_house.kill_house.kill_house_operator.user.mobile
    #             else:
    #                 buyer_name = allocation.to_cold_house.live_stock_support.user.name
    #                 buyer_mobile = allocation.to_cold_house.live_stock_support.user.mobile
    #         elif allocation.allocation_type == 'killhouse_killhouse':
    #             allocation_type = 'کشتارگاه به کشتارگاه'
    #             buyer_name = allocation.to_kill_house.kill_house.name
    #             buyer_mobile = allocation.to_kill_house.kill_house_operator.user.mobile
    #         else:
    #             allocation_type = '-'
    #             buyer_name = '-'
    #             buyer_mobile = '-'
    #
    #         if allocation.sell_type == 'exclusive':
    #             sell_type = 'اختصاصی'
    #         else:
    #             sell_type = 'آزاد'
    #         system_registration_code = 'ارسال شده' if allocation.system_registration_code == True else 'ارسال نشده'
    #         state = 'در انتظار تایید' if allocation.state == 'pending' else 'تایید شده'
    #         list1 = [
    #             m,
    #             str(shamsi_date((allocation.date))),
    #             allocation_type,
    #             buyer_name,
    #             buyer_mobile,
    #             sell_type,
    #             allocation.amount,
    #             allocation.total_amount,
    #             allocation.number_of_carcasses,
    #             allocation.weight_of_carcasses,
    #             allocation.receiver_real_number_of_carcasses,
    #             allocation.receiver_real_weight_of_carcasses,
    #             # allocation.registration_code,
    #             # system_registration_code,
    #             state,
    #
    #         ]
    #         m += 1
    #
    #         create_value(worksheet, list1, l + 1, 1)
    # total_input_bars_weight = allocations.aggregate(
    #     total=Sum('real_weight_of_carcasses'))['total'] or 0
    # total_number_of_carcasses = allocations.aggregate(
    #     total=Sum('number_of_carcasses'))['total'] or 0
    # total_weight_of_carcasses = allocations.aggregate(
    #     total=Sum('weight_of_carcasses'))['total'] or 0
    # total_receiver_real_number_of_carcasses = allocations.aggregate(
    #     total=Sum('receiver_real_number_of_carcasses'))['total'] or 0
    # total_receiver_real_weight_of_carcasses = allocations.aggregate(
    #     total=Sum('receiver_real_weight_of_carcasses'))['total'] or 0
    #
    # value_header_list2 = [
    #     cold_house.total_input_weight,
    #     cold_house.total_allocated_weight,
    #     cold_house.total_remain_weight,
    #     len(allocations),
    #     total_input_bars_weight,
    #     0,
    #     0,
    #
    # ]
    #
    # create_value(worksheet, value_header_list2, 3, 5, border_style='thin')
    # list2 = [
    #     'مجموع==>',
    #     '',
    #     '',
    #     '',
    #     '',
    #     '',
    #     '',
    #     '',
    #     total_number_of_carcasses,
    #     total_weight_of_carcasses,
    #     total_receiver_real_number_of_carcasses,
    #     total_receiver_real_weight_of_carcasses,
    #     # '',
    #     # '',
    #     '',
    #
    # ]
    #
    # 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


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def create_guilds_or_stewards_from_excel(request):
    pass
    # file = request.FILES['file'].read()
    # read = openpyxl.load_workbook(BytesIO(file), data_only=True)
    # sheet = read.active
    # group = Group.objects.get(name__exact="Guilds")
    # steward_role = Group.objects.get(name__exact="Steward")
    # password = '123456'
    # result_list=[]
    # yesterday= datetime.datetime.now().date()
    # birth_day=convert_to_shamsi(day=yesterday.day,
    #                                      month=yesterday.month,
    #                                      year=yesterday.year).replace('-','/')
    # for i, row in enumerate(sheet.iter_rows(values_only=True)):
    #     if i <= 1:
    #         continue
    #     kill_house_name = row[1]
    #     first_name = row[2]
    #     last_name = row[3]
    #     national_id = row[4]
    #     mobile = row[5]
    #     city_name = row[6]
    #     postal_code = row[7]
    #     address = row[8]
    #     guild_name = row[9]
    #     type_activity = row[10]
    #     area_activity = row[11]
    #     guilds_id = row[12]
    #     license_number = row[13]
    #     is_steward = row[14]
    #
    #
    #     is_steward = True if is_steward == 'مباشر' else 'صنف'
    #     mobile = str(mobile)
    #
    #     if len(mobile) < 10:
    #         continue
    #     if len(mobile) == 10:
    #         mobile = '0' + mobile
    #
    #     try:
    #         city = City.objects.get(name=city_name)
    #         province = Province.objects.get(key=city.province.key)
    #
    #         system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
    #         if system_profile:
    #             if not Guilds.objects.filter(user=system_profile, trash=False).exists():
    #                 hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
    #                 data = {
    #                     "username": mobile,
    #                     "first_name": first_name,
    #                     "last_name": last_name,
    #                     "password": hashed_password,
    #                     "national_code": national_id,
    #                     "role": "Rancher",
    #                     "api_key": PROJECT_API_KEY
    #                 }
    #                 req = requests.post(
    #                     url=ARTA_REGISTER,
    #                     data=data,
    #                     verify=False
    #                 )
    #
    #                 if req.status_code == 200:
    #                     province = Province.objects.filter(trash=False).first()
    #                     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
    #                     city_id = City.objects.filter(trash=False, name=city).first()
    #
    #                     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=datetime.datetime.now().date(),
    #                         city=city_id,
    #                         province=province
    #                     )
    #                     system_profile.save()
    #                     system_profile.role.add(group)
    #                     address = SystemAddress(
    #                         province=province,
    #                         city=city_id,
    #                         address='',
    #
    #                     )
    #                     address.save()
    #
    #             cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
    #             rancher = Rancher(
    #                 user=system_profile,
    #                 address=address,
    #                 cooperative=cooperative,
    #                 name=rancher_name,
    #                 mobile=mobile,
    #                 fullname=first_name + ' ' + last_name,
    #                 city=city,
    #                 herd_name=rancher_name,
    #                 postal_code=postal_code,
    #                 epidemiological_code=epidemiological_code,
    #                 herd_code=herd_code,
    #                 national_id=national_id,
    #                 type='rural' if type_rancher == 'روستایی' else 'industrial'
    #
    #
    #             )
    #             rancher.save()
    #
    #         for _i in range(range_live_stock):
    #             live_stock = LiveStock(
    #                 herd_code=herd_code,
    #                 type=type_live_stock,
    #                 birth_day=birth_day,
    #                 birth_day_gh=yesterday,
    #                 gender=gender,
    #
    #             )
    #             live_stock.save()
    #     except:
    #         result_list.append(rancher_name)
    #
    # return Response(result_list)


def non_receipt_request_excel(request):
    filterset_class = KillHouseRequestFilterSet
    filterset_fields = [
        'killhouse_user__kill_house_operator__user__fullname',
        'killhouse_user__kill_house_operator__user__mobile',
        'province_request__poultry_request__poultry__user__fullname',
        'province_request__poultry_request__poultry__user__mobile',
        'province_request__poultry_request__order_code',
        'province_request__poultry_request__order_code',
        'bar_code',
    ]

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

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

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

    if request.GET['role'] in ['CityOperator', 'CityJahad', 'CityPoultry']:
        if request.GET['role'] == 'CityOperator':
            city_operator = CityOperator.objects.get(user=user, trash=False)
            kill_house_requests = KillHouseRequest.objects.filter(
                (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house)),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                main_non_receipt=True,
                province_request__poultry_request__poultry__city_operator=city_operator.unit_name,

            ).order_by('-kill_request__recive_date')
        else:
            kill_house_requests = KillHouseRequest.objects.filter(
                (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house)),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2,
                main_non_receipt=True,
                province_request__poultry_request__poultry__address__city=user.city

            ).order_by('-kill_request__recive_date')

    else:

        kill_house_requests = KillHouseRequest.objects.filter(
            (Q(killhouse_user__in=kill_house) | Q(kill_request__slaughter_house__in=kill_house) | Q(
                killer__in=kill_house)),
            kill_request__recive_date__date__gte=date1,
            kill_request__recive_date__date__lte=date2,
            main_non_receipt=True

        ).order_by('-kill_request__recive_date')

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

    serializer = KillHouseRequestForBarManagementSerializer(kill_house_requests, many=True).data
    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')
    red_font = Font(color="C00000", bold=True)
    if 'date1' in request.GET:
        date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        from_date_1 = shamsi_date(date1)
        to_date_1 = shamsi_date(date2)
        worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
    header_list2 = [
        "تعداد اولیه",
        "وزن اولیه بار (کیلوگرم)",
        "تحویلی دامپزشک (قطعه)",
        "وزن تحویلی دامپزشک (کیلوگرم)",

    ]

    create_header(worksheet, header_list2, 5, 2, height=20.8, border_style='thin')
    create_header_freez(worksheet, excel_options, 1, 6, 7, 20)

    excel_description(worksheet, 'A1', f'عدم وصول', size=11, color='red',
                      row2='D1')

    worksheet['A3'].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 = 'A3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['A3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    l = 5
    m = 1

    if serializer:
        for data in serializer:
            l += 1
            non_receipt_state_type = 'رد شده'
            non_receipt_state = data.get('non_receipt_state')
            if non_receipt_state:
                if non_receipt_state == 'pending':
                    non_receipt_state_type = 'در انتظار تایید'
                if non_receipt_state == 'accepted':
                    non_receipt_state_type = 'تایید شده'
            non_receipt_check_date = data.get('non_receipt_check_date')
            if non_receipt_check_date:
                try:
                    non_receipt_check_date = datetime.datetime.strptime(str(non_receipt_check_date),
                                                                        '%Y-%m-%dT%H:%M:%S.%f').date()
                except ValueError:
                    non_receipt_check_date = datetime.datetime.strptime(str(non_receipt_check_date),
                                                                        '%Y-%m-%dT%H:%M:%S').date()
                non_receipt_check_date = shamsi_date(non_receipt_check_date, in_value=True)
            else:
                non_receipt_check_date = '-'
            recive_date = data.get('kill_request', {}).get('recive_date')
            if recive_date:
                try:
                    recive_date = datetime.datetime.strptime(str(recive_date), '%Y-%m-%dT%H:%M:%S.%f').date()
                except ValueError:
                    recive_date = datetime.datetime.strptime(str(recive_date), '%Y-%m-%dT%H:%M:%S').date()
                recive_date = shamsi_date(recive_date, in_value=True)
            else:
                recive_date = '-'

            if data.get('poultry_request', {}).get('export') == False:
                export_type = 'عادی'
            else:
                export_type = 'صادرات'
            list1 = [
                m,
                str(data.get('bar_code')) or "-",
                data.get('traffic_code') or "-",
                str(recive_date),
                data.get('killhouse_user', {}).get('name') if data.get(
                    'killhouse_user') else "-",
                data.get('killhouse_user', {}).get('kill_house_operator', {}).get('user', {}).get('mobile') if data.get(
                    'killhouse_user') else "-",
                data.get('killer', {}).get('name') if data.get(
                    'killer') else "-",
                data.get('killer', {}).get('kill_house_operator', {}).get('user', {}).get('mobile') if data.get(
                    'killer') else "-",
                data.get('poultry_request', {}).get('poultry', {}).get('unit_name') if data.get(
                    'poultry_request') else "-",
                data.get('poultry_request', {}).get('poultry', {}).get('user', {}).get('mobile') if data.get(
                    'poultry_request') else "-",
                data.get('quantity') or "-",
                data.get('weight_info', {}).get('weight') if data.get('weight_info') else "-",
                data.get('price') or 0,
                data.get('weight_info', {}).get('kill_house_price') if data.get('weight_info') else 0,
                data.get('car', {}).get('type_car') if data.get('car') else "-",
                data.get('car', {}).get('driver_name') if data.get('car') else "-",
                data.get('vet_accepted_real_quantity') or 0,
                data.get('vet_accepted_real_weight') or 0,
                str(data.get('poultry_request', {}).get('order_code')) if data.get('poultry_request') else "-",
                export_type,
                non_receipt_state_type,
                data.get('message') or "-",
                data.get('non_receipt_checker') or "-",
                str(non_receipt_check_date),
            ]
            m += 1

            create_value(worksheet, list1, l + 1, 1)
    total_quantity = sum(
        data.get('quantity', 0) if data.get('quantity') != "-" else 0
        for data in serializer
    )

    total_weight = sum(
        data.get('weight_info', {}).get('weight', 0) if data.get('weight_info') and data.get('weight_info', {}).get(
            'weight') != "-" else 0
        for data in serializer
    )

    total_price = sum(
        data.get('price', 0)
        for data in serializer
    )

    total_vet_accepted_real_quantity = sum(
        data.get('vet_accepted_real_quantity', 0)
        for data in serializer
    )

    total_vet_accepted_real_weight = sum(
        data.get('vet_accepted_real_weight', 0)
        for data in serializer
    )

    value_header_list2 = [
        total_quantity,
        total_weight,
        total_vet_accepted_real_quantity,
        total_vet_accepted_real_weight

    ]
    # 
    create_value(worksheet, value_header_list2, 3, 5, border_style='thin')
    list2 = [
        'مجموع==>',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        total_quantity,
        total_weight,
        '',
        '',
        '',
        '',
        total_vet_accepted_real_quantity,
        total_vet_accepted_real_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 return_kill_house_request_excel(request):
    serializer_class = KillHouseRequestForBarManagementSerializer
    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',
    ]

    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')
    user = SystemUserProfile.objects.get(key=request.GET['key'])
    if request.GET['role'] == 'KillHouse':

        kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
        if 'date1' in request.GET and 'date2' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            kill_house_requests = KillHouseRequest.objects.filter(
                Q(killhouse_user=kill_house) | Q(killer=kill_house),
                Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2)

        else:
            kill_house_requests = KillHouseRequest.objects.filter(
                Q(killhouse_user=kill_house) | Q(killer=kill_house),
                Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True))

    else:
        if 'date1' in request.GET and 'date2' in request.GET:
            date1 = datetime.datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            kill_house_requests = KillHouseRequest.objects.filter(
                Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True),
                kill_request__recive_date__date__gte=date1,
                kill_request__recive_date__date__lte=date2)

        else:
            kill_house_requests = KillHouseRequest.objects.filter(
                Q(non_receipt=True, main_non_receipt=True) | Q(trash=True, return_trash=True))

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

    serializer = serializer_class(kill_house_requests, many=True).data

    header_list2 = [
            "ردیف",
            "کد بار",
            "کدسفارش",
            "نوع درخواست",
            "نوع کشتار",
            "نام فارم",
            "نام مرغدار",
            "شهر مرغدار",
            "تاریخ درخواست کشتار",
            "تعداد بار",
            "تاریخ ثبت بار",
            "نام کشتارگاه",
            "شهر کشتارگاه",
            "وزن",
            "میانگین وزنی",
            "تعداد نهایی",
            "وزن نهایی",
            "قیمت مرغدار",
            "قیمت کشتارگاه",
            "وضعیت تایید",
            "پلاک خودرو",
            "نام راننده",
            "عدم دریافت",
            "پیام عدم دریافت",
            "نوع برگشت"
        ]
    create_header(worksheet, header_list2, 1, 12, height=21.8, width=20, border_style='thin')
    excel_description(worksheet, 'A2', f'بارهای بازگشتی',
                      size=11, color='red', row2='B4')
    if serializer:
        l = 13
        m = 1

        for item in serializer:
            state = ""
            if item.get('state') == "pending":
                state = "در انتظار تایید"
            elif item.get('state') == "accepted":
                state = "تایید شده"
            elif item.get('state') == "rejected":
                state = "رد شده"

            request_type = ""
            if item.get('poultry_request', {}).get('market'):
                request_type = "پنل معاملات"
            elif item.get('poultry_request', {}).get('direct_buying'):
                request_type = "خرید مستقیم"
            elif item.get('warehouse'):
                request_type = "انبار"
            else:
                request_type = "اتحادیه"

            kill_type = ""
            if item.get('poultry_request', {}).get('freezing'):
                kill_type = "انجماد"
            elif item.get('poultry_request', {}).get('export'):
                kill_type = "صادرات"
            else:
                kill_type = "عادی"

            list1 = [
                m,
                str(item.get('bar_code') or "-"),
                str(item.get('poultry_request', {}).get('order_code')) or "-",
                request_type,
                kill_type,
                item.get('poultry_request', {}).get('poultry', {}).get('unit_name') or "-",
                f"{item.get('poultry_request', {}).get('poultry', {}).get('user', {}).get('fullname') or '-'} ({item.get('poultry_request', {}).get('poultry', {}).get('user', {}).get('mobile') or '-'})",
                item.get('poultry_request', {}).get('poultry', {}).get('address', {}).get('city', {}).get(
                    'name') or "-",
                str(shamsi_date(convert_str_to_date(item.get('kill_request', {}).get('recive_date')), in_value=True)),
                item.get('quantity', 0),
                str(shamsi_date(convert_str_to_date(item.get('create_date')), in_value=True)),
                item.get('killhouse_user', {}).get('name') or item.get('killer', {}).get('name') or "-",
                item.get('killhouse_user', {}).get('kill_house_operator', {}).get('user', {}).get('city', {}).get(
                    'name') or item.get('killer', {}).get('kill_house_operator', {}).get('user', {}).get('city',
                                                                                                         {}).get(
                    'name') or "-",
                item.get('weight_info', {}).get('weight', 0) if item.get('weight_info', {}).get(
                    'weight') else "-",
                item.get('weight_info', {}).get('index_weight', 0) if item.get('weight_info', {}).get(
                    'index_weight') else "-",
                item.get('accepted_real_quantity', 0),
                item.get('accepted_real_weight', 0),
                item.get('poultry_request', {}).get('amount', 0) if item.get('poultry_request', {}).get(
                    'amount') else "-",
                item.get('weight_info', {}).get('kill_house_price', 0) if item.get('weight_info', {}).get(
                    'kill_house_price') else "-",
                state,
                item.get('car', {}).get('pelak') or "-",
                item.get('car', {}).get('driver_name') or "-",
                "دارد" if item.get('non_receipt') else "ندارد",
                item.get('non_receipt_message') or "-",
                ("کاربر" if item.get('non_receipt') and item.get('main_non_receipt') else "سیستم") + " " + str(
                    shamsi_date(convert_str_to_date(item.get('modify_date'))))
            ]

            create_value(worksheet, list1, l, 1, border_style='thin', m=m)
            m += 1
            l += 1
        header_list2 = [
            "تعداد کل تخصیصات",
            "تعداد تخصیصات بازگشتی کاربر",
            "تعداد تخصیصات بازگشتی سیستم",
            "حجم کل تخصیصات",
            "حجم تخصیصات بازگشتی کاربر",
            "حجم تخصیصات بازگشتی سیستم",
            "وزن کل تخصیصات",
            "وزن بازگشتی کاربر",
            "وزن بازگشتی سیستم",
            "تعداد کل بارها",
            "تعداد بارهای عدم وصول",
            "تعداد بارهای بازگشتی سیستمی",
            "حجم کل بارها",
            "حجم بارهای عدم وصول",
            "حجم بارهای بازگشتی سیستمی",
            "وزن کل بارها",
            "وزن بارهای عدم وصول",
            "وزن بارهای بازگشتی سیستمی",
            "وزن خریدهای بازگشتی با کارمزد",
            "کارمزد خریدهای بازگشتی"
        ]
        create_header(worksheet, header_list2, 3, 3, height=21.8, width=20, color='C00000', border_style='thin')

        total_wage_type = WageType.objects.filter(trash=False)
        province_live_wage_type = total_wage_type.filter(en_name='province-kill-request', trash=False).first()
        province_live_wage_type_amount = province_live_wage_type.amount if province_live_wage_type.status == True else 0

        province_kill_request_filters = {
            'archive_wage': False,
            'state__in': ('pending', 'accepted'),
            'first_car_allocated_quantity': 0
        }

        kill_house_request_filters = {}
        if 'date1' in request.GET:
            date1 = request.GET.get('date1')
            date2 = request.GET.get('date2')
            province_kill_request_filters['kill_request__recive_date__date__gte'] = date1
            province_kill_request_filters['kill_request__recive_date__date__lte'] = date2
            kill_house_request_filters['kill_request__recive_date__date__gte'] = date1
            kill_house_request_filters['kill_request__recive_date__date__lte'] = date2
        if request.GET['role'] == 'KillHouse':
            kill_house = KillHouse.objects.filter(kill_house_operator__user=user, trash=False).first()
            province_kill_request_filters['killhouse_user'] = kill_house
            return_kill_house_requests = KillHouseRequest.objects.filter(
                Q(killhouse_user=kill_house) | Q(killer=kill_house),
                Q(non_receipt=True, main_non_receipt=True, non_receipt_state__in=('pending', 'accepted')) | Q(
                    trash=True, return_trash=True),
                **kill_house_request_filters)
        else:
            return_kill_house_requests = KillHouseRequest.objects.filter(
                Q(non_receipt=True, main_non_receipt=True, non_receipt_state__in=('pending', 'accepted')) | Q(
                    trash=True, return_trash=True),
                **kill_house_request_filters)

        return_province_kill_requests = ProvinceKillRequest.objects.filter(
            Q(trash=False, return_to_province=True) | Q(trash=True, return_trash=True),
            **province_kill_request_filters).order_by('id')

        return_province_kill_requests_aggregates = return_province_kill_requests.aggregate(
            total_count=Count('id'),
            total_operator_return_count=Count('id', filter=Q(trash=False, return_to_province=True)),
            total_system_return_count=Count('id', filter=Q(trash=True, return_trash=True)),
            total_quantity=Sum('total_killed_quantity'),
            total_operator_return_quantity=Sum('main_quantity', filter=Q(trash=False, return_to_province=True)),
            total_system_return_quantity=Sum('total_killed_quantity', filter=Q(trash=True, return_trash=True)),
            total_weight=Sum('total_killed_weight'),
            total_operator_return_weight=Sum(F('main_quantity') * F('province_request__poultry_request__Index_weight'),
                                             filter=Q(trash=False, return_to_province=True)),
            total_system_return_weight=Sum('total_killed_weight', filter=Q(trash=True, return_trash=True)),

        )
        return_kill_house_requests_aggregates = return_kill_house_requests.aggregate(
            total_count=Count('id'),
            total_non_receipt_count=Count('id', filter=Q(non_receipt=True, main_non_receipt=True)),
            total_system_return_count=Count('id', filter=Q(trash=True, return_trash=True)),
            total_quantity=Sum('accepted_real_quantity'),
            total_non_receipt_quantity=Sum('accepted_real_quantity', filter=Q(non_receipt=True, main_non_receipt=True)),
            total_system_return_quantity=Sum('accepted_real_quantity', filter=Q(trash=True, return_trash=True)),
            total_weight=Sum('accepted_real_weight'),
            total_non_receipt_weight=Sum('accepted_real_weight', filter=Q(non_receipt=True, main_non_receipt=True)),
            total_system_return_weight=Sum('accepted_real_weight', filter=Q(trash=True, return_trash=True)),
        )
        province_kill_request_total_operator_return_quantity = return_province_kill_requests_aggregates[
                                                                   'total_operator_return_quantity'] or 0
        province_kill_request_total_system_return_quantity = return_province_kill_requests_aggregates[
                                                                 'total_system_return_quantity'] or 0
        province_kill_request_total_quantity = province_kill_request_total_operator_return_quantity + province_kill_request_total_system_return_quantity
        province_kill_request_total_operator_return_weight = return_province_kill_requests_aggregates[
                                                                 'total_operator_return_weight'] or 0
        province_kill_request_total_system_return_weight = return_province_kill_requests_aggregates[
                                                               'total_system_return_weight'] or 0
        province_kill_request_total_weight = province_kill_request_total_operator_return_weight + province_kill_request_total_system_return_weight
        kill_house_request_total_system_return_weight = return_kill_house_requests_aggregates[
                                                            'total_system_return_weight'] or 0
        total_return_weight_with_wage = province_kill_request_total_system_return_weight + kill_house_request_total_system_return_weight
        result = {
            "province_kill_request_total_count": return_province_kill_requests_aggregates['total_count'] or 0,
            "province_kill_request_total_operator_return_count": return_province_kill_requests_aggregates[
                                                                     'total_operator_return_count'] or 0,
            "province_kill_request_total_system_return_count": return_province_kill_requests_aggregates[
                                                                   'total_system_return_count'] or 0,
            "province_kill_request_total_quantity": province_kill_request_total_quantity,
            "province_kill_request_total_operator_return_quantity": province_kill_request_total_operator_return_quantity,
            "province_kill_request_total_system_return_quantity": province_kill_request_total_system_return_quantity,
            "province_kill_request_total_weight": province_kill_request_total_weight,
            "province_kill_request_total_operator_return_weight": province_kill_request_total_operator_return_weight,
            "province_kill_request_total_system_return_weight": province_kill_request_total_system_return_weight,
            "kill_house_request_total_count": return_kill_house_requests_aggregates['total_count'] or 0,
            "kill_house_request_total_non_receipt_count": return_kill_house_requests_aggregates[
                                                              'total_non_receipt_count'] or 0,
            "kill_house_request_total_system_return_count": return_kill_house_requests_aggregates[
                                                                'total_system_return_count'] or 0,
            "kill_house_request_total_quantity": return_kill_house_requests_aggregates['total_quantity'] or 0,
            "kill_house_request_total_non_receipt_quantity": return_kill_house_requests_aggregates[
                                                                 'total_non_receipt_quantity'] or 0,
            "kill_house_request_total_system_return_quantity": return_kill_house_requests_aggregates[
                                                                   'total_system_return_quantity'] or 0,
            "kill_house_request_total_weight": return_kill_house_requests_aggregates['total_weight'] or 0,
            "kill_house_request_total_non_receipt_weight": return_kill_house_requests_aggregates[
                                                               'total_non_receipt_weight'] or 0,
            "kill_house_request_total_system_return_weight": kill_house_request_total_system_return_weight,
            "total_return_weight_with_wage": total_return_weight_with_wage,
            "total_return_wage": total_return_weight_with_wage * province_live_wage_type_amount,
        }
        value_header_list = [
            result.get('province_kill_request_total_count') or 0,
            result.get('province_kill_request_total_operator_return_count') or 0,
            result.get('province_kill_request_total_system_return_count') or 0,
            result.get('province_kill_request_total_quantity') or 0,
            result.get('province_kill_request_total_operator_return_quantity') or 0,
            result.get('province_kill_request_total_system_return_quantity') or 0,
            result.get('province_kill_request_total_weight') or 0,
            result.get('province_kill_request_total_operator_return_weight') or 0,
            result.get('province_kill_request_total_system_return_weight') or 0,
            result.get('kill_house_request_total_count') or 0,
            result.get('kill_house_request_total_non_receipt_count') or 0,
            result.get('kill_house_request_total_system_return_count') or 0,
            result.get('kill_house_request_total_quantity') or 0,
            result.get('kill_house_request_total_non_receipt_quantity') or 0,
            result.get('kill_house_request_total_system_return_quantity') or 0,
            result.get('kill_house_request_total_weight') or 0,
            result.get('kill_house_request_total_non_receipt_weight') or 0,
            result.get('kill_house_request_total_system_return_weight') or 0,
            result.get('total_return_weight_with_wage') or 0,
            result.get('total_return_wage') or 0,

        ]
        create_value(worksheet, value_header_list, 4, 3, border_style='thin')

        summary_list = [
            'جمع کل==>',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',

        ]

        create_value(worksheet, summary_list, l + 1, 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 warehouse_archive_combined_excel(request):
    # Filters for list
    date1 = request.GET.get('date1')
    date2 = request.GET.get('date2')

    list_filters = {"trash": False}
    if date1:
        list_filters['date__date__gte'] = date1
        list_filters['date__date__lte'] = date2

    archives = WarehouseArchive.objects.filter(**list_filters).order_by('-create_date')
    list_data = WarehouseArchiveSerializer(archives, many=True).data

    value = request.GET.get('value')
    search = request.GET.get('search')
    if value and search == 'filter':
        if value != 'undefined' and str(value).strip():
            archives = archives.filter(
                build_query(WarehouseArchiveFilterSet.Meta.fields, value)
            )

    # Build dashboard queryset like TotalKillHouseWarehouseArchiveDashboardViewSet
    dash_filters = {"trash": False, "kill_house__isnull": False}
    if date1:
        dash_filters['create_date__date__gte'] = date1
        dash_filters['create_date__date__lte'] = date2
    dash_archives = WarehouseArchive.objects.filter(**dash_filters)
    kill_houses = KillHouse.objects.filter(id__in=dash_archives.values_list('kill_house__id', flat=True), trash=False)

    if search == 'filter' and value not in ("", None, 'undefined'):
        kh_list = []
        for item in [
            'name',
            'kill_house_operator__user__mobile',
            'kill_house_operator__user__fullname',
            'kill_house_operator__user__first_name',
            'kill_house_operator__user__last_name',
        ]:
            query = QueryDict('{0}__contains={1}'.format(item, value))
            ps = KillHouseFilterSet(data=query, queryset=kill_houses)
            if ps.filter().exists():
                kh_list = ps.filter()
        kill_houses = kh_list if kh_list else kill_houses.none()

    dash_data = TotalKillHouseWarehouseArchiveDashboardSerializer(
        kill_houses, many=True, context={'date1': date1, 'date2': date2}
    ).data

    # Headers
    excel_options = [
        'ردیف',
        'تاریخ بایگانی',
        'تاریخ انبار',
        'نام کشتارگاه',
        'شهر',
        'وزن (کیلوگرم)',
        'نوع سهمیه',
        'ثبت کننده',
        'شماره تماس',
        'توضیحات',
    ]

    header_list2 = [
        'ردیف',
        'نام کشتارگاه',
        'تعداد کل',
        'تعداد دولتی',
        'تعداد آزاد',
        'وزن کل (کیلوگرم)',
        'وزن دولتی (کیلوگرم)',
        'وزن آزاد (کیلوگرم)',
    ]

    # Workbook setup (single sheet)
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)

    # Title and date range (like sample)
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')
    red_font = Font(color="C00000", bold=True)
    if date1 and date2:
        try:
            d1 = datetime.datetime.strptime(str(date1), '%Y-%m-%d').date()
            d2 = datetime.datetime.strptime(str(date2), '%Y-%m-%d').date()
            from_date_1 = shamsi_date(d1)
            to_date_1 = shamsi_date(d2)
            worksheet['A3'] = f'از تاریخ:({from_date_1})    تا تاریخ:({to_date_1})'
        except Exception:
            pass

    # Render dashboard header (to the top area, columns start at 5 like sample)
    create_header(worksheet, header_list2, 5, 2, height=20.8, border_style='thin')

    # Compute where the list should start based on dashboard rows
    dash_count = len(dash_data) if dash_data else 0
    list_header_row = 6 + dash_count

    # Render list header with freeze and filter below dashboard block
    create_header_freez(worksheet, excel_options, 1, list_header_row, list_header_row + 1, 20)

    excel_description(worksheet, 'A1', f'مانده انبار کشتارگاه', size=11, color='red', row2='D1')

    worksheet['A3'].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 = 'A3:D3'
    worksheet.merge_cells(merge_range1)
    worksheet.merge_cells(merge_range)
    worksheet.merge_cells(merge_range2)
    worksheet['B1'].font = red_font
    worksheet['A3'].font = Font(size=11)
    worksheet['B2'].font = Font(size=10, bold=True, color="C00000")

    # Fill dashboard rows under header_list2
    # header_list2 is at row 5, so start values at row 6
    dash_row = 3
    for i, item in enumerate(dash_data, start=1):
        vals = [
            i,
            item.get('name', '-'),
            (item.get('info') or {}).get('total_count', 0) or 0,
            (item.get('info') or {}).get('total_governmental_count', 0) or 0,
            (item.get('info') or {}).get('total_free_count', 0) or 0,
            (item.get('info') or {}).get('total_weight', 0) or 0,
            (item.get('info') or {}).get('total_governmental_weight', 0) or 0,
            (item.get('info') or {}).get('total_free_weight', 0) or 0,
        ]
        create_value(worksheet, vals, dash_row, 5, border_style='thin')
        dash_row += 1

    # Fill list rows starting from computed list header (data starts at header_row + 1)
    l = list_header_row
    total_count = 0
    total_weight = 0
    governmental_count = 0
    governmental_weight = 0
    free_count = 0
    free_weight = 0

    for idx, arc in enumerate(list_data, start=1):
        l += 1
        cd = convert_str_to_date(arc.get('create_date'))
        create_date_sh = str(shamsi_date(cd, in_value=True)) if cd else '-'
        d = convert_str_to_date(arc.get('date'))
        date_sh = str(shamsi_date(d, in_value=True)) if d else '-'
        kh = arc.get('kill_house') or {}
        kh_name = kh.get('name', '-')
        city = kh.get('city', '-')
        quota_val = arc.get('quota')
        quota = 'آزاد' if quota_val == 'free' else ('دولتی' if quota_val == 'governmental' else (quota_val or '-'))
        weight_val = arc.get('weight') or 0

        # accumulate totals
        total_count += 1
        total_weight += weight_val or 0
        if quota_val == 'governmental':
            governmental_count += 1
            governmental_weight += weight_val or 0
        if quota_val == 'free':
            free_count += 1
            free_weight += weight_val or 0

        row_vals = [
            idx,
            create_date_sh,
            date_sh,
            kh_name,
            city,
            weight_val,
            quota,
            arc.get('registerer') or '-',
            arc.get('registerer_mobile') or '-',
            arc.get('description') or '-',
        ]
        create_value(worksheet, row_vals, l, 1, border_style='thin')

    # summary row after list
    summary_list = [
        'جمع کل==>',
        '',
        '',
        '',
        '',
        total_weight,
        '',
        '',
        '',
        '',
    ]

    create_value(worksheet, summary_list, l + 1, 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

