from datetime import datetime
from io import BytesIO
import json

from django.db.models import Sum
from django.http import QueryDict, HttpResponse
from openpyxl import Workbook
from openpyxl.styles import Alignment

from LiveStock.Cooperative.filterset import CooperativeFilterSet
from LiveStock.Jahad.filterset import LiveStockAllocationsFilterSet
from LiveStock.Rancher.helpers import update_one_rancher
from LiveStock.helpers import build_query
from LiveStock.models import LiveStockProduct, LiveStockAllocations, LiveStockRolseProduct, Cooperative, Rancher
from authentication.models import SystemUserProfile
from panel.ProvinceOperator.serializers import PosMachineTransactionsForLiveStockSerializer, \
    CooperativeForAllocationsReportSerializer, PosMachineTransactionsSerializer, \
    PosMachineTransactionsForLiveStockSerializerForExcel
from panel.convert_date import convert_to_shamsi
from panel.filterset import PosMachineTransactionsFilterSet
from panel.helper_excel import shamsi_date, create_header, excel_description, create_header_freez, create_value
from panel.models import PosMachineTransactions, ProductsTransactions


def allocation_live_stock_excel(request):
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    products = {
        "bran": "سبوس",
        "barley": "جو",
        "soy": "سویا",
        "corn": "ذرت",
    }
    name = products[request.GET.get('name')]

    product = LiveStockProduct.objects.filter(trash=False, name=name).first()
    if request.GET['role'] == 'LiveStockProvinceJahad':
        allocations = LiveStockAllocations.objects.filter(jahad__user=user, allocate_from="LiveStockProvinceJahad",
                                                          trash=False, product__parent_product=product).order_by(
            'id').exclude(allocate_to='LiveStockProvinceJahad')
        roles_new_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
                                                                 , parent_product=product).first()
    elif request.GET['role'] == 'Union':
        allocations = LiveStockAllocations.objects.filter(union__user=user, trash=False, allocate_from="Union",
                                                          product__parent_product=product).order_by('id')
        roles_new_product = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
                                                                 parent_product=product).first()
    else:
        allocations = LiveStockAllocations.objects.filter(cooperative__user=user, charge=False,
                                                          allocate_to="Cooperative",
                                                          trash=False, product__parent_product=product).order_by(
            'id')
        roles_new_product = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
                                                                 parent_product=product).first()

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

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

    value = request.GET.get('value')
    search = request.GET.get('search')
    if value and search == 'filter':
        if search != 'undefined' and search.strip():
            allocations = allocations.filter(
                build_query(LiveStockAllocationsFilterSet.Meta.fields, value)
            )
    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')
    if request.GET['role'] == "LiveStockProvinceJahad":

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

        ]
    else:
        header_list = [
            'ورودی به انبار',

            'تخصیص به تعاونی ها',
            'توزیع به دامداران',
            'مجموع  تخصیص و توزیع به دامداران',
            'مانده انبار',

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

    create_header(worksheet, header_list, 1, 3, height=20)

    excel_description(worksheet, 'B1', f'تخصیصات {name}', color='red', row2='C1')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)


    l = 5
    m = 1
    if allocations:
        for data in allocations:
            if data.allocate_from == 'LiveStockProvinceJahad':
                allocate_from="جهاد"
                allocate_from_full_name=data.jahad.user.fullname
            else:
                allocate_from = "اتحادیه"
                allocate_from_full_name=data.union.user.fullname
            if data.allocate_to == 'Union':
                allocate_to = "اتحادیه"
                allocate_to_full_name = data.union.user.fullname
            else:
                allocate_to = "تعاونی"
                allocate_to_full_name = data.cooperative.user.fullname

            list1 = [
                m,
                data.weight,
                f'{allocate_from}({allocate_from_full_name})',
                f'{allocate_to}({allocate_to_full_name})',
                allocate_from_full_name,
                str(shamsi_date(data.create_date)),
                data.place,
                data.description

            ]
            m += 1
            l += 1
            create_value(worksheet, list1, l + 1, 1, border_style='thin')

    if allocations:
        jahat_to_union = allocations.filter(jahad__isnull=False, allocate_to='Union')
        jahat_to_cooperative = allocations.filter(jahad__isnull=False, allocate_to='Cooperative')
        union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False, allocate_to='Cooperative')

        jahat_to_union_weight = jahat_to_union.aggregate(total=Sum('weight'))[
                                    'total'] or 0
        jahat_to_union_real_weight = jahat_to_union.aggregate(total=Sum('real_weight'))[
                                         'total'] or 0
        jahat_to_cooperative_weight = jahat_to_cooperative.aggregate(total=Sum('weight'))[
                                          'total'] or 0
        jahat_to_cooperative_real_weight = jahat_to_cooperative.aggregate(total=Sum('real_weight'))[
                                               'total'] or 0
        union_to_cooperative_weight = union_to_cooperative.aggregate(total=Sum('weight'))[
                                          'total'] or 0
        union_to_cooperative_real_weight = union_to_cooperative.aggregate(total=Sum('real_weight'))[
                                               'total'] or 0
        roles_product = LiveStockRolseProduct.objects.filter(trash=False)
        union_remain = roles_product.filter(union__isnull=False)
        cooperative_remain = roles_product.filter(cooperative__isnull=False)
        role_product_union = union_remain.aggregate(total=Sum('total_remain_weight'))[
                                 'total'] or 0
        role_product_cooperative = cooperative_remain.aggregate(total=Sum('total_remain_weight'))[
                                       'total'] or 0
        role_product_cooperative_receipt_weight = cooperative_remain.aggregate(total=Sum('total_receipt_weight'))[
                                                      'total'] or 0
        if request.GET['role'] == 'Union':
            value_header_list = [

            roles_new_product.total_weight,

             roles_new_product.total_allocated_weight,
                0,
                0 +  roles_new_product.total_allocated_weight,
             roles_new_product.total_remain_weight,

            ]

        else:
            value_header_list = [

                roles_new_product.total_weight,
                jahat_to_union_weight,
                jahat_to_cooperative_weight,

                roles_new_product.total_allocated_weight,
                union_to_cooperative_weight,
                jahat_to_cooperative_weight + union_to_cooperative_weight,
                0,
                0,
                roles_new_product.total_remain_weight,
                role_product_union,
                role_product_cooperative,

            ]
        create_value(worksheet, value_header_list, 4, 1)

    weight = allocations.aggregate(total=Sum('weight'))['total'] or 0


    list2 = [
        'مجموع==>',
        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=" تخصیصات {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def warehouse_live_stock_excel(request):
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    products = {
        "bran": "سبوس",
        "barley": "جو",
        "soy": "سویا",
        "corn": "ذرت",
    }
    name = products[request.GET.get('name')]

    product = LiveStockProduct.objects.filter(trash=False, name=name).first()
    if request.GET['role'] == 'LiveStockProvinceJahad':
        allocations = LiveStockAllocations.objects.filter(jahad__user=user, trash=False,
                                                          product__parent_product=product,
                                                          allocate_to='LiveStockProvinceJahad').order_by('id')
        roles_new_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
                                                                 , parent_product=product).first()
    elif request.GET['role'] == 'Union':
        allocations = LiveStockAllocations.objects.filter(allocate_from='LiveStockProvinceJahad', union__user=user,
                                                          trash=False, product__parent_product=product).order_by(
            'id')
        roles_new_product = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
                                                                 parent_product=product).first()
    else:
        allocations = LiveStockAllocations.objects.filter(
            charge=True, cooperative__user=user,
            trash=False, product__parent_product=product).order_by('id')
        roles_new_product = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
                                                                 parent_product=product).first()

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

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

    value = request.GET.get('value')
    search = request.GET.get('search')
    if value and search == 'filter':
        if search != 'undefined' and search.strip():
            allocations = allocations.filter(
                build_query(LiveStockAllocationsFilterSet.Meta.fields, value)
            )
    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')
    if request.GET['role'] == "LiveStockProvinceJahad":

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

        ]
    elif request.GET['role'] == "Union":
        header_list = [
            'ورودی به انبار',

            'تخصیص به تعاونی ها',
            'توزیع به دامداران',
            'مجموع  تخصیص و توزیع به دامداران',
            'مانده انبار',

        ]
    else:
        header_list = [
            'سهمیه دریافتی',
            'ورودی به انبار',

            'توزیع به دامداران',
            'مانده انبار',

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

    create_header(worksheet, header_list, 1, 3, height=20)

    excel_description(worksheet, 'B1', f'انبار {name}', color='red', row2='C1')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)


    l = 5
    m = 1
    if allocations:
        for data in allocations:
            if data.allocate_from == 'LiveStockProvinceJahad':
                allocate_from="جهاد"
                allocate_from_full_name=data.jahad.user.fullname
            else:
                allocate_from = "اتحادیه"
                allocate_from_full_name=data.union.user.fullname
            if data.allocate_to == 'Union':
                allocate_to = "اتحادیه"
                allocate_to_full_name = data.union.user.fullname
            elif data.allocate_to == 'LiveStockProvinceJahad':
                allocate_to="جهاد"
                allocate_to_full_name=data.jahad.user.fullname
            else:
                allocate_to = "تعاونی"
                allocate_to_full_name = data.cooperative.user.fullname

            list1 = [
                m,
                data.weight,
                f'{allocate_from}({allocate_from_full_name})',
                f'{allocate_to}({allocate_to_full_name})',
                allocate_from_full_name,
                str(shamsi_date(data.create_date)),
                data.place,
                data.description

            ]
            m += 1
            l += 1
            create_value(worksheet, list1, l + 1, 1, border_style='thin')

    if allocations:
        jahat_to_union = allocations.filter(jahad__isnull=False, allocate_to='Union')
        union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False, allocate_to='Cooperative')
        jahat_to_cooperative_filter = LiveStockAllocations.objects.filter(jahad__isnull=False, allocate_to='Cooperative')
        jahat_to_cooperative = jahat_to_cooperative_filter.filter(jahad__isnull=False, allocate_to='Cooperative')

        jahat_to_union_weight = jahat_to_union.aggregate(total=Sum('weight'))[
                                    'total'] or 0
        jahat_to_union_real_weight = jahat_to_union.aggregate(total=Sum('real_weight'))[
                                         'total'] or 0
        jahat_to_cooperative_weight = jahat_to_cooperative.aggregate(total=Sum('weight'))[
                                          'total'] or 0
        jahat_to_cooperative_real_weight = jahat_to_cooperative.aggregate(total=Sum('real_weight'))[
                                               'total'] or 0
        union_to_cooperative_weight = union_to_cooperative.aggregate(total=Sum('weight'))[
                                          'total'] or 0
        union_to_cooperative_real_weight = union_to_cooperative.aggregate(total=Sum('real_weight'))[
                                               'total'] or 0
        roles_product = LiveStockRolseProduct.objects.filter(trash=False)
        union_remain = roles_product.filter(union__isnull=False)
        cooperative_remain = roles_product.filter(cooperative__isnull=False)
        role_product_union = union_remain.aggregate(total=Sum('total_remain_weight'))[
                                 'total'] or 0
        role_product_cooperative = cooperative_remain.aggregate(total=Sum('total_remain_weight'))[
                                       'total'] or 0
        role_product_cooperative_receipt_weight = cooperative_remain.aggregate(total=Sum('total_receipt_weight'))[
                                                      'total'] or 0
        if request.GET['role'] == 'Union':
            value_header_list = [

            roles_new_product.total_weight,

             roles_new_product.total_allocated_weight,
                0,
                0 +  roles_new_product.total_allocated_weight,
             roles_new_product.total_remain_weight,

            ]
        if request.GET['role'] == 'Cooperative':
            value_header_list = [
                role_product_cooperative_receipt_weight,
                roles_new_product.total_weight,

                0,

                roles_new_product.total_remain_weight,

            ]
        else:
            value_header_list = [

                roles_new_product.total_weight,
                jahat_to_union_weight,
                jahat_to_cooperative_weight,

                roles_new_product.total_allocated_weight,
                union_to_cooperative_weight,
                jahat_to_cooperative_weight + union_to_cooperative_weight,
                0,
                0,
                roles_new_product.total_remain_weight,
                role_product_union,
                role_product_cooperative,

            ]
        create_value(worksheet, value_header_list, 4, 1)

    weight = allocations.aggregate(total=Sum('weight'))['total'] or 0


    list2 = [
        'مجموع==>',
        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="انبار {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def live_stock_transaction_excel(request):
    products = {
        "bran": "سبوس",
        "barley": "جو",
        "soy": "سویا",
        "corn": "ذرت",
    }
    name = products[request.GET.get('name')]
    filterset_class = PosMachineTransactionsFilterSet
    filterset_fields = [
        'mobile',
        'natcode',
        'fullname',
    ]
    user = SystemUserProfile.objects.get(key=request.GET['key'], trash=False)
    date1 = request.GET.get('date1')
    date2 = request.GET.get('date2')
    role = request.GET.get('role')
    filters = {}





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


    ]
    header_list = [
        'تعداد تراکنش ها',
        'مجموع دام سنگین',
        'مجموع دام سبک',

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

    ]
    sheet_names=['تراکنش های موفق']
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)

    for name in sheet_names:
        sheet_name = 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')
        if sheet_name == 'تراکنش های موفق':
            cooperative_key = request.GET.get('cooperative_key')
            date1 = request.GET.get('date1')
            date2 = request.GET.get('date2')
            role = request.GET.get('role')
            state = request.GET.get('state')
            filters = {}
            products = {
                "bran": "سبوس",
                "barley": "جو",
                "soy": "سویا",
                "corn": "ذرت",
                "sheep_concentrate": "کنسانتره گوسفندی",
                "high_cow_concentrate": "کنسانتره گاو شیری پرتولید",
                "medium_cow_concentrate": "کنسانتره گاو شیری متوسط",
                "fattening_calf_concentrate": "کنسانتره گوساله پرواری",
            }
            product = products[request.GET.get('name')]

            filters['paid'] = True


            cooperative_key = request.GET.get('cooperative_key')
            if role in ('LiveStockProvinceJahad', 'Union'):
                if product:
                    product_transactions = ProductsTransactions.objects.filter(
                        live_stack_products__parent_product__name=product, trash=False).values_list('transaction__id',
                                                                                                    flat=True)
                    transactions = PosMachineTransactions.objects.filter(id__in=product_transactions, trash=False,
                                                                         live_stock=True).order_by('-date')

                else:
                    transactions = PosMachineTransactions.objects.filter(trash=False, live_stock=True).order_by('-date')


            elif cooperative_key:
                cooperative = Cooperative.objects.get(key=cooperative_key)
                if product:
                    product_transactions = ProductsTransactions.objects.filter(
                        live_stack_products__parent_product__name=product, live_stack_products__cooperative=cooperative,
                        trash=False).values_list('transaction__id',
                                                 flat=True)
                    transactions = PosMachineTransactions.objects.filter(id__in=product_transactions, trash=False,
                                                                         live_stock=True).order_by('-date')
                else:

                    transactions = PosMachineTransactions.objects.filter(pos__cooperative=cooperative, trash=False,
                                                                         live_stock=True).order_by('-date')



            else:
                cooperative = Cooperative.objects.get(user=user)
                if product:
                    product_transactions = ProductsTransactions.objects.filter(
                        live_stack_products__parent_product__name=product, live_stack_products__cooperative=cooperative,
                        trash=False).values_list('transaction__id',
                                                 flat=True)
                    transactions = PosMachineTransactions.objects.filter(id__in=product_transactions, trash=False,
                                                                         live_stock=True).order_by('-date')

                else:

                    transactions = PosMachineTransactions.objects.filter(pos__cooperative=cooperative, trash=False,
                                                                         live_stock=True).order_by('-date')

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

                filters['date__date__gte'] = date1
                filters['date__date__lte'] = date2

            transactions = transactions.filter(**filters).order_by('-date')
            if 'search' in request.GET and 'value' in request.GET:
                transactions_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=transactions
                            )
                            ).filter():
                                ps = filterset_class(data=query, queryset=transactions)
                                transactions_list = ps.filter()
                        transactions = [] if len(transactions_list) == 0 else transactions_list

            transactions = transactions.filter(**filters).order_by('-date')
            serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data

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

            create_header(worksheet, header_list, 5, 3, height=20)

            excel_description(worksheet, 'B1', f'تراکنش های موفق محصول {name}', color='red', row2='C1')

            create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)


            l = 5
            m = 1
            if serializer:
                for data in serializer:
                    date = datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S.%f')
                    shares=data.get('shares') or {}
                    additional = json.loads(data['additional']) if data.get('additional', '').strip() else {}
                    if additional.get('isTaavoni'):
                        tavanoni='تعاونی' if additional['isTaavoni'] == True else 'کارخانه'
                    else:
                        tavanoni='-'
                    list1 = [
                        m,
                        str(convert_to_shamsi(datetime=date)),
                        data['fullname'],
                        data['natcode'],
                        data['mobile'],
                        data['pos']['cooperative']['name'] + '('+data['pos']['cooperative']['user']['fullname'] +')',
                        data['pos']['cooperative']['user']['mobile'],
                        data['result'],
                        tavanoni,
                        data['products'][0]['name'],
                        data['natcode'],
                        additional.get('cur_heavy', 0),
                        additional.get('cur_light', 0),
                        data['products'][0]['cur_weight'],
                        data['price'],
                        shares.get('totalCooperativePrice') or 0,
                        shares.get('totalUnionPrice') or 0,
                        shares.get('totalCompanyPrice') or 0,
                    ]
                    m += 1
                    l += 1
                    create_value(worksheet, list1, l + 1, 1, border_style='thin')

                cur_heavy = sum(json.loads(data['additional']).get('cur_heavy', 0) for data in serializer)
                cur_light = sum(json.loads(data['additional']).get('cur_light', 0) for data in serializer)

                cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
                price = sum(data['price'] for data in serializer)
                cooperative_price = sum(data.get('shares', {}).get('totalCooperativePrice') or 0 for data in serializer)
                union_price = sum(data.get('shares', {}).get('totalUnionPrice') or 0 for data in serializer)
                total_company_price = sum(data.get('shares', {}).get('totalCompanyPrice') or 0 for data in serializer)

                value_header_list = [
                    len(transactions),
                    cur_heavy,
                    cur_light,
                    cur_weight,
                    price,
                    cooperative_price,
                    union_price,
                    total_company_price,

                ]
                create_value(worksheet, value_header_list, 4, 5)



                list2 = [
                    'مجموع==>',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    cur_heavy,
                    cur_light,
                    cur_weight,
                    price,
                    cooperative_price,
                    union_price,
                    total_company_price,



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

        # else:
        #     cooperative_key = request.GET.get('cooperative_key')
        #     if role in ('LiveStockProvinceJahad', 'Union'):
        #         transactions = PosMachineTransactions.objects.filter(trash=False, live_stock=True).order_by('-date')
        #     elif cooperative_key:
        #         cooperative = Cooperative.objects.get(key=cooperative_key)
        #         transactions = PosMachineTransactions.objects.filter(pos__cooperative=cooperative, trash=False,
        #                                                              live_stock=True).order_by('-date')
        #
        #
        #     else:
        #         cooperative = Cooperative.objects.get(user=user)
        #         transactions = PosMachineTransactions.objects.filter(pos__cooperative=cooperative, trash=False,
        #                                                              live_stock=True).order_by('-date')
        #
        #     if date1 and date2:
        #         date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        #         date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        #
        #         filters['date__date__gte'] = date1
        #         filters['date__date__lte'] = date2
        #
        #     if 'search' in request.GET and 'value' in request.GET:
        #         transactions_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=transactions
        #                     )
        #                     ).filter():
        #                         ps = filterset_class(data=query, queryset=transactions)
        #                         transactions_list = ps.filter()
        #                 transactions = [] if len(transactions_list) == 0 else transactions_list
        #     transactions = transactions.filter(**filters, paid=False).order_by('-date')
        #     serializer = PosMachineTransactionsForLiveStockSerializerForExcel(transactions, many=True).data
        #
        #     if 'date1' in request.GET:
        #         date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        #         date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        #         from_date1 = shamsi_date(date1)
        #         to_date1 = shamsi_date(date2)
        #         excel_description(worksheet, 'B2', f'از تاریخ {from_date1} تا {to_date1}', color='red', row2='D3')
        #
        #     create_header(worksheet, header_list, 5, 3, height=20)
        #
        #     excel_description(worksheet, 'B1', f'تراکنش های ناموفق', color='red', row2='C1')
        #
        #     create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)
        #
        #     l = 5
        #     m = 1
        #     if serializer:
        #         for data in serializer:
        #             date = datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S.%f')
        #
        #             additional = json.loads(data['additional'])
        #             if additional.get('isTaavoni'):
        #                 tavanoni = 'تعاونی' if additional['isTaavoni'] == True else 'کارخانه'
        #             else:
        #                 tavanoni = '-'
        #             list1 = [
        #                 m,
        #                 str(convert_to_shamsi(datetime=date)),
        #                 data['fullname'],
        #                 data['natcode'],
        #                 data['mobile'],
        #                 data['pos']['cooperative']['name'] + '(' + data['pos']['cooperative']['user']['fullname'] + ')',
        #                 data['pos']['cooperative']['user']['mobile'],
        #                 data['result'],
        #                 tavanoni,
        #                 data['products'][0]['name'],
        #                 data['natcode'],
        #                 additional.get('cur_heavy',0),
        #                 additional.get('cur_light',0),
        #                 data['products'][0]['cur_weight'],
        #                 data['price'],
        #                 additional.get('cooperative_price',0),
        #                 additional.get('union_price',0),
        #             ]
        #             m += 1
        #             l += 1
        #             create_value(worksheet, list1, l + 1, 1, border_style='thin')
        #
        #         cur_heavy = sum(json.loads(data['additional']).get('cur_heavy', 0) for data in serializer)
        #         cur_light = sum(json.loads(data['additional']).get('cur_light', 0) for data in serializer)
        #         cooperative_price = sum(
        #             json.loads(data['additional']).get('cooperative_price', 0) for data in serializer)
        #         union_price = sum(json.loads(data['additional']).get('union_price', 0) for data in serializer)
        #         cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
        #         price = sum(data['price'] for data in serializer)
        #
        #         value_header_list = [
        #             len(transactions),
        #             cur_heavy,
        #             cur_light,
        #             cur_weight,
        #             price,
        #             cooperative_price,
        #             union_price,
        #
        #         ]
        #         create_value(worksheet, value_header_list, 4, 5)
        #
        #         list2 = [
        #             'مجموع==>',
        #             '',
        #             '',
        #             '',
        #             '',
        #             '',
        #             '',
        #             '',
        #             '',
        #             '',
        #             '',
        #             cur_heavy,
        #             cur_light,
        #             cur_weight,
        #             price,
        #             cooperative_price,
        #             union_price,
        #
        #         ]
        #         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="تراکنش های محصول {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def cooperative_warehouse_excel(request):
    products = {
        "bran": "سبوس",
        "barley": "جو",
        "soy": "سویا",
        "corn": "ذرت",
    }
    name = products[request.GET.get('name')]
    cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
    value = request.GET.get('value')
    search = request.GET.get('search')
    if value and search == 'filter':
        if search != 'undefined' and search.strip():
            cooperatives = cooperatives.filter(
                build_query(CooperativeFilterSet.Meta.fields, search)
            )

    serializer = CooperativeForAllocationsReportSerializer(cooperatives, many=True,context={'request':request}).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')

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

    ]

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

    create_header(worksheet, header_list, 3, 3, height=20)

    excel_description(worksheet, 'B1', f'گزارش فروش {name}', color='red', row2='C1')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)


    l = 5
    m = 1
    if serializer:
        for data in serializer:


            list1 = [
                m,
                data['name'],
                data['user']['fullname'] if data['user']['fullname'] else '-',
                data['user']['province_name'] if data['user']['province_name'] else '-',
                data['user']['city_name'] if data['user']['city_name'] else '-',
                data['user']['mobile'] if data['user']['mobile'] else '-',
                data['user']['national_id'] if data['user']['national_id'] else '-',
                data['info']['total_receipt_weight'] if data['info']['total_receipt_weight'] else '-',
                data['info']['total_weight'] if data['info']['total_weight'] else '-',
                data['info']['total_allocated_weight'] if data['info']['total_allocated_weight'] else '-',
                data['info']['total_remain_weight'] if data['info']['total_remain_weight'] else '-',
                data['info']['transactions'] if data['info']['transactions'] else '-',
                data['info']['total_transactions_price'] if data['info']['total_transactions_price'] else '-',
                data['info']['total_transactions_weight'] if data['info']['total_transactions_weight'] else '-',


            ]
            m += 1
            l += 1
            create_value(worksheet, list1, l + 1, 1, border_style='thin')

    if serializer:

        total_receipt_weight = sum(
            item['info'].get('total_receipt_weight', 0) for item in serializer)
        total_weight = sum(
            item['info'].get('total_weight', 0) for item in serializer)
        total_allocated_weight = sum(
            item['info'].get('total_allocated_weight', 0) for item in serializer)
        total_remain_weight = sum(
            item['info'].get('total_remain_weight', 0) for item in serializer)
        transactions = sum(
            item['info'].get('transactions', 0) for item in serializer)
        total_transactions_price = sum(
            item['info'].get('total_transactions_price', 0) for item in serializer)
        total_transactions_weight = sum(
            item['info'].get('total_transactions_weight', 0) for item in serializer)
        value_header_list = [

            total_receipt_weight,
            total_weight,
            total_allocated_weight,
            total_remain_weight,
            transactions,
            total_transactions_price,
            total_transactions_weight,



        ]
        create_value(worksheet, value_header_list, 4, 3)


        list2 = [
            'مجموع==>',
            '',
            '',
            '',
            '',
            '',
            '',
            total_receipt_weight,
            total_weight,
            total_allocated_weight,
            total_remain_weight,
            transactions,
            total_transactions_price,
            total_transactions_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="گزارش فروش {name}.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response


def safe_get_additional(data):
    additional_str = data.get('additional')
    if additional_str in [None, '', 'null', 'undefined']:
        return {}
    try:
        return json.loads(additional_str)
    except (json.JSONDecodeError, TypeError):
        return {}


def management_live_stock_excel(request):
    sheet_names=['اطلاعات کلی توزیع تعاونی ها']
    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    workbook.remove(worksheet)

    for name in sheet_names[:1]:
        sheet_name = 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')
        if sheet_name == 'اطلاعات کلی توزیع تعاونی ها':
            cooperatives = Cooperative.objects.filter(trash=False).order_by('id')

            serializer = CooperativeForAllocationsReportSerializer(cooperatives, many=True).data
            excel_options = [
                'ردیف',
                'نام تعاونی',
                'کاربر',
                'استان',
                'شهر',
                'موبایل',
                'کد ملی',
                'سهمیه دریافتی',
                'وزن تحویلی',
                'وزن فروش رفته',
                'مانده انبار',
                'تعداد تراکنش ها',
                'جمع تراکنش ها',
                'وزن کل تراکنش ها',

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

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

            ]

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

            create_header(worksheet, header_list, 3, 3, height=20)

            excel_description(worksheet, 'A1', f'اطلاعات کلی توزیع تعاونی ها', color='red', row2='C1')

            create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)

            l = 5
            m = 1
            if serializer:
                for data in serializer:
                    if data['info']['transactions'] >0 and data['name'] not in sheet_names:
                        sheet_names.append(data['name'])
                    list1 = [
                        m,
                        data['name'],
                        data['user']['fullname'],
                        data['user']['province_name'],
                        data['user']['city_name'],
                        data['user']['mobile'],
                        data['user']['national_id'],
                        data['info']['total_receipt_weight'],
                        data['info']['total_weight'],
                        data['info']['total_allocated_weight'],
                        data['info']['total_remain_weight'],
                        data['info']['transactions'],
                        data['info']['total_transactions_price'],
                        data['info']['total_transactions_weight'],

                    ]
                    m += 1
                    l += 1
                    create_value(worksheet, list1, l + 1, 1, border_style='thin')

            if serializer:
                total_receipt_weight = sum(
                    item['info'].get('total_receipt_weight', 0) for item in serializer)
                total_weight = sum(
                    item['info'].get('total_weight', 0) for item in serializer)
                total_allocated_weight = sum(
                    item['info'].get('total_allocated_weight', 0) for item in serializer)
                total_remain_weight = sum(
                    item['info'].get('total_remain_weight', 0) for item in serializer)
                transactions = sum(
                    item['info'].get('transactions', 0) for item in serializer)
                total_transactions_price = sum(
                    item['info'].get('total_transactions_price', 0) for item in serializer)
                total_transactions_weight = sum(
                    item['info'].get('total_transactions_weight', 0) for item in serializer)
                value_header_list = [

                    total_receipt_weight,
                    total_weight,
                    total_allocated_weight,
                    total_remain_weight,
                    transactions,
                    total_transactions_price,
                    total_transactions_weight,

                ]
                create_value(worksheet, value_header_list, 4, 3)

                list2 = [
                    'مجموع==>',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    total_receipt_weight,
                    total_weight,
                    total_allocated_weight,
                    total_remain_weight,
                    transactions,
                    total_transactions_price,
                    total_transactions_weight,

                ]
                create_value(worksheet, list2, l + 3, 1, color='green')
        # elif sheet_name == 'اطلاعات کلی خریداران':
        #      cell = worksheet.cell(row=1, column=1)
        #      cell.alignment = Alignment(horizontal='center', vertical='center')
        #      excel_options = [
        #             'ردیف',
        #             'دامدار',
        #             'کدملی دامدار',
        #             'شهر',
        #             'تعداد تراکنش ها',
        #             'مجموع دام سنگین',
        #             'مجموع دام سبک',
        #
        #             'مجموع وزن(کیلوگرم)',
        #             'مبلغ تراکنش(ریال)',
        #             'سهم تعاونی(ریال)',
        #             'سهم اتحادیه(ریال)',
        #
        #         ]
        #      header_list = [
        #         'تعداد دامداران',
        #         'تعداد تراکنش ها',
        #         'مجموع دام سنگین',
        #         'مجموع دام سبک',
        #
        #         'مجموع وزن(کیلوگرم)',
        #         'مبلغ تراکنش(ریال)',
        #         'سهم تعاونی(ریال)',
        #         'سهم اتحادیه(ریال)',
        #
        #      ]
        #      ransactions = PosMachineTransactions.objects.filter(trash=False,
        #                                                          live_stock=True, paid=True,
        #                                                          ).order_by('id')
        #      natcpdes = ransactions.values_list('natcode',flat=True).distinct()
        #
        #      ranchers=Rancher.objects.filter(trash=False,national_id__in=natcpdes).only('name','national_id')
        #      print(len(ranchers))
        #      if 'date1' in request.GET:
        #          date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
        #          date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
        #          from_date1 = shamsi_date(date1)
        #          to_date1 = shamsi_date(date2)
        #          excel_description(worksheet, 'B2', f'از تاریخ {from_date1} تا {to_date1}', color='red', row2='D3')
        #
        #      create_header(worksheet, header_list, 5, 3, height=20)
        #
        #      excel_description(worksheet, 'A1', f' تراکنش های موفق {name}', color='red', row2='D1')
        #
        #      create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)
        #
        #      l = 5
        #      m = 1
        #      if ranchers:
        #          for rancher in ranchers:
        #              transactions = ransactions.filter(natcode=rancher.national_id).order_by('id')
        #
        #              serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data
        #              cur_heavy = sum(json.loads(data['additional']).get('cur_heavy', 0) for data in serializer)
        #              cur_light = sum(json.loads(data['additional']).get('cur_light', 0) for data in serializer)
        #              cooperative_price = sum(
        #                  json.loads(data['additional']).get('cooperative_price', 0) for data in serializer)
        #              union_price = sum(json.loads(data['additional']).get('union_price', 0) for data in serializer)
        #              cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
        #              price = sum(data['price'] for data in serializer)
        #              list1 = [
        #                  m,
        #                  rancher.name,
        #                  rancher.national_id,
        #                  len(transactions),
        #                  cur_heavy,
        #                  cur_light,
        #                  cur_weight,
        #                  price,
        #                  cooperative_price,
        #                  union_price,
        #
        #              ]
        #              m += 1
        #              l += 1
        #              create_value(worksheet, list1, l + 1, 1, border_style='thin')
        #          transactions = ransactions
        #
        #          serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data
        #          cur_heavy = sum(json.loads(data['additional']).get('cur_heavy', 0) for data in serializer)
        #          cur_light = sum(json.loads(data['additional']).get('cur_light', 0) for data in serializer)
        #          cooperative_price = sum(
        #              json.loads(data['additional']).get('cooperative_price', 0) for data in serializer)
        #          union_price = sum(json.loads(data['additional']).get('union_price', 0) for data in serializer)
        #          cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
        #          price = sum(data['price'] for data in serializer)
        #
        #          value_header_list = [
        #              len(natcpdes),
        #              len(transactions),
        #              cur_heavy,
        #              cur_light,
        #              cur_weight,
        #              price,
        #              cooperative_price,
        #              union_price,
        #
        #          ]
        #          create_value(worksheet, value_header_list, 4, 5)
        #
        #          list2 = [
        #              'مجموع==>',
        #              '',
        #              '',
        #              '',
        #              len(transactions),
        #              cur_heavy,
        #              cur_light,
        #              cur_weight,
        #              price,
        #              cooperative_price,
        #              union_price,
        #
        #          ]
        #          create_value(worksheet, list2, l + 3, 1, color='green')
    for name in sheet_names[1:]:
        last_part = name.rsplit(' ', 3)[-3:]
        new_name = ' '.join(last_part)
        sheet_name = new_name
        worksheet = workbook.create_sheet(sheet_name)
        worksheet.sheet_view.rightToLeft = True
        worksheet.insert_rows(1)
        excel_options = [
            'ردیف',
            'تاریخ',
            'خریدار',
            'کد ملی خریدار',
            'موبایل خریدار',
            'فروشنده',
            'تلفن فروشنده',
            'وضعیت',
            'محل تحویل',
            'کالا',
            'کد ملی فروشنده',
            'دام سنگین',
            'دام سبک',
            'وزن(کیلوگرم)',
            'مبلغ تراکنش(ریال)',
            'سهم تعاونی(ریال)',
            'سهم اتحادیه(ریال)',

        ]
        header_list = [
            'تعداد تراکنش ها',
            'مجموع دام سنگین',
            'مجموع دام سبک',

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

        ]
        cooperative = Cooperative.objects.get(name=name)
        transactions = PosMachineTransactions.objects.filter(pos__cooperative=cooperative, trash=False,
                                                             live_stock=True,paid=True).order_by('-date')



        serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data

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

        create_header(worksheet, header_list, 5, 3, height=20)

        excel_description(worksheet, 'A1', f' تراکنش های موفق {name}', color='red', row2='D1')

        create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)

        l = 5
        m = 1
        if serializer:
            for data in serializer:
                date = datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S.%f')

                additional_str = data.get('additional')
                if additional_str in [None, '', 'null', 'undefined']:
                    additional = {}
                else:
                    try:
                        additional = json.loads(additional_str)
                    except (json.JSONDecodeError, TypeError):
                        additional = {}

                if additional.get('isTaavoni'):
                    tavanoni = 'تعاونی' if additional['isTaavoni'] == True else 'کارخانه'
                else:
                    tavanoni = '-'
                list1 = [
                    m,
                    str(convert_to_shamsi(datetime=date)),
                    data['fullname'],
                    data['natcode'],
                    data['mobile'],
                    data['pos']['cooperative']['name'] + '(' + data['pos']['cooperative']['user']['fullname'] + ')',
                    data['pos']['cooperative']['user']['mobile'],
                    data['result'],
                    tavanoni,
                    data['products'][0]['name'],
                    data['natcode'],
                    additional.get('cur_heavy', 0),
                    additional.get('cur_light', 0),
                    data['products'][0]['cur_weight'],
                    data['price'],
                    additional.get('cooperative_price', 0),
                    additional.get('union_price', 0),
                ]
                m += 1
                l += 1
                create_value(worksheet, list1, l + 1, 1, border_style='thin')

            cur_heavy = sum(safe_get_additional(data).get('cur_heavy', 0) for data in serializer)
            cur_light = sum(safe_get_additional(data).get('cur_light', 0) for data in serializer)
            cooperative_price = sum(safe_get_additional(data).get('cooperative_price', 0) for data in serializer)
            union_price = sum(safe_get_additional(data).get('union_price', 0) for data in serializer)
            cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
            price = sum(data['price'] for data in serializer)

            value_header_list = [
                len(transactions),
                cur_heavy,
                cur_light,
                cur_weight,
                price,
                cooperative_price,
                union_price,

            ]
            create_value(worksheet, value_header_list, 4, 5)

            list2 = [
                'مجموع==>',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                cur_heavy,
                cur_light,
                cur_weight,
                price,
                cooperative_price,
                union_price,

            ]
            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 fix_rancher(request):
     ransactions = PosMachineTransactions.objects.filter(trash=False,
                                                             live_stock=True, paid=True,
                                                             ).values_list('natcode',flat=True).distinct()

     ranchers=Rancher.objects.filter(trash=False,national_id__in=ransactions,has_script=False)

     for r in ranchers:
         update_one_rancher(r)

     return HttpResponse('ok')


def rancher_management(request):

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


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

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

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

    ]
    ransactions = PosMachineTransactions.objects.filter(trash=False,
                                                     live_stock=True, paid=True,
                                                     ).order_by('id')
    natcpdes = ransactions.values_list('natcode',flat=True).distinct()

    ranchers=Rancher.objects.filter(trash=False,national_id__in=natcpdes,has_script=True).only('name','national_id',
                                                                                                  'heavy_livestock','light_livestock','city','mobile')


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

    create_header(worksheet, header_list, 5, 3, height=20)

    excel_description(worksheet, 'A1', f'دامداران مغایرت دار', color='red', row2='D1')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)

    l = 5
    m = 1
    if ranchers:
     for rancher in ranchers:
         transactions = ransactions.filter(natcode=rancher.national_id).order_by('id')

         serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data
         cur_heavy = sum(safe_get_additional(data).get('cur_heavy', 0) for data in serializer)
         cur_light = sum(safe_get_additional(data).get('cur_light', 0) for data in serializer)
         cooperative_price = sum(safe_get_additional(data).get('cooperative_price', 0) for data in serializer)
         union_price = sum(safe_get_additional(data).get('union_price', 0) for data in serializer)
         cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
         price = sum(data['price'] for data in serializer)

         cooperative_list_name = list({data['pos']['cooperative']['name'] for data in serializer})
         cooperative_list_mobile = list({data['pos']['cooperative']['user']['mobile'] for data in serializer})
         natcode_list = list({data['natcode'] for data in serializer})

         cooperative_names_str = ' / '.join(cooperative_list_name) if cooperative_list_name else ''
         cooperative_mobiles_str = ' / '.join(cooperative_list_mobile) if cooperative_list_mobile else ''
         natcode_list_str = ' / '.join(natcode_list) if natcode_list else ''

         date_list=[]
         for data in serializer:
             date = datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S.%f')
             date_list.append(str(convert_to_shamsi(datetime=date)))
         date_str = ' / '.join(date_list) if date_list else ''
         type_rancher='روستایی' if rancher.type=='rural' else 'صنعتی'
         list1 = [
             m,
             rancher.name,
             type_rancher,
             rancher.national_id,
             rancher.mobile,
             rancher.city,
             rancher.heavy_livestock,
             rancher.light_livestock,
             rancher.weight_quota_heavy,
             rancher.weight_quota_light,
             cooperative_names_str,
             cooperative_mobiles_str,
             natcode_list_str,
             len(transactions),
             date_str,
             cur_heavy,
             cur_light,

             cur_weight,

             price,
             cooperative_price,
             union_price,

         ]
         l += 1
         m += 1

         create_value(worksheet, list1, l + 1, 1, border_style='thin')
     transactions = ransactions

     serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data
     cur_heavy = sum(safe_get_additional(data).get('cur_heavy', 0) for data in serializer)
     cur_light = sum(safe_get_additional(data).get('cur_light', 0) for data in serializer)
     cooperative_price = sum(safe_get_additional(data).get('cooperative_price', 0) for data in serializer)
     union_price = sum(safe_get_additional(data).get('union_price', 0) for data in serializer)
     cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
     price = sum(data['price'] for data in serializer)
     heavy_livestock = ranchers.aggregate(total=Sum('heavy_livestock'))[
                            'total'] or 0
     light_livestock = ranchers.aggregate(total=Sum('light_livestock'))[
                            'total'] or 0
     weight_quota_light = ranchers.aggregate(total=Sum('weight_quota_light'))[
                            'total'] or 0
     weight_quota_heavy = ranchers.aggregate(total=Sum('weight_quota_heavy'))[
                            'total'] or 0
     value_header_list = [
         len(natcpdes),
         len(transactions),
         cur_heavy,
         cur_light,
         heavy_livestock,
         light_livestock,
         weight_quota_heavy,
         weight_quota_light,

         cur_weight,
         price,
         cooperative_price,
         union_price,

     ]
     create_value(worksheet, value_header_list, 4, 5)

     list2 = [
         'مجموع==>',
         '',
         '',
         '',
         '',
         '',
         heavy_livestock,
         light_livestock,
         weight_quota_heavy,
         weight_quota_light,
         '',
         '',
         '',
         len(transactions),
         '',
         cur_heavy,
         cur_light,

         cur_weight,
         price,
         cooperative_price,
         union_price,

     ]
     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 gasgdasd(request):
    ransactions = PosMachineTransactions.objects.filter(trash=False,
                                                        live_stock=True, paid=True,
                                                        ).order_by('id')
    natcpdes = ransactions.values_list('natcode', flat=True).distinct()

    ranchers = Rancher.objects.filter(trash=False, national_id__in=natcpdes,has_script=False).only('name', 'national_id',
                                                                                  'heavy_livestock', 'light_livestock',
                                                                                  'city', 'mobile')
    for r in ranchers:
        update_one_rancher(r)

    return HttpResponse('ok')


def live_stock_product_excel(request):

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


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

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

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

    ]
    ransactions = PosMachineTransactions.objects.filter(trash=False,
                                                     live_stock=True, paid=True,
                                                     ).order_by('id')
    natcpdes = ransactions.values_list('natcode',flat=True).distinct()

    ranchers=Rancher.objects.filter(trash=False,national_id__in=natcpdes,has_script=True).only('name','national_id',
                                                                                                  'heavy_livestock','light_livestock','city','mobile')


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

    create_header(worksheet, header_list, 5, 3, height=20)

    excel_description(worksheet, 'A1', f'دامداران مغایرت دار', color='red', row2='D1')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)

    l = 5
    m = 1
    if ranchers:
     for rancher in ranchers:
         transactions = ransactions.filter(natcode=rancher.national_id).order_by('id')

         serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data
         cur_heavy = sum(safe_get_additional(data).get('cur_heavy', 0) for data in serializer)
         cur_light = sum(safe_get_additional(data).get('cur_light', 0) for data in serializer)
         cooperative_price = sum(safe_get_additional(data).get('cooperative_price', 0) for data in serializer)
         union_price = sum(safe_get_additional(data).get('union_price', 0) for data in serializer)
         cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
         price = sum(data['price'] for data in serializer)

         cooperative_list_name = list({data['pos']['cooperative']['name'] for data in serializer})
         cooperative_list_mobile = list({data['pos']['cooperative']['user']['mobile'] for data in serializer})
         natcode_list = list({data['natcode'] for data in serializer})

         cooperative_names_str = ' / '.join(cooperative_list_name) if cooperative_list_name else ''
         cooperative_mobiles_str = ' / '.join(cooperative_list_mobile) if cooperative_list_mobile else ''
         natcode_list_str = ' / '.join(natcode_list) if natcode_list else ''

         date_list=[]
         for data in serializer:
             date = datetime.strptime(str(data['date']), '%Y-%m-%dT%H:%M:%S.%f')
             date_list.append(str(convert_to_shamsi(datetime=date)))
         date_str = ' / '.join(date_list) if date_list else ''
         type_rancher='روستایی' if rancher.type=='rural' else 'صنعتی'
         list1 = [
             m,
             rancher.name,
             type_rancher,
             rancher.national_id,
             rancher.mobile,
             rancher.city,
             rancher.heavy_livestock,
             rancher.light_livestock,
             rancher.weight_quota_heavy,
             rancher.weight_quota_light,
             cooperative_names_str,
             cooperative_mobiles_str,
             natcode_list_str,
             len(transactions),
             date_str,
             cur_heavy,
             cur_light,

             cur_weight,

             price,
             cooperative_price,
             union_price,

         ]
         l += 1
         m += 1

         create_value(worksheet, list1, l + 1, 1, border_style='thin')
     transactions = ransactions

     serializer = PosMachineTransactionsForLiveStockSerializer(transactions, many=True).data
     cur_heavy = sum(safe_get_additional(data).get('cur_heavy', 0) for data in serializer)
     cur_light = sum(safe_get_additional(data).get('cur_light', 0) for data in serializer)
     cooperative_price = sum(safe_get_additional(data).get('cooperative_price', 0) for data in serializer)
     union_price = sum(safe_get_additional(data).get('union_price', 0) for data in serializer)
     cur_weight = sum(data['products'][0].get('cur_weight', 0) for data in serializer)
     price = sum(data['price'] for data in serializer)
     heavy_livestock = ranchers.aggregate(total=Sum('heavy_livestock'))[
                            'total'] or 0
     light_livestock = ranchers.aggregate(total=Sum('light_livestock'))[
                            'total'] or 0
     weight_quota_light = ranchers.aggregate(total=Sum('weight_quota_light'))[
                            'total'] or 0
     weight_quota_heavy = ranchers.aggregate(total=Sum('weight_quota_heavy'))[
                            'total'] or 0
     value_header_list = [
         len(natcpdes),
         len(transactions),
         cur_heavy,
         cur_light,
         heavy_livestock,
         light_livestock,
         weight_quota_heavy,
         weight_quota_light,

         cur_weight,
         price,
         cooperative_price,
         union_price,

     ]
     create_value(worksheet, value_header_list, 4, 5)

     list2 = [
         'مجموع==>',
         '',
         '',
         '',
         '',
         '',
         heavy_livestock,
         light_livestock,
         weight_quota_heavy,
         weight_quota_light,
         '',
         '',
         '',
         len(transactions),
         '',
         cur_heavy,
         cur_light,

         cur_weight,
         price,
         cooperative_price,
         union_price,

     ]
     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
