from datetime import datetime, timedelta

import jdatetime
import requests
from django.db.models import Sum, Q, F
from django.http import HttpResponse

from authentication.models import SystemUserProfile
from general_urls import base_url_for_sms_report
from helper_eata import token, chat_id, chat_id_mali
from panel.ProvinceOperator.serializers import TotalWageInformationSerializer
from panel.helper_excel import shamsi_date, to_locale_str
from panel.models import PoultryHatching, ProvinceKillRequest, KillHousePercentage, TotalWageInformation, \
    InternalTransaction, TokenEitaaForEachVet, VetFarm, KillHouseRequest, PoultryRequest, Poultry
from ticket.models import TicketSupport, MessageSupport


def format_datetime_to_shamsi(input_date):
    if isinstance(input_date, datetime):
        input_date = input_date.date()

    shamsi_date = jdatetime.date.fromgregorian(date=input_date)
    shamsi_date_str = shamsi_date.strftime('%Y/%m/%d')

    weekday_str = input_date.strftime('%A')
    weekdays = {
        'Saturday': 'شنبه',
        'Sunday': 'یکشنبه',
        'Monday': 'دوشنبه',
        'Tuesday': 'سه‌شنبه',
        'Wednesday': 'چهارشنبه',
        'Thursday': 'پنج‌شنبه',
        'Friday': 'جمعه'
    }
    weekday_str_fa = weekdays.get(weekday_str, '')

    formatted_date = f"گزارش {weekday_str_fa} به تاریخ {shamsi_date_str}"

    return formatted_date


def bot_eitaa_for_bar(request):
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()
    response = requests.get(
        f'https://{base_url_for_sms_report}backend.rasadyaar.ir/province_request_letter/?date={date}')
    date_time_jalali = format_datetime_to_shamsi(date)

    if response.status_code == 200:
        data = response.json()

        allocation = data.get('allocation', [])
        kill_house_num = 1
        messages_sent = 0

        for entry in allocation:
            date_shamsi = shamsi_date(date).replace('-', '_')
            base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
            base_message += f'❗{date_time_jalali}❗\n'
            base_message += f' #گزارش_بار_داخل_استان #{date_shamsi}\n\n'
            total_quantity = entry.get('total_quantity')
            if total_quantity and int(total_quantity) > 0:
                len_bar = entry.get('province_kill_request')
                killer = 'کشتارگاه' if entry.get('killer') == False else 'کشتارکن'
                name = entry.get("name").replace(' ', '_')
                mobile = entry.get("kill_house_operator").get("user").get("mobile")
                total_quantity = "{:,}".format(int(total_quantity))

                current_message = base_message
                current_message += f'🟢 {killer} #{name} ({mobile})\n'
                current_message += f'تعداد کل بار: {len(len_bar)}\n'
                current_message += f'حجم کل بار: {total_quantity}\n'
                current_message += f'--------------------------------\n'

                m = 1
                for request1 in entry.get('province_kill_request', []):
                    poultry = request1.get('poultry', 'نامشخص')
                    poultry_mobile = request1.get('poultry_mobile', 'نامشخص')
                    quantity = request1.get('quantity', 0)
                    average_weight = request1.get('Index_weight', 'نامشخص')
                    weight = request1.get('weight', 'نامشخص')
                    car_type = request1.get('car_type', 'نامشخص')
                    driver_name = request1.get('driver_name', 'نامشخص')
                    traffic_code = request1.get('traffic_code', 'نامشخص')
                    pelak = request1.get('pelak', 'نامشخص')
                    quantity = "{:,}".format(int(quantity))
                    weight = "{:,}".format(int(weight))

                    current_message += f'\n🔸{m}-مرغدار: {poultry} ({poultry_mobile})\n'
                    current_message += f'میانگین وزن بار: {average_weight}\n'
                    current_message += f'حجم بار: {quantity}\n'
                    current_message += f'وزن بار: {weight}\n'
                    current_message += f'نوع ماشین: {car_type}\n'
                    current_message += f'نام راننده: {driver_name}\n'
                    current_message += f'کد حمل و نقل: {traffic_code}\n'
                    current_message += f'پلاک: {pelak}\n'
                    current_message += '-' * 30 + '\n'
                    m += 1

                data = {
                    'chat_id': chat_id,
                    'text': current_message,
                }
                response = requests.post(url, data=data, verify=False)
                if response.status_code == 200:
                    messages_sent += 1
                kill_house_num += 1

        return HttpResponse(f'{messages_sent} پیام با موفقیت ارسال شد.')

    return HttpResponse('Error fetching data', status=500)


def bot_eitaa_free_bar(request):
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()
    response = requests.get(
        f'https://{base_url_for_sms_report}backend.rasadyar.com/province_request_letter/?date={date}')
    date_time_jalali = format_datetime_to_shamsi(date)
    if response.status_code == 200:
        data = response.json()
        date_shamsi = shamsi_date(date).replace('-', '_')
        out_province = data.get('out_province', [])
        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
        base_message += f'❗{date_time_jalali}❗\n'
        base_message += f' #گزارش_خارج_استان #{date_shamsi}\n\n'
        base_message += f'تعداد کل سفارشات: {len(out_province)}\n'
        base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

        messages = []
        current_message = base_message
        m = 1
        for entry in out_province:
            quantity = entry['quantity']
            poultry_name = entry['poultry']['user']['fullname']
            poultry_mobile = entry['poultry']['user']['mobile']
            buyer_fullname = entry['out_province_poultry_request_buyer']['fullname']
            buyer_mobile = entry['out_province_poultry_request_buyer']['mobile']
            buyer_city = entry['out_province_poultry_request_buyer']['city']
            city = entry['poultry']['user']['city']['name']
            weight = entry.get('Index_weight', 'نامشخص')
            weight_all = quantity * weight
            quantity = "{:,}".format(entry['quantity'])
            weight_all = "{:,}".format(int(weight_all))

            new_message_part = f'{m}:\n'
            new_message_part += f"🟢 مرغدار : {poultry_name} ({poultry_mobile})\n"
            new_message_part += f"شهر: {city}\n"
            new_message_part += f"🔸 خریدار :  {buyer_fullname} ({buyer_mobile})\n"
            new_message_part += f"شهر: {buyer_city}\n"
            new_message_part += f"میانگین وزن : {weight}\n"
            new_message_part += f" تعداد : {quantity}\n"
            new_message_part += f" وزن تقریبی : {weight_all}\n"
            new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'
            m += 1
            if len(current_message) + len(new_message_part) > 4000:
                messages.append(current_message)
                current_message = base_message

            current_message += new_message_part

        if current_message and current_message != base_message:
            messages.append(current_message)

        for message in messages:
            data = {
                'chat_id': chat_id,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)

        return HttpResponse(f'{len(messages)} پیام ارسال شد.')


def bot_eitaa_for_hatching_gt_50(request):
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()
    date_time_jalali = format_datetime_to_shamsi(date)
    date_shamsi = shamsi_date(date).replace('-', '_')
    base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
    base_message += f'❗{date_time_jalali}❗\n'
    base_message += f' #گزارش_فارم_بالای_50_روز #{date_shamsi}\n\n'
    base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

    poultry_hatching = PoultryHatching.objects.filter(trash=False, chicken_age__gte=50)
    m = 1
    for hatching in poultry_hatching:
        message = f'{m}-مرغدار {hatching.poultry.unit_name}\n' \
                  f''
        m += 1
        base_message += message
    data = {
        'chat_id': chat_id,
        'text': base_message,
    }
    response = requests.post(url, data=data, verify=False)
    return HttpResponse(f'{len(base_message)} پیام ارسال شد.')


def bot_eitaa_for_province_kill_request(request):
    if base_url_for_sms_report in ('ma', 'test'):
        url = f'https://eitaayar.ir/api/{token}/sendMessage'
        date = datetime.now().date()
        province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, state__in=('accepted', 'pending'),
                                                                    return_to_province=False,
                                                                    kill_request__recive_date__date=date) \
            .order_by('-kill_request__recive_date').only('main_quantity', 'quantity',
                                                         'province_request__poultry_request__Index_weight',
                                                         'main_quantity', 'province_request__poultry_request__export',
                                                         'province_request__poultry_request__poultry__unit_name',
                                                         'province_request__city_request_Poultry__poultry_request__poultry__user__mobile',
                                                         'province_request__city_request_Poultry__poultry_request__poultry__user__city__name',
                                                         'kill_request__kill_house__name',
                                                         'kill_request__kill_house__kill_house_operator__user__mobile',
                                                         'province_request__poultry_request__direct_buying',
                                                         'province_request__poultry_request__order_code',
                                                         'kill_request__kill_house__system_address__city__name')
        date_time_jalali = format_datetime_to_shamsi(date)

        date_shamsi = shamsi_date(date).replace('-', '_')
        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
        base_message += f'❗{date_time_jalali}❗\n'
        base_message += f' #گزارش_تخصیصات #{date_shamsi}\n\n'
        base_message += f'تعداد کل تخصیصات: {len(province_kill_requests)}\n'
        base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

        messages = []
        current_message = base_message
        m = 1
        for entry in province_kill_requests:
            main_quantity = entry.main_quantity
            remain_quantity = entry.quantity if entry.return_to_province == False else 0
            poultry_name = entry.province_request.poultry_request.poultry.unit_name
            poultry_mobile = entry.province_request.poultry_request.poultry.user.mobile

            city = entry.province_request.poultry_request.poultry.user.city.name
            buyer = entry.kill_request.kill_house.name
            buyer_city = entry.kill_request.kill_house.system_address.city.name
            buyer_mobile = entry.kill_request.kill_house.kill_house_operator.user.mobile
            weight = entry.province_request.poultry_request.Index_weight
            order_code = entry.province_request.poultry_request.order_code
            weight_all = remain_quantity * weight
            main_quantity = "{:,}".format(main_quantity)
            remain_quantity = "{:,}".format(remain_quantity)
            weight_all = "{:,}".format(int(weight_all))

            if entry.province_request.poultry_request.direct_buying == True:
                province_type = 'خرید مستقیم'
            elif entry.province_request.poultry_request.export == True:
                province_type = 'فروش به خارج استان'
            else:
                province_type = 'اتحادیه'
            new_message_part = f'{m}:\n'
            new_message_part += f"🟢 مرغدار : {poultry_name} ({poultry_mobile})\n"
            new_message_part += f"شهر: {city}\n"
            new_message_part += f"کد سفارش: {order_code}\n"
            new_message_part += f"نوع فروش: {province_type}\n"
            new_message_part += f" تعداد تخصیصی :{main_quantity}\n"
            new_message_part += f"مانده قابل تخصیص :{remain_quantity}\n"
            new_message_part += f"میانگین وزن : {weight}\n"
            new_message_part += f"وزن تقریبی :{weight_all}\n"
            new_message_part += f"\n"
            new_message_part += f"🔴🔴خریدار : {buyer} ({buyer_mobile})\n"
            new_message_part += f"شهر خریدار: {buyer_city}\n"
            new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'
            m += 1
            if len(current_message) + len(new_message_part) > 4000:
                messages.append(current_message)
                current_message = base_message

            current_message += new_message_part

        if current_message and current_message != base_message:
            messages.append(current_message)

        for message in messages:
            data = {
                'chat_id': chat_id,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)

        return HttpResponse(f'{len(messages)} پیام ارسال شد.')


def bot_eitaa_for_each_province_kill_request(entry, vet):
    if base_url_for_sms_report in ('ma', 'test'):
        messages = []
        chat_id_eitaa = None
        if vet:
            chat_id_eitaa = TokenEitaaForEachVet.objects.filter(vet_mobile=vet.vet.user.mobile).first()

        url = f'https://eitaayar.ir/api/{token}/sendMessage'
        date = datetime.now().date()

        date_time_jalali = format_datetime_to_shamsi(date)

        date_shamsi = shamsi_date(date).replace('-', '_')
        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
        base_message += f'❗{date_time_jalali}❗\n'
        base_message += f' #گزارش_تخصیصات #{date_shamsi}\n\n'
        base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

        current_message = base_message
        m = 1

        main_quantity = entry.main_quantity
        remain_quantity = (entry.main_quantity - entry.total_killed_quantity) if (
                                                                                         entry.main_quantity - entry.total_killed_quantity) > 0 else 0
        poultry_name = entry.province_request.poultry_request.poultry.unit_name
        poultry_mobile = entry.province_request.poultry_request.poultry.user.mobile

        city = entry.province_request.poultry_request.poultry.user.city.name
        buyer = entry.kill_request.kill_house.name
        buyer_city = entry.kill_request.kill_house.system_address.city.name
        buyer_mobile = entry.kill_request.kill_house.kill_house_operator.user.mobile
        weight = entry.province_request.poultry_request.Index_weight
        order_code = entry.province_request.poultry_request.order_code
        weight_all = entry.total_killed_quantity * weight
        main_quantity = "{:,}".format(main_quantity)
        remain_quantity = "{:,}".format(remain_quantity)
        weight_all = "{:,}".format(int(weight_all))

        if entry.province_request.poultry_request.direct_buying == True:
            province_type = 'خرید مستقیم'
        elif entry.province_request.poultry_request.export == True:
            province_type = 'فروش به خارج استان'
        elif entry.market == True:
            province_type = 'پنل معاملاتی'
        else:
            province_type = 'اتحادیه'
        new_message_part = f'{m}:\n'
        new_message_part += f"🟢 مرغدار : {poultry_name} ({poultry_mobile})\n"
        new_message_part += f"شهر: {city}\n"
        new_message_part += f"کد سفارش: {order_code}\n"
        new_message_part += f"نوع فروش: {province_type}\n"
        new_message_part += f" تعداد تخصیصی :{main_quantity}\n"
        new_message_part += f"مانده قابل تخصیص :{remain_quantity}\n"
        new_message_part += f"میانگین وزن : {weight}\n"
        new_message_part += f"وزن تقریبی :{weight_all}\n"
        new_message_part += f"\n"
        new_message_part += f"🔴🔴خریدار : {buyer} ({buyer_mobile})\n"
        new_message_part += f"شهر خریدار: {buyer_city}\n"
        new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'
        m += 1
        if len(current_message) + len(new_message_part) > 4000:
            messages.append(current_message)
            current_message = base_message

        current_message += new_message_part

        if current_message and current_message != base_message:
            messages.append(current_message)
        if chat_id_eitaa:
            chat_id_eitaa = chat_id_eitaa.token
            for message in messages:
                data = {
                    'chat_id': chat_id_eitaa,
                    'text': message,
                }
                response = requests.post(url, data=data, verify=False)
        for message in messages:
            data = {
                'chat_id': chat_id,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)


def bot_eitaa_for_each_delete_province_kill_request(entry):
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()
    order_code = entry.province_request.poultry_request.order_code
    date_time_jalali = format_datetime_to_shamsi(date)

    date_shamsi = shamsi_date(date).replace('-', '_')
    base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
    base_message += f'❗{date_time_jalali}❗\n'
    base_message += f' #گزارش_تخصیصات_حذف_شده #{date_shamsi}\n\n'
    base_message += f'❗❗❗❗اصلاحیه تخصیص حذف شده با کد سفارش {order_code}❗❗❗❗\n\n'
    base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

    messages = []
    current_message = base_message
    m = 1

    main_quantity = entry.main_quantity
    remain_quantity = (entry.main_quantity - entry.total_killed_quantity) if (
                                                                                     entry.main_quantity - entry.total_killed_quantity) > 0 else 0
    poultry_name = entry.province_request.poultry_request.poultry.unit_name
    poultry_mobile = entry.province_request.poultry_request.poultry.user.mobile

    city = entry.province_request.poultry_request.poultry.user.city.name
    buyer = entry.kill_request.kill_house.name
    buyer_city = entry.kill_request.kill_house.system_address.city.name
    buyer_mobile = entry.kill_request.kill_house.kill_house_operator.user.mobile
    weight = entry.province_request.poultry_request.Index_weight

    weight_all = entry.total_killed_quantity * weight
    main_quantity = "{:,}".format(main_quantity)
    remain_quantity = "{:,}".format(remain_quantity)
    weight_all = "{:,}".format(int(weight_all))

    if entry.province_request.poultry_request.direct_buying == True:
        province_type = 'خرید مستقیم'
    elif entry.province_request.poultry_request.export == True:
        province_type = 'فروش به خارج استان'
    elif entry.market == True:
        province_type = 'پنل معاملاتی'
    else:
        province_type = 'اتحادیه'
    new_message_part = f'{m}:\n'
    new_message_part += f"🟢 مرغدار : {poultry_name} ({poultry_mobile})\n"
    new_message_part += f"شهر: {city}\n"
    new_message_part += f"کد سفارش: {order_code}\n"
    new_message_part += f"نوع فروش: {province_type}\n"
    new_message_part += f" تعداد تخصیصی :{main_quantity}\n"
    new_message_part += f"مانده قابل تخصیص :{remain_quantity}\n"
    new_message_part += f"میانگین وزن : {weight}\n"
    new_message_part += f"وزن تقریبی :{weight_all}\n"
    new_message_part += f"\n"
    new_message_part += f"🔴🔴خریدار : {buyer} ({buyer_mobile})\n"
    new_message_part += f"شهر خریدار: {buyer_city}\n"
    new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'
    new_message_part += f'❗❗❗تخصیص با کد سفارش {order_code} حذف شده است❗❗❗'
    m += 1
    if len(current_message) + len(new_message_part) > 4000:
        messages.append(current_message)
        current_message = base_message

    current_message += new_message_part

    if current_message and current_message != base_message:
        messages.append(current_message)

    for message in messages:
        data = {
            'chat_id': chat_id,
            'text': message,
        }
        response = requests.post(url, data=data, verify=False)


def bot_eitaa_out_province_live_bar(request, poultry_requests, vet):
    chat_id_eitaa = None
    if vet:
        chat_id_eitaa = TokenEitaaForEachVet.objects.filter(vet_mobile=vet.vet.user.mobile).first()
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()
    response = poultry_requests
    date_time_jalali = format_datetime_to_shamsi(date)

    date_shamsi = shamsi_date(date).replace('-', '_')
    out_province = len(poultry_requests)
    base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
    base_message += f'❗{date_time_jalali}❗\n'
    base_message += f' #گزارش_فروش_مرغ_زنده_خارج_استان #{date_shamsi}\n\n'
    base_message += f'تعداد کل سفارشات: {out_province}\n'
    base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

    messages = []
    current_message = base_message
    m = 1

    quantity = poultry_requests.aggregate(total=Sum('quantity'))[
                   'total'] or 0
    poultry_name = poultry_requests.last().poultry.user.fullname
    poultry_mobile = poultry_requests.last().poultry.user.mobile
    buyer_fullname = poultry_requests.last().out_province_poultry_request_buyer.fullname
    buyer_mobile = poultry_requests.last().out_province_poultry_request_buyer.mobile
    buyer_city = poultry_requests.last().out_province_poultry_request_buyer.city
    city = poultry_requests.last().poultry.user.city.name
    weight = poultry_requests.aggregate(total=Sum('Index_weight'))[
                 'total'] or 0
    weight = weight / out_province if out_province > 0 else 0
    weight_all = quantity * weight
    quantity = "{:,}".format(quantity)
    weight_all = "{:,}".format(int(weight_all))

    new_message_part = f'{m}:\n'
    new_message_part += f"🟢 مرغدار : {poultry_name} ({poultry_mobile})\n"
    new_message_part += f"شهر: {city}\n"
    new_message_part += f"🔸 خریدار :  {buyer_fullname} ({buyer_mobile})\n"
    new_message_part += f"شهر: {buyer_city}\n"
    new_message_part += f"میانگین وزن : {weight}\n"
    new_message_part += f" تعداد : {quantity}\n"
    new_message_part += f" وزن تقریبی : {weight_all}\n"
    new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'
    m += 1
    if len(current_message) + len(new_message_part) > 4000:
        messages.append(current_message)
        current_message = base_message

    current_message += new_message_part

    if current_message and current_message != base_message:
        messages.append(current_message)
    if chat_id_eitaa:
        chat_id_eitaa = chat_id_eitaa.token
        for message in messages:
            data = {
                'chat_id': chat_id_eitaa,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)
    for message in messages:
        data = {
            'chat_id': chat_id,
            'text': message,
        }
        response = requests.post(url, data=data, verify=False)

    return HttpResponse(f'{len(messages)} پیام ارسال شد.')


def transaction_for_eata(request, transaction):
    if transaction.payer_type == 'poultry':
        pass
    else:
        url = f'https://eitaayar.ir/api/{token}/sendMessage'
        date = datetime.now().date()
        if base_url_for_sms_report == 'ma':
            province = 'مرکزی'
        elif base_url_for_sms_report == 'ha':
            province = 'همدان'
        elif base_url_for_sms_report == 'ku':
            province = 'کردستان'
        elif base_url_for_sms_report == 'bu':
            province = 'بوشهر'
        else:
            province = 'تست'
        date_shamsi = shamsi_date(date).replace('-', '_')
        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
        base_message += f' #گزارش_تراکنش_پرداختی #{date_shamsi}\n'
        base_message += f' #استان_{province}\n\n'
        base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

        messages = []
        current_message = base_message

        from_date = jdatetime.date.fromgregorian(
            year=transaction.date.year,
            month=transaction.date.month,
            day=transaction.date.day
        ).strftime('%Y-%m-%d')
        reversed_date = reversed(from_date.split("-"))
        separate = "-"
        date = separate.join(reversed_date)
        union_share = "{:,}".format(transaction.union_share)
        company_share = "{:,}".format(transaction.company_share)
        guilds_share = "{:,}".format(transaction.guilds_share)
        others_share = "{:,}".format(transaction.other_share)
        amount = "{:,}".format(transaction.amount)

        if transaction.payer_type == 'kill_house':
            if transaction.kill_house.killer == True and transaction.kill_house.type == 'exclusive':
                parent = KillHousePercentage.objects.get(kill_house=transaction.kill_house, trash=False)
                payer_type = f'کشتارکن اختصاصی {parent.kill_house_for_killer.name}'
            elif transaction.kill_house.killer == True and transaction.kill_house.type == 'public':
                payer_type = 'کشتارکن عمومی'
            else:
                payer_type = 'کشتارگاه'
            payer_unit_name = transaction.kill_house.name
        else:
            payer_type = 'مرغدار'
            payer_unit_name = transaction.poultry.unit_name

        new_message_part = f"🟢 پرداخت کننده : {transaction.payer_fullname}\n"
        new_message_part += f"🟢 تلفن  : {transaction.payer_mobile}\n"
        new_message_part += f"🟢 ماهیت پرداخت کننده  : {payer_type}\n"
        new_message_part += f"🟢 نام واحد  : {payer_unit_name}\n"
        new_message_part += f"تاریخ پرداخت: {date}\n"
        new_message_part += f"مبلغ کل تراکنش: {amount} ریال \n"
        new_message_part += f"\n"
        new_message_part += f"🔸 سهم اتحادیه مرغدارن :  {union_share} ریال \n"
        new_message_part += f"🔸 سهم شرکت :  {company_share} ریال \n"
        new_message_part += f"🔸 سهم صنف پروتئین :  {guilds_share} ریال \n"
        new_message_part += f"🔸 سهم دامپزشک :  {others_share} ریال \n"
        new_message_part += f"\n"
        # if base_url_for_sms_report == 'ma':
        #     new_message_part += f"‼توجه: سهم صنف پروتئین به حساب اتحادیه مرغدارن واریز شد.‼"
        if base_url_for_sms_report == 'ha':
            new_message_part += f"‼توجه: سهم صنف پروتئین و مسئول فنی فارم به حساب اتحادیه مرغدارن واریز شد.‼"
        new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'

        if len(current_message) + len(new_message_part) > 4000:
            messages.append(current_message)
            current_message = base_message

        current_message += new_message_part

        if current_message and current_message != base_message:
            messages.append(current_message)

        for message in messages:
            data = {
                'chat_id': chat_id_mali,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)

        return HttpResponse('ok')


def daily_cron_job_transaction_for_eata():
    total_wage_info = TotalWageInformation.objects.get(trash=False)
    serializer = TotalWageInformationSerializer(total_wage_info).data
    total_wage = "{:,}".format(int(serializer['wage_info']['total_wage']))
    total_unpaid_wage = "{:,}".format(int(serializer['wage_info']['total_unpaid_wage']))
    total_paid_wage = "{:,}".format(int(serializer['wage_info']['total_paid_wage']))

    company_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "شرکت"), None)
    company_total_unpaid_wage = "{:,}".format(int(company_unpaid_wage)) if company_unpaid_wage is not None else "0"
    company_total_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "شرکت"), None)
    company_total_wage = "{:,}".format(int(company_total_wage)) if company_total_wage is not None else "0"
    company_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "شرکت"),
        None)
    company_total_paid_wage = "{:,}".format(int(company_paid_wage)) if company_paid_wage is not None else "0"

    guilds_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "صنف پروتئین"),
        None)
    guilds_total_unpaid_wage = "{:,}".format(int(guilds_unpaid_wage)) if guilds_unpaid_wage is not None else "0"
    guilds_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "صنف پروتئین"), None)
    guilds_total_wage = "{:,}".format(int(guilds_wage)) if guilds_wage is not None else "0"

    guilds_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "صنف پروتئین"),
        None)
    guilds_total_paid_wage = "{:,}".format(int(guilds_paid_wage)) if guilds_paid_wage is not None else "0"

    union_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "اتحادیه"), None)
    union_total_unpaid_wage = "{:,}".format(int(union_unpaid_wage)) if union_unpaid_wage is not None else "0"
    union_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "اتحادیه"), None)
    union_total_wage = "{:,}".format(int(union_wage)) if union_wage is not None else "0"
    union_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "اتحادیه"),
        None)
    union_total_paid_wage = "{:,}".format(int(union_paid_wage)) if union_paid_wage is not None else "0"

    other_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "دامپزشک"), None)
    other_total_unpaid_wage = "{:,}".format(int(other_unpaid_wage)) if other_unpaid_wage is not None else "0"
    other_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "دامپزشک"), None)
    other_total_wage = "{:,}".format(int(other_wage)) if other_wage is not None else "0"
    other_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "دامپزشک"), None)
    other_total_paid_wage = "{:,}".format(int(other_paid_wage)) if other_paid_wage is not None else "0"

    date = datetime.now().date()

    url = f'https://eitaayar.ir/api/{token}/sendMessage'

    if base_url_for_sms_report == 'ma':
        province = 'مرکزی'
    elif base_url_for_sms_report == 'ha':
        province = 'همدان'
    elif base_url_for_sms_report == 'ku':
        province = 'کردستان'
    elif base_url_for_sms_report == 'bu':
        province = 'بوشهر'
    else:
        province = 'تست'
    date_shamsi = shamsi_date(date).replace('-', '_')
    base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
    base_message += f' #اطلاعات_جامع_تعرفه #{date_shamsi}\n'
    base_message += f' #استان_{province}\n\n'
    base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

    messages = []
    current_message = base_message

    union_share = union_total_paid_wage
    company_share = company_total_paid_wage
    guilds_share = guilds_total_paid_wage
    other_share = other_total_paid_wage

    amount = total_paid_wage

    new_message_part = f"مجموع تعرفه: {total_wage} ریال \n"
    new_message_part += f"مجموع پرداختی: {amount} ریال \n"
    new_message_part += f"مجموع باقیمانده: {total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    new_message_part += f"🔸 کل سهم اتحادیه مرغدارن :  {union_total_wage} ریال \n"
    new_message_part += f"🔸واریزی سهم اتحادیه مرغدارن :  {union_share} ریال \n"
    new_message_part += f"🔸مانده سهم اتحادیه مرغدارن :  {union_total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    new_message_part += f"🔹کل سهم شرکت :  {company_total_wage} ریال \n"
    new_message_part += f"🔹واریزی سهم شرکت :  {company_share} ریال \n"
    new_message_part += f"🔹مانده سهم شرکت :  {company_total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    new_message_part += f"🔻 کل سهم صنف پروتئین :  {guilds_total_wage} ریال \n"
    new_message_part += f"🔻 واریزی سهم صنف پروتئین :  {guilds_share} ریال \n"
    new_message_part += f"🔻 مانده سهم صنف پروتئین :  {guilds_total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    # if base_url_for_sms_report == 'ma':
    #     new_message_part += f"‼توجه: سهم صنف پروتئین به حساب اتحادیه مرغدارن واریز شد.‼"
    if base_url_for_sms_report == 'ha':
        new_message_part += f"\n"
        new_message_part += f"🔻 کل سهم دامپزشک :  {other_total_wage} ریال \n"
        new_message_part += f"🔻 واریزی سهم دامپزشک :  {other_share} ریال \n"
        new_message_part += f"🔻 مانده سهم دامپزشک :  {other_total_unpaid_wage} ریال \n"
        new_message_part += f"\n"
        new_message_part += f"‼توجه: سهم صنف پروتئین و مسئول فنی فارم به حساب اتحادیه مرغدارن واریز شد.‼"
    new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'

    if len(current_message) + len(new_message_part) > 4000:
        messages.append(current_message)
        current_message = base_message

    current_message += new_message_part

    if current_message and current_message != base_message:
        messages.append(current_message)

    for message in messages:
        data = {
            'chat_id': chat_id_mali,
            'text': message,
        }
        response = requests.post(url, data=data, verify=False)


def bot_eitaa_for_bug_reporter(text):
    token = "bot363954:e3d4dca2-f1b3-4f44-b5a9-d48aa11c79b8"
    chat_id = 10473672
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    t = f"\n"
    t += f" {text['result']} \n"
    t += f"\n"
    t += f"\n"
    t += f"عنوان خطا:"
    t += f"\n"
    t += f"\n"
    t += f"{text['error_title']} \n"
    t += f"\n"
    t += f"\n"
    t += f"پیغام خطا:"
    t += f"\n"
    t += f"\n"
    t += f"{text['error_message']} \n"
    t += f"\n"
    t += f"\n"
    t += f"توضیحات بیشتر:"
    t += f"\n"
    t += f"\n"
    t += f"{text['error_traceback']} \n"

    data = {
        'chat_id': chat_id,
        'text': t,
    }
    response = requests.post(url, data=data, verify=False)


def daily_manual_transaction_for_eata(request):
    total_wage_info = TotalWageInformation.objects.get(trash=False)
    serializer = TotalWageInformationSerializer(total_wage_info).data
    total_wage = "{:,}".format(int(serializer['wage_info']['total_wage']))
    total_unpaid_wage = "{:,}".format(int(serializer['wage_info']['total_unpaid_wage']))
    total_paid_wage = "{:,}".format(int(serializer['wage_info']['total_paid_wage']))

    company_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "شرکت"), None)
    company_total_unpaid_wage = "{:,}".format(int(company_unpaid_wage)) if company_unpaid_wage is not None else "0"
    company_total_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "شرکت"), None)
    company_total_wage = "{:,}".format(int(company_total_wage)) if company_total_wage is not None else "0"
    company_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "شرکت"),
        None)
    company_total_paid_wage = "{:,}".format(int(company_paid_wage)) if company_paid_wage is not None else "0"

    guilds_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "صنف پروتئین"),
        None)
    guilds_total_unpaid_wage = "{:,}".format(int(guilds_unpaid_wage)) if guilds_unpaid_wage is not None else "0"
    guilds_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "صنف پروتئین"), None)
    guilds_total_wage = "{:,}".format(int(guilds_wage)) if guilds_wage is not None else "0"

    guilds_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "صنف پروتئین"),
        None)
    guilds_total_paid_wage = "{:,}".format(int(guilds_paid_wage)) if guilds_paid_wage is not None else "0"

    union_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "اتحادیه"), None)
    union_total_unpaid_wage = "{:,}".format(int(union_unpaid_wage)) if union_unpaid_wage is not None else "0"
    union_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "اتحادیه"), None)
    union_total_wage = "{:,}".format(int(union_wage)) if union_wage is not None else "0"
    union_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "اتحادیه"),
        None)
    union_total_paid_wage = "{:,}".format(int(union_paid_wage)) if union_paid_wage is not None else "0"

    other_unpaid_wage = next(
        (share["total_unpaid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "دامپزشک"), None)
    other_total_unpaid_wage = "{:,}".format(int(other_unpaid_wage)) if other_unpaid_wage is not None else "0"
    other_wage = next(
        (share["total_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "دامپزشک"), None)
    other_total_wage = "{:,}".format(int(other_wage)) if other_wage is not None else "0"
    other_paid_wage = next(
        (share["total_paid_wage"] for share in serializer['wage_info']['shares'] if share["name"] == "دامپزشک"), None)
    other_total_paid_wage = "{:,}".format(int(other_paid_wage)) if other_paid_wage is not None else "0"

    date = datetime.now().date()

    url = f'https://eitaayar.ir/api/{token}/sendMessage'

    if base_url_for_sms_report == 'ma':
        province = 'مرکزی'
    elif base_url_for_sms_report == 'ha':
        province = 'همدان'
    elif base_url_for_sms_report == 'ku':
        province = 'کردستان'
    elif base_url_for_sms_report == 'bu':
        province = 'بوشهر'
    else:
        province = 'تست'
    date_shamsi = shamsi_date(date).replace('-', '_')
    base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
    base_message += f' #اطلاعات_جامع_تعرفه #{date_shamsi}\n'
    base_message += f' #استان_{province}\n\n'
    base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

    messages = []
    current_message = base_message

    union_share = union_total_paid_wage
    company_share = company_total_paid_wage
    guilds_share = guilds_total_paid_wage
    other_share = other_total_paid_wage

    amount = total_paid_wage

    new_message_part = f"مجموع تعرفه: {total_wage} ریال \n"
    new_message_part += f"مجموع پرداختی: {amount} ریال \n"
    new_message_part += f"مجموع باقیمانده: {total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    new_message_part += f"🔸 کل سهم اتحادیه مرغدارن :  {union_total_wage} ریال \n"
    new_message_part += f"🔸واریزی سهم اتحادیه مرغدارن :  {union_share} ریال \n"
    new_message_part += f"🔸مانده سهم اتحادیه مرغدارن :  {union_total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    new_message_part += f"🔹کل سهم شرکت :  {company_total_wage} ریال \n"
    new_message_part += f"🔹واریزی سهم شرکت :  {company_share} ریال \n"
    new_message_part += f"🔹مانده سهم شرکت :  {company_total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    new_message_part += f"🔻 کل سهم صنف پروتئین :  {guilds_total_wage} ریال \n"
    new_message_part += f"🔻 واریزی سهم صنف پروتئین :  {guilds_share} ریال \n"
    new_message_part += f"🔻 مانده سهم صنف پروتئین :  {guilds_total_unpaid_wage} ریال \n"
    new_message_part += f"\n"
    # if base_url_for_sms_report == 'ma':
    #     new_message_part += f"‼توجه: سهم صنف پروتئین به حساب اتحادیه مرغدارن واریز شد.‼"
    if base_url_for_sms_report == 'ha':
        new_message_part += f"\n"
        new_message_part += f"🔻 کل سهم دامپزشک :  {other_total_wage} ریال \n"
        new_message_part += f"🔻 واریزی سهم دامپزشک :  {other_share} ریال \n"
        new_message_part += f"🔻 مانده سهم دامپزشک :  {other_total_unpaid_wage} ریال \n"
        new_message_part += f"\n"
        new_message_part += f"‼توجه: سهم صنف پروتئین و مسئول فنی فارم به حساب اتحادیه مرغدارن واریز شد.‼"
    new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'

    if len(current_message) + len(new_message_part) > 4000:
        messages.append(current_message)
        current_message = base_message

    current_message += new_message_part

    if current_message and current_message != base_message:
        messages.append(current_message)

    for message in messages:
        data = {
            'chat_id': chat_id_mali,
            'text': message,
        }
        response = requests.post(url, data=data, verify=False)

    return HttpResponse('ok')


def transaction_for_eata_new(request):
    transactions = InternalTransaction.objects.filter(trash=False, status='completed', date__date=datetime.now().date())
    for transaction in transactions:
        if transaction.payer_type == 'poultry':
            pass
        else:
            url = f'https://eitaayar.ir/api/{token}/sendMessage'
            date = datetime.now().date()
            if base_url_for_sms_report == 'ma':
                province = 'مرکزی'
            elif base_url_for_sms_report == 'ha':
                province = 'همدان'
            elif base_url_for_sms_report == 'ku':
                province = 'کردستان'
            elif base_url_for_sms_report == 'bu':
                province = 'بوشهر'
            else:
                province = 'تست'
            date_shamsi = shamsi_date(date).replace('-', '_')
            base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
            base_message += f' #گزارش_تراکنش_پرداختی #{date_shamsi}\n'
            base_message += f' #استان_{province}\n\n'
            base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

            messages = []
            current_message = base_message

            from_date = jdatetime.date.fromgregorian(
                year=transaction.date.year,
                month=transaction.date.month,
                day=transaction.date.day
            ).strftime('%Y-%m-%d')
            reversed_date = reversed(from_date.split("-"))
            separate = "-"
            date = separate.join(reversed_date)
            union_share = "{:,}".format(transaction.union_share)
            company_share = "{:,}".format(transaction.company_share)
            guilds_share = "{:,}".format(transaction.guilds_share)
            others_share = "{:,}".format(transaction.other_share)
            amount = "{:,}".format(transaction.amount)

            if transaction.payer_type == 'kill_house':
                if transaction.kill_house.killer == True and transaction.kill_house.type == 'exclusive':
                    parent = KillHousePercentage.objects.get(kill_house=transaction.kill_house, trash=False)
                    payer_type = f'کشتارکن اختصاصی {parent.kill_house_for_killer.name}'
                elif transaction.kill_house.killer == True and transaction.kill_house.type == 'public':
                    payer_type = 'کشتارکن عمومی'
                else:
                    payer_type = 'کشتارگاه'
                payer_unit_name = transaction.kill_house.name
            else:
                payer_type = 'مرغدار'
                payer_unit_name = transaction.poultry.unit_name

            new_message_part = f"🟢 پرداخت کننده : {transaction.payer_fullname}\n"
            new_message_part += f"🟢 تلفن  : {transaction.payer_mobile}\n"
            new_message_part += f"🟢 ماهیت پرداخت کننده  : {payer_type}\n"
            new_message_part += f"🟢 نام واحد  : {payer_unit_name}\n"
            new_message_part += f"تاریخ پرداخت: {date}\n"
            new_message_part += f"مبلغ کل تراکنش: {amount} ریال \n"
            new_message_part += f"\n"
            new_message_part += f"🔸 سهم اتحادیه مرغدارن :  {union_share} ریال \n"
            new_message_part += f"🔸 سهم شرکت :  {company_share} ریال \n"
            new_message_part += f"🔸 سهم صنف پروتئین :  {guilds_share} ریال \n"
            new_message_part += f"🔸 سهم دامپزشک :  {others_share} ریال \n"
            new_message_part += f"\n"
            # if base_url_for_sms_report == 'ma':
            #     new_message_part += f"‼توجه: سهم صنف پروتئین به حساب اتحادیه مرغدارن واریز شد.‼"
            if base_url_for_sms_report == 'ha':
                new_message_part += f"‼توجه: سهم صنف پروتئین و مسئول فنی فارم به حساب اتحادیه مرغدارن واریز شد.‼"
            new_message_part += '\n➖➖➖➖➖➖➖➖➖➖\n'

            if len(current_message) + len(new_message_part) > 4000:
                messages.append(current_message)
                current_message = base_message

            current_message += new_message_part

            if current_message and current_message != base_message:
                messages.append(current_message)

            for message in messages:
                data = {
                    'chat_id': chat_id_mali,
                    'text': message,
                }
                response = requests.post(url, data=data, verify=False)

    return HttpResponse('ok')


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

    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    today = datetime.now().date()
    date_time_jalali = format_datetime_to_shamsi(today)
    date_shamsi = shamsi_date(date1).replace('-', '_')
    date_shamsi2 = shamsi_date(date2).replace('-', '_')

    vet_tokens = list(
        TokenEitaaForEachVet.objects
            .all()
            .only("vet_mobile", "token")
            .values_list('vet_mobile', flat=True)
            .distinct()
    )
    if not vet_tokens:
        return HttpResponse('no vets')

    vet_farms_qs = VetFarm.objects.filter(trash=False, vet__user__mobile__in=vet_tokens) \
        .only("id", "vet__user__mobile", "poultry__id")

    poultry_qs = Poultry.objects.filter(trash=False, id__in=vet_farms_qs.values_list('poultry__id', flat=True)) \
        .only("id", "unit_name", "breeding_unique_id")

    poultry_map = {p.id: p.breeding_unique_id for p in poultry_qs}
    poultry_breeding_ids = set(poultry_map.values())

    vet_farm_pairs = list(vet_farms_qs.values_list('vet__user__mobile', 'poultry__id'))
    breeding_to_vets = {}
    for vet_mobile, poultry_id in vet_farm_pairs:
        breeding = poultry_map.get(poultry_id)
        if breeding:
            breeding_to_vets.setdefault(breeding, set()).add(vet_mobile)

    kill_request_qs = KillHouseRequest.objects.filter(
        trash=False,
        kill_request__recive_date__date__gte=date1,
        kill_request__recive_date__date__lte=date2,
        province_request__poultry_request__poultry__in=poultry_qs
    ).only(
        "bar_code", "accepted_real_quantity", "clearance_code", "quarantine_quantity",
        "quarantine_code_state",
        "kill_request__recive_date",
        "killhouse_user__name",
        "province_request__poultry_request__poultry__unit_name",
    )

    poultry_request_out_qs = PoultryRequest.objects.filter(
        trash=False,
        out=True,
        send_date__date__gte=date1,
        send_date__date__lte=date2,
        poultry__in=poultry_qs
    ).only(
        "order_code", "quantity", "send_date", "quarantine_code",
        "buyer_fullname", "buyer_province", "buyer_city",
        "poultry__unit_name"
    )

    kill_house_request_code_quarantine = list(kill_request_qs.values_list('clearance_code', flat=True).distinct())
    kill_house_free_sale = list(poultry_request_out_qs.filter(quarantine_code__isnull=False)
                                .values_list('quarantine_code', flat=True).distinct())
    result = list(filter(None, kill_house_request_code_quarantine)) + list(filter(None, kill_house_free_sale))

    rsi_url = (
        f'https://rsibackend.rasadyar.com/app/send_different_bar/?province={base_url_for_sms_report}'
        f'&date1={date1}&date2={date2}'
    )
    try:
        rsi_resp = requests.post(rsi_url, json=result, headers={'Content-Type': 'application/json'})
        rsi_data = rsi_resp.json() if rsi_resp.status_code == 200 else []
    except Exception:
        rsi_data = []

    diffrent_rsi_by_vet = {vet: {'in': [], 'out': []} for vet in vet_tokens}

    for data in rsi_data:
        try:
            part_code = data['hatching']['poultry']['PartIdCode']
        except Exception:
            continue
        if part_code not in breeding_to_vets:
            continue
        date_str = str(data.get('Date', '')).split('T')[0]
        try:
            date_n = datetime.strptime(date_str, '%Y-%m-%d').date()
        except Exception:
            continue

        info = 'کد قرنطینه: {0} - حجم: {1} قطعه-مرغدار:{2} - مقصد بار: {3} - تاریخ بار: ({4})'.format(
            data.get('TrackingCode', ''),
            to_locale_str(int(data.get('GoodAmount', 0))),
            data.get('hatching', {}).get('poultry', {}).get('UnitName', ''),
            data.get('DesUnitName', ''),
            shamsi_date(date_n),
        )
        vets_for_part = breeding_to_vets.get(part_code, set())
        for v in vets_for_part:
            if data.get('Out') is False:
                diffrent_rsi_by_vet[v]['in'].append(info)
            else:
                diffrent_rsi_by_vet[v]['out'].append(info)

    for vet_mobile in vet_tokens:
        vet_specific_farms_qs = vet_farms_qs.filter(vet__user__mobile=vet_mobile)
        if not vet_specific_farms_qs.exists():
            continue

        vet_poultry_ids = list(vet_specific_farms_qs.values_list('poultry__id', flat=True).distinct())

        vet_kill_request = kill_request_qs.filter(
            province_request__poultry_request__poultry__in=vet_poultry_ids
        )
        vet_poultry_request_out = poultry_request_out_qs.filter(poultry__in=vet_poultry_ids)

        base_message = (
            '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
            f'❗{date_time_jalali}❗\n'
            f' #گزارش_بارهای_فاقد_مجوز_از_تاریخ_{date_shamsi}_تا_تاریخ_{date_shamsi2} #\n\n'
            f'➖➖➖➖➖➖➖➖➖➖\n'
        )
        current_message = base_message
        messages = []

        def _add_text(txt):
            nonlocal current_message, messages, base_message
            if not txt:
                return
            if len(current_message) + len(txt) > 4000:
                messages.append(current_message)
                current_message = base_message
            current_message += txt

        in_has_code_qs = vet_kill_request.filter(clearance_code__isnull=False)
        in_no_code_qs = vet_kill_request.filter(clearance_code__isnull=True)
        in_has_code_count = in_has_code_qs.count()
        in_no_code_count = in_no_code_qs.count()

        base_vet_message = 'دامپزشک محترم فارم({0}) گزارش عملکرد بارها به شرح زیر میباشد:\n'.format(
            vet_specific_farms_qs.first()
                .vet.user.fullname if vet_specific_farms_qs.first() else '-')
        _add_text(base_vet_message)
        bars_info = []
        for kill_req in in_no_code_qs:
            try:
                unit_name = kill_req.province_request.poultry_request.poultry.unit_name
            except Exception:
                unit_name = ''
            bars_info.append(
                'کد بار: {0} - حجم: {1} قطعه-مرغدار:{4} - مقصد بار: {2} - تاریخ بار: ({3})'.format(
                    kill_req.bar_code,
                    to_locale_str(int(kill_req.accepted_real_quantity or 0)),
                    getattr(kill_req.killhouse_user, 'name', ''),
                    shamsi_date(kill_req.kill_request.recive_date) if getattr(kill_req.kill_request, 'recive_date',
                                                                              None) else '',
                    unit_name
                )
            )
        bars_details = "\n".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

        diffrent_bars_info = []
        diffrent_qs = in_has_code_qs.filter(~Q(quarantine_quantity=F('quantity')))
        for kill_req in diffrent_qs:
            if kill_req.quarantine_quantity:
                quarantine_quantity = to_locale_str(int(kill_req.quarantine_quantity))
                diffrent_quantity = to_locale_str(
                    int(kill_req.quarantine_quantity) - int(kill_req.accepted_real_quantity))
            else:
                state = getattr(kill_req, 'quarantine_code_state', None)
                if state == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif state == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif state == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                else:
                    quarantine_quantity = 'ادغام'
                diffrent_quantity = 0
            diffrent_bars_info.append(
                'کد بار: {0} - حجم: {1} قطعه-مرغدار:{4} - کد قرنطینه: {2} - استعلام از قرنطینه: ({3})-اختلاف:{6}- تاریخ بار: ({5})'.format(
                    kill_req.bar_code,
                    to_locale_str(int(kill_req.accepted_real_quantity or 0)),
                    kill_req.clearance_code or '',
                    quarantine_quantity,
                    getattr(kill_req.province_request.poultry_request.poultry, 'unit_name', ''),
                    shamsi_date(kill_req.kill_request.recive_date) if getattr(kill_req.kill_request, 'recive_date',
                                                                              None) else '',
                    diffrent_quantity
                )
            )
        diffrent_bars_details = "\n".join([f"{i + 1}. {info}" for i, info in enumerate(diffrent_bars_info)])

        new_message_part_in = '❗❗ - تعداد بارهای داخل استان دارای مجوز قرنطینه {0} عدد و تعداد بار های فاقد مجوز {1} عدد میباشد.\n\n'.format(
            in_has_code_count, in_no_code_count
        )
        if bars_info:
            new_message_part_in += "بارهای داخل استان فاقد قرنطینه به شرح زیر میباشد:\n"
            new_message_part_in += f"{bars_details}\n"
            new_message_part_in += "--------------------------------\n"
        if diffrent_bars_info:
            new_message_part_in += "از بارهای داخل استان دارای مجوز تعداد {} بار دارای مغایرت در داده هستند:\n".format(
                diffrent_qs.count())
            new_message_part_in += f"{diffrent_bars_details}\n"
            new_message_part_in += "--------------------------------\n"

        rsi_in_list = diffrent_rsi_by_vet.get(vet_mobile, {}).get('in', [])
        if rsi_in_list:
            new_message_part_in += "با توجه به رصد هوش مصنوعی سامانه تعداد {} بار داخل استان در سامانه رصدیار ثبت نشده است:\n".format(
                len(rsi_in_list))
            new_message_part_in += "\n".join([f"{i + 1}. {it}" for i, it in enumerate(rsi_in_list)])
            new_message_part_in += "\n--------------------------------\n"

        new_message_part_in += "\n➖➖➖➖➖➖➖➖➖➖\n"

        _add_text(new_message_part_in)

        out_has_code_count = vet_poultry_request_out.filter(quarantine_code__isnull=False).count()
        out_no_code_qs = vet_poultry_request_out.filter(quarantine_code__isnull=True)
        out_no_code_count = out_no_code_qs.count()

        bars_info_out = []
        for poultry_req in out_no_code_qs:
            bars_info_out.append(
                'کد سفارش: {0} - حجم: {1} قطعه-مرغدار:{4} - خریدار: {2} - استان خریدار:{5} - شهر خریدار:{6} - تاریخ بار: ({3})'.format(
                    poultry_req.order_code,
                    to_locale_str(int(poultry_req.quantity or 0)),
                    poultry_req.buyer_fullname or '',
                    shamsi_date(poultry_req.send_date) if getattr(poultry_req, 'send_date', None) else '',
                    getattr(poultry_req.poultry, 'unit_name', ''),
                    poultry_req.buyer_province or '',
                    poultry_req.buyer_city or '',
                )
            )
        bars_details_out = "\n".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info_out)])

        new_message_part_out = '❗❗ - تعداد بارهای خارج استان دارای مجوز قرنطینه {0} عدد و تعداد بار های فاقد مجوز {1} عدد میباشد.\n\n'.format(
            out_has_code_count, out_no_code_count
        )
        if bars_info_out:
            new_message_part_out += "بارهای خارج استان فاقد قرنطینه به شرح زیر میباشد:\n"
            new_message_part_out += f"{bars_details_out}\n"
            new_message_part_out += "--------------------------------\n"

        rsi_out_list = diffrent_rsi_by_vet.get(vet_mobile, {}).get('out', [])
        if rsi_out_list:
            new_message_part_out += "با توجه به رصد هوش مصنوعی سامانه تعداد {} بار خارج استان در سامانه رصدیار ثبت نشده است:\n".format(
                len(rsi_out_list))
            new_message_part_out += "\n".join([f"{i + 1}. {it}" for i, it in enumerate(rsi_out_list)])
            new_message_part_out += "\n--------------------------------\n"

        new_message_part_out += "\n➖➖➖➖➖➖➖➖➖➖\n"

        _add_text(new_message_part_out)

        if current_message and current_message != base_message:
            messages.append(current_message)

        chat_token = TokenEitaaForEachVet.objects.filter(vet_mobile=vet_mobile).values_list('token', flat=True).first()
        if chat_token and messages:
            for message in messages:
                try:
                    requests.post(url, data={'chat_id': chat_token, 'text': message}, verify=False)
                except Exception:
                    pass
        for message in messages:
            data = {
                'chat_id': chat_id,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)
    return HttpResponse('ok')


def daily_report_for_each_vet_farm_cron():
    today = datetime.now().date() - timedelta(days=1)

    date1 = today
    date2 = today

    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date_time_jalali = format_datetime_to_shamsi(today)
    date_shamsi = shamsi_date(date1).replace('-', '_')
    date_shamsi2 = shamsi_date(date2).replace('-', '_')

    vet_tokens = list(
        TokenEitaaForEachVet.objects
            .all()
            .only("vet_mobile", "token")
            .values_list('vet_mobile', flat=True)
            .distinct()
    )
    if not vet_tokens:
        return HttpResponse('no vets')

    vet_farms_qs = VetFarm.objects.filter(trash=False, vet__user__mobile__in=vet_tokens) \
        .only("id", "vet__user__mobile", "poultry__id")

    poultry_qs = Poultry.objects.filter(trash=False, id__in=vet_farms_qs.values_list('poultry__id', flat=True)) \
        .only("id", "unit_name", "breeding_unique_id")

    poultry_map = {p.id: p.breeding_unique_id for p in poultry_qs}
    poultry_breeding_ids = set(poultry_map.values())

    vet_farm_pairs = list(vet_farms_qs.values_list('vet__user__mobile', 'poultry__id'))
    breeding_to_vets = {}
    for vet_mobile, poultry_id in vet_farm_pairs:
        breeding = poultry_map.get(poultry_id)
        if breeding:
            breeding_to_vets.setdefault(breeding, set()).add(vet_mobile)

    kill_request_qs = KillHouseRequest.objects.filter(
        trash=False,
        kill_request__recive_date__date__gte=date1,
        kill_request__recive_date__date__lte=date2,
        province_request__poultry_request__poultry__in=poultry_qs
    ).only(
        "bar_code", "accepted_real_quantity", "clearance_code", "quarantine_quantity",
        "quarantine_code_state",
        "kill_request__recive_date",
        "killhouse_user__name",
        "province_request__poultry_request__poultry__unit_name",
    )

    poultry_request_out_qs = PoultryRequest.objects.filter(
        trash=False,
        out=True,
        send_date__date__gte=date1,
        send_date__date__lte=date2,
        poultry__in=poultry_qs
    ).only(
        "order_code", "quantity", "send_date", "quarantine_code",
        "buyer_fullname", "buyer_province", "buyer_city",
        "poultry__unit_name"
    )

    kill_house_request_code_quarantine = list(kill_request_qs.values_list('clearance_code', flat=True).distinct())
    kill_house_free_sale = list(poultry_request_out_qs.filter(quarantine_code__isnull=False)
                                .values_list('quarantine_code', flat=True).distinct())
    result = list(filter(None, kill_house_request_code_quarantine)) + list(filter(None, kill_house_free_sale))

    rsi_url = (
        f'https://rsibackend.rasadyar.com/app/send_different_bar/?province={base_url_for_sms_report}'
        f'&date1={date1}&date2={date2}'
    )
    try:
        rsi_resp = requests.post(rsi_url, json=result, headers={'Content-Type': 'application/json'})
        rsi_data = rsi_resp.json() if rsi_resp.status_code == 200 else []
    except Exception:
        rsi_data = []

    diffrent_rsi_by_vet = {vet: {'in': [], 'out': []} for vet in vet_tokens}

    for data in rsi_data:
        try:
            part_code = data['hatching']['poultry']['PartIdCode']
        except Exception:
            continue
        if part_code not in breeding_to_vets:
            continue
        date_str = str(data.get('Date', '')).split('T')[0]
        try:
            date_n = datetime.strptime(date_str, '%Y-%m-%d').date()
        except Exception:
            continue

        info = 'کد قرنطینه: {0} - حجم: {1} قطعه-مرغدار:{2} - مقصد بار: {3} - تاریخ بار: ({4})'.format(
            data.get('TrackingCode', ''),
            to_locale_str(int(data.get('GoodAmount', 0))),
            data.get('hatching', {}).get('poultry', {}).get('UnitName', ''),
            data.get('DesUnitName', ''),
            shamsi_date(date_n),
        )
        vets_for_part = breeding_to_vets.get(part_code, set())
        for v in vets_for_part:
            if data.get('Out') is False:
                diffrent_rsi_by_vet[v]['in'].append(info)
            else:
                diffrent_rsi_by_vet[v]['out'].append(info)

    for vet_mobile in vet_tokens:
        vet_specific_farms_qs = vet_farms_qs.filter(vet__user__mobile=vet_mobile)
        if not vet_specific_farms_qs.exists():
            continue

        vet_poultry_ids = list(vet_specific_farms_qs.values_list('poultry__id', flat=True).distinct())

        vet_kill_request = kill_request_qs.filter(
            province_request__poultry_request__poultry__in=vet_poultry_ids
        )
        vet_poultry_request_out = poultry_request_out_qs.filter(poultry__in=vet_poultry_ids)

        base_message = (
            '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
            f'❗{date_time_jalali}❗\n'
            f' #گزارش_بارهای_فاقد_مجوز_از_تاریخ_{date_shamsi}_تا_تاریخ_{date_shamsi2} #\n\n'
            f'➖➖➖➖➖➖➖➖➖➖\n'
        )
        current_message = base_message
        messages = []

        def _add_text(txt):
            nonlocal current_message, messages, base_message
            if not txt:
                return
            if len(current_message) + len(txt) > 4000:
                messages.append(current_message)
                current_message = base_message
            current_message += txt

        in_has_code_qs = vet_kill_request.filter(clearance_code__isnull=False)
        in_no_code_qs = vet_kill_request.filter(clearance_code__isnull=True)
        in_has_code_count = in_has_code_qs.count()
        in_no_code_count = in_no_code_qs.count()

        base_vet_message = 'دامپزشک محترم فارم({0}) گزارش عملکرد بارها به شرح زیر میباشد:\n'.format(
            vet_specific_farms_qs.first()
                .vet.user.fullname if vet_specific_farms_qs.first() else '-')
        _add_text(base_vet_message)
        bars_info = []
        for kill_req in in_no_code_qs:
            try:
                unit_name = kill_req.province_request.poultry_request.poultry.unit_name
            except Exception:
                unit_name = ''
            bars_info.append(
                'کد بار: {0} - حجم: {1} قطعه-مرغدار:{4} - مقصد بار: {2} - تاریخ بار: ({3})'.format(
                    kill_req.bar_code,
                    to_locale_str(int(kill_req.accepted_real_quantity or 0)),
                    getattr(kill_req.killhouse_user, 'name', ''),
                    shamsi_date(kill_req.kill_request.recive_date) if getattr(kill_req.kill_request, 'recive_date',
                                                                              None) else '',
                    unit_name
                )
            )
        bars_details = "\n".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

        diffrent_bars_info = []
        diffrent_qs = in_has_code_qs.filter(~Q(quarantine_quantity=F('quantity')))
        for kill_req in diffrent_qs:
            if kill_req.quarantine_quantity:
                quarantine_quantity = to_locale_str(int(kill_req.quarantine_quantity))
                diffrent_quantity = to_locale_str(
                    int(kill_req.quarantine_quantity) - int(kill_req.accepted_real_quantity))
            else:
                state = getattr(kill_req, 'quarantine_code_state', None)
                if state == 'contradiction':
                    quarantine_quantity = 'مغایرت کد رهگیری'
                elif state == 'noclearance':
                    quarantine_quantity = 'فاقد کد رهگیری'
                elif state == 'notconfirmed':
                    quarantine_quantity = 'عدم تایید راهداری'
                else:
                    quarantine_quantity = 'ادغام'
                diffrent_quantity = 0
            diffrent_bars_info.append(
                'کد بار: {0} - حجم: {1} قطعه-مرغدار:{4} - کد قرنطینه: {2} - استعلام از قرنطینه: ({3})-اختلاف:{6}- تاریخ بار: ({5})'.format(
                    kill_req.bar_code,
                    to_locale_str(int(kill_req.accepted_real_quantity or 0)),
                    kill_req.clearance_code or '',
                    quarantine_quantity,
                    getattr(kill_req.province_request.poultry_request.poultry, 'unit_name', ''),
                    shamsi_date(kill_req.kill_request.recive_date) if getattr(kill_req.kill_request, 'recive_date',
                                                                              None) else '',
                    diffrent_quantity
                )
            )
        diffrent_bars_details = "\n".join([f"{i + 1}. {info}" for i, info in enumerate(diffrent_bars_info)])

        new_message_part_in = '❗❗ - تعداد بارهای داخل استان دارای مجوز قرنطینه {0} عدد و تعداد بار های فاقد مجوز {1} عدد میباشد.\n\n'.format(
            in_has_code_count, in_no_code_count
        )
        if bars_info:
            new_message_part_in += "بارهای داخل استان فاقد قرنطینه به شرح زیر میباشد:\n"
            new_message_part_in += f"{bars_details}\n"
            new_message_part_in += "--------------------------------\n"
        if diffrent_bars_info:
            new_message_part_in += "از بارهای داخل استان دارای مجوز تعداد {} بار دارای مغایرت در داده هستند:\n".format(
                diffrent_qs.count())
            new_message_part_in += f"{diffrent_bars_details}\n"
            new_message_part_in += "--------------------------------\n"

        rsi_in_list = diffrent_rsi_by_vet.get(vet_mobile, {}).get('in', [])
        if rsi_in_list:
            new_message_part_in += "با توجه به رصد هوش مصنوعی سامانه تعداد {} بار داخل استان در سامانه رصدیار ثبت نشده است:\n".format(
                len(rsi_in_list))
            new_message_part_in += "\n".join([f"{i + 1}. {it}" for i, it in enumerate(rsi_in_list)])
            new_message_part_in += "\n--------------------------------\n"

        new_message_part_in += "\n➖➖➖➖➖➖➖➖➖➖\n"

        _add_text(new_message_part_in)

        out_has_code_count = vet_poultry_request_out.filter(quarantine_code__isnull=False).count()
        out_no_code_qs = vet_poultry_request_out.filter(quarantine_code__isnull=True)
        out_no_code_count = out_no_code_qs.count()

        bars_info_out = []
        for poultry_req in out_no_code_qs:
            bars_info_out.append(
                'کد سفارش: {0} - حجم: {1} قطعه-مرغدار:{4} - خریدار: {2} - استان خریدار:{5} - شهر خریدار:{6} - تاریخ بار: ({3})'.format(
                    poultry_req.order_code,
                    to_locale_str(int(poultry_req.quantity or 0)),
                    poultry_req.buyer_fullname or '',
                    shamsi_date(poultry_req.send_date) if getattr(poultry_req, 'send_date', None) else '',
                    getattr(poultry_req.poultry, 'unit_name', ''),
                    poultry_req.buyer_province or '',
                    poultry_req.buyer_city or '',
                )
            )
        bars_details_out = "\n".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info_out)])

        new_message_part_out = '❗❗ - تعداد بارهای خارج استان دارای مجوز قرنطینه {0} عدد و تعداد بار های فاقد مجوز {1} عدد میباشد.\n\n'.format(
            out_has_code_count, out_no_code_count
        )
        if bars_info_out:
            new_message_part_out += "بارهای خارج استان فاقد قرنطینه به شرح زیر میباشد:\n"
            new_message_part_out += f"{bars_details_out}\n"
            new_message_part_out += "--------------------------------\n"

        rsi_out_list = diffrent_rsi_by_vet.get(vet_mobile, {}).get('out', [])
        if rsi_out_list:
            new_message_part_out += "با توجه به رصد هوش مصنوعی سامانه تعداد {} بار خارج استان در سامانه رصدیار ثبت نشده است:\n".format(
                len(rsi_out_list))
            new_message_part_out += "\n".join([f"{i + 1}. {it}" for i, it in enumerate(rsi_out_list)])
            new_message_part_out += "\n--------------------------------\n"

        new_message_part_out += "\n➖➖➖➖➖➖➖➖➖➖\n"

        _add_text(new_message_part_out)

        if current_message and current_message != base_message:
            messages.append(current_message)

        chat_token = TokenEitaaForEachVet.objects.filter(vet_mobile=vet_mobile).values_list('token', flat=True).first()
        if chat_token and messages:
            for message in messages:
                try:
                    requests.post(url, data={'chat_id': chat_token, 'text': message}, verify=False)
                except Exception:
                    pass
        for message in messages:
            data = {
                'chat_id': chat_id,
                'text': message,
            }
            response = requests.post(url, data=data, verify=False)


def send_all_bar_to_eitaa(request):
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()

    all_kill_house_requests = KillHouseRequest.objects.filter(
        trash=False,
        kill_request__recive_date__date=date
    ).select_related(
        'province_request__poultry_request__poultry__user__city',
        'kill_request__kill_house__kill_house_operator__user',
        'kill_request__kill_house__system_address__city',
        'add_car__driver'
    )

    poultry_ids = all_kill_house_requests.values_list(
        'province_request__poultry_request__poultry__id',
        flat=True
    ).distinct()

    vet_farms = VetFarm.objects.filter(
        trash=False,
        poultry__id__in=poultry_ids
    ).select_related('vet__user', 'poultry')

    vet_to_poultries = {}
    for vet_farm in vet_farms:
        vet_mobile = vet_farm.vet.user.mobile
        if vet_mobile not in vet_to_poultries:
            vet_to_poultries[vet_mobile] = []
        vet_to_poultries[vet_mobile].append(vet_farm.poultry.id)

    if not vet_to_poultries:
        return HttpResponse('هیچ دامپزشکی یافت نشد.')

    for vet_mobile, poultry_list in vet_to_poultries.items():
        chat_id_eitaa = TokenEitaaForEachVet.objects.filter(vet_mobile=vet_mobile).first()

        if not chat_id_eitaa:
            continue

        vet_kill_requests = all_kill_house_requests.filter(
            province_request__poultry_request__poultry__id__in=poultry_list
        )

        if not vet_kill_requests.exists():
            continue

        date_time_jalali = format_datetime_to_shamsi(date)
        date_shamsi = shamsi_date(date).replace('-', '_')

        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
        base_message += f'❗{date_time_jalali}❗\n'
        base_message += f' #گزارش_بارها #{date_shamsi}\n\n'
        base_message += f'تعداد کل بارها: {vet_kill_requests.count()}\n'
        base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

        messages = []
        current_message = base_message
        m = 1

        for entry in vet_kill_requests:
            try:
                main_quantity = entry.accepted_real_quantity
                real_weight = entry.accepted_real_weight
                poultry_name = entry.province_request.poultry_request.poultry.unit_name
                poultry_mobile = entry.province_request.poultry_request.poultry.user.mobile

                city = entry.province_request.poultry_request.poultry.user.city.name
                buyer = entry.kill_request.kill_house.name
                buyer_city = entry.kill_request.kill_house.system_address.city.name
                buyer_mobile = entry.kill_request.kill_house.kill_house_operator.user.mobile
                weight = entry.province_request.poultry_request.Index_weight
                order_code = entry.bar_code
                recive_date = entry.kill_request.recive_date
                recive_date_shamsi = shamsi_date(recive_date) if recive_date else ''
                main_quantity = "{:,}".format(int(main_quantity))
                real_weight = "{:,}".format(int(real_weight))

                driver_name = '-'
                driver_mobile = '-'
                driver_pelak = '-'
                driver_health_code = '-'
                if entry.add_car and entry.add_car.driver:
                    driver_name = entry.add_car.driver.driver_name or '-'
                    driver_mobile = entry.add_car.driver.driver_mobile or '-'
                    driver_pelak = entry.add_car.driver.pelak or '-'
                    driver_health_code = entry.add_car.driver.health_code or '-'

                if entry.province_request.poultry_request.direct_buying == True:
                    province_type = 'خرید مستقیم'
                elif entry.province_request.poultry_request.export == True:
                    province_type = 'فروش به خارج استان'
                else:
                    province_type = 'اتحادیه'

                driver_info = f' - راننده: {driver_name} ({driver_mobile}) پلاک: {driver_pelak} کد حمل: {driver_health_code}'

                new_message_part = f'{m}. کد بار: {order_code} - حجم بار: {main_quantity} قطعه - وزن بار: {real_weight} - میانگین وزن: {weight} - مرغدار: {poultry_name} ({poultry_mobile}) - شهر: {city} - نوع فروش: {province_type} - خریدار: {buyer} ({buyer_mobile}) - شهر خریدار: {buyer_city}{driver_info} - تاریخ بار: ({recive_date_shamsi})\n\n'
                m += 1

                if len(current_message) + len(new_message_part) > 4000:
                    messages.append(current_message)
                    current_message = base_message

                current_message += new_message_part
            except Exception as e:
                continue

        if current_message and current_message != base_message:
            messages.append(current_message)

        chat_id_eitaa_token = chat_id_eitaa.token
        for message in messages:
            try:
                data = {
                    'chat_id': chat_id_eitaa_token,
                    'text': message,
                }
                response = requests.post(url, data=data, verify=False)
            except Exception:
                pass

    return HttpResponse('پیام‌ها ارسال شد.')


def send_all_bar_to_eitaa_cron():
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()

    all_kill_house_requests = KillHouseRequest.objects.filter(
        trash=False,
        kill_request__recive_date__date=date
    ).select_related(
        'province_request__poultry_request__poultry__user__city',
        'kill_request__kill_house__kill_house_operator__user',
        'kill_request__kill_house__system_address__city',
        'add_car__driver'
    )

    poultry_ids = all_kill_house_requests.values_list(
        'province_request__poultry_request__poultry__id',
        flat=True
    ).distinct()

    vet_farms = VetFarm.objects.filter(
        trash=False,
        poultry__id__in=poultry_ids
    ).select_related('vet__user', 'poultry')

    vet_to_poultries = {}
    for vet_farm in vet_farms:
        vet_mobile = vet_farm.vet.user.mobile
        if vet_mobile not in vet_to_poultries:
            vet_to_poultries[vet_mobile] = []
        vet_to_poultries[vet_mobile].append(vet_farm.poultry.id)

    if not vet_to_poultries:
        return

    for vet_mobile, poultry_list in vet_to_poultries.items():
        chat_id_eitaa = TokenEitaaForEachVet.objects.filter(vet_mobile=vet_mobile).first()

        if not chat_id_eitaa:
            continue

        vet_kill_requests = all_kill_house_requests.filter(
            province_request__poultry_request__poultry__id__in=poultry_list
        )

        if not vet_kill_requests.exists():
            continue

        date_time_jalali = format_datetime_to_shamsi(date)
        date_shamsi = shamsi_date(date).replace('-', '_')

        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
        base_message += f'❗{date_time_jalali}❗\n'
        base_message += f' #گزارش_بارها #{date_shamsi}\n\n'
        base_message += f'تعداد کل بارها: {vet_kill_requests.count()}\n'
        base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

        messages = []
        current_message = base_message
        m = 1

        for entry in vet_kill_requests:
            try:
                main_quantity = entry.accepted_real_quantity
                real_weight = entry.accepted_real_weight
                poultry_name = entry.province_request.poultry_request.poultry.unit_name
                poultry_mobile = entry.province_request.poultry_request.poultry.user.mobile

                city = entry.province_request.poultry_request.poultry.user.city.name
                buyer = entry.kill_request.kill_house.name
                buyer_city = entry.kill_request.kill_house.system_address.city.name
                buyer_mobile = entry.kill_request.kill_house.kill_house_operator.user.mobile
                weight = entry.province_request.poultry_request.Index_weight
                order_code = entry.bar_code
                recive_date = entry.kill_request.recive_date
                recive_date_shamsi = shamsi_date(recive_date) if recive_date else ''
                main_quantity = "{:,}".format(int(main_quantity))
                real_weight = "{:,}".format(int(real_weight))

                driver_name = '-'
                driver_mobile = '-'
                driver_pelak = '-'
                driver_health_code = '-'
                if entry.add_car and entry.add_car.driver:
                    driver_name = entry.add_car.driver.driver_name or '-'
                    driver_mobile = entry.add_car.driver.driver_mobile or '-'
                    driver_pelak = entry.add_car.driver.pelak or '-'
                    driver_health_code = entry.add_car.driver.health_code or '-'

                if entry.province_request.poultry_request.direct_buying == True:
                    province_type = 'خرید مستقیم'
                elif entry.province_request.poultry_request.export == True:
                    province_type = 'فروش به خارج استان'
                else:
                    province_type = 'اتحادیه'

                driver_info = f' - راننده: {driver_name} ({driver_mobile}) پلاک: {driver_pelak} کد حمل: {driver_health_code}'

                new_message_part = f'{m}. کد بار: {order_code} - حجم بار: {main_quantity} قطعه - وزن بار: {real_weight} - میانگین وزن: {weight} - مرغدار: {poultry_name} ({poultry_mobile}) - شهر: {city} - نوع فروش: {province_type} - خریدار: {buyer} ({buyer_mobile}) - شهر خریدار: {buyer_city}{driver_info} - تاریخ بار: ({recive_date_shamsi})\n\n'
                m += 1

                if len(current_message) + len(new_message_part) > 4000:
                    messages.append(current_message)
                    current_message = base_message

                current_message += new_message_part
            except Exception as e:
                continue

        if current_message and current_message != base_message:
            messages.append(current_message)

        chat_id_eitaa_token = chat_id_eitaa.token
        for message in messages:
            try:
                data = {
                    'chat_id': chat_id_eitaa_token,
                    'text': message,
                }
                response = requests.post(url, data=data, verify=False)
            except Exception:
                pass

    return HttpResponse('پیام‌ها ارسال شد.')


def send_single_bar_to_eitaa(kill_house_request):
    url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date()

    if not kill_house_request:
        return

    poultry = kill_house_request.province_request.poultry_request.poultry

    vet_farm = VetFarm.objects.filter(
        trash=False,
        poultry=poultry
    ).select_related('vet__user').first()

    if not vet_farm:
        return

    vet_mobile = vet_farm.vet.user.mobile

    chat_id_eitaa = TokenEitaaForEachVet.objects.filter(vet_mobile=vet_mobile).first()

    if not chat_id_eitaa:
        return

    date_time_jalali = format_datetime_to_shamsi(date)
    date_shamsi = shamsi_date(date).replace('-', '_')

    base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗\n'
    base_message += f'❗{date_time_jalali}❗\n'
    base_message += f' #گزارش_بار_جدید #{date_shamsi}\n\n'
    base_message += f'➖➖➖➖➖➖➖➖➖➖\n'

    try:
        main_quantity = kill_house_request.accepted_real_quantity
        real_weight = kill_house_request.accepted_real_weight
        poultry_name = kill_house_request.province_request.poultry_request.poultry.unit_name
        poultry_mobile = kill_house_request.province_request.poultry_request.poultry.user.mobile

        city = kill_house_request.province_request.poultry_request.poultry.user.city.name
        buyer = kill_house_request.kill_request.kill_house.name
        buyer_city = kill_house_request.kill_request.kill_house.system_address.city.name
        buyer_mobile = kill_house_request.kill_request.kill_house.kill_house_operator.user.mobile
        weight = kill_house_request.province_request.poultry_request.Index_weight
        order_code = kill_house_request.bar_code
        main_quantity = "{:,}".format(int(main_quantity))
        real_weight = "{:,}".format(int(real_weight))

        if kill_house_request.province_request.poultry_request.direct_buying == True:
            province_type = 'خرید مستقیم'
        elif kill_house_request.province_request.poultry_request.export == True:
            province_type = 'فروش به خارج استان'
        else:
            province_type = 'اتحادیه'

        message = base_message
        message += f"🟢 مرغدار : {poultry_name} ({poultry_mobile})\n"
        message += f"شهر: {city}\n"
        message += f"کد بار: {order_code}\n"
        message += f"نوع فروش: {province_type}\n"
        message += f" حجم بار :{main_quantity}\n"
        message += f" وزن بار :{real_weight}\n"
        message += f"میانگین وزن : {weight}\n"
        message += f"\n"
        message += f"🔴🔴خریدار : {buyer} ({buyer_mobile})\n"
        message += f"شهر خریدار: {buyer_city}\n"
        message += '\n➖➖➖➖➖➖➖➖➖➖\n'

        chat_id_eitaa_token = chat_id_eitaa.token
        data = {
            'chat_id': chat_id_eitaa_token,
            'text': message,
        }
        response = requests.post(url, data=data, verify=False)

    except Exception as e:
        pass


def send_all_bar_to_eitaa_ticket(request):
    # url = f'https://eitaayar.ir/api/{token}/sendMessage'
    date = datetime.now().date() - timedelta(days=1)

    all_kill_house_requests = KillHouseRequest.objects.filter(
        trash=False,
        kill_request__recive_date__date__gte=date
    ).select_related(
        'province_request__poultry_request__poultry__user__city',
        'kill_request__kill_house__kill_house_operator__user',
        'kill_request__kill_house__system_address__city',
        'add_car__driver'
    )

    poultry_ids = all_kill_house_requests.values_list(
        'province_request__poultry_request__poultry__id',
        flat=True
    ).distinct()

    vet_farms = VetFarm.objects.filter(
        trash=False,
        poultry__id__in=poultry_ids
    ).select_related('vet__user', 'poultry')

    vet_to_poultries = {}
    for vet_farm in vet_farms:
        vet_mobile = vet_farm.vet.user.mobile
        if vet_mobile not in vet_to_poultries:
            vet_to_poultries[vet_mobile] = []
        vet_to_poultries[vet_mobile].append(vet_farm.poultry.id)

    if not vet_to_poultries:
        return

    for vet_mobile, poultry_list in vet_to_poultries.items():
        chat_id_eitaa = TokenEitaaForEachVet.objects.filter(vet_mobile=vet_mobile).first()

        if not chat_id_eitaa:
            continue

        vet_kill_requests = all_kill_house_requests.filter(
            province_request__poultry_request__poultry__id__in=poultry_list
        )

        if not vet_kill_requests.exists():
            continue

        date_time_jalali = format_datetime_to_shamsi(date)
        date_shamsi = shamsi_date(date).replace('-', '_')

        base_message = '🗓📢❗ سامانه رصدیار، زنجیره تامین،تولید و توزیع مرغ گوشتی📢❗'
        base_message += f'***'
        base_message += f'❗{date_time_jalali}❗'
        base_message += f'***'
        base_message += f' #گزارش_بارها #{date_shamsi}'
        base_message += f'***'
        base_message += f'تعداد کل بارها: {vet_kill_requests.count()}'
        base_message += f'***'
        base_message += f'➖➖➖➖➖➖➖➖➖➖'
        base_message += '***'

        messages = []
        current_message = base_message
        m = 1

        for entry in vet_kill_requests:
            try:
                main_quantity = entry.accepted_real_quantity
                real_weight = entry.accepted_real_weight
                poultry_name = entry.province_request.poultry_request.poultry.unit_name
                poultry_mobile = entry.province_request.poultry_request.poultry.user.mobile

                city = entry.province_request.poultry_request.poultry.user.city.name
                buyer = entry.kill_request.kill_house.name
                buyer_city = entry.kill_request.kill_house.system_address.city.name
                buyer_mobile = entry.kill_request.kill_house.kill_house_operator.user.mobile
                weight = entry.province_request.poultry_request.Index_weight
                order_code = entry.bar_code
                recive_date = entry.kill_request.recive_date
                recive_date_shamsi = shamsi_date(recive_date) if recive_date else ''
                main_quantity = "{:,}".format(int(main_quantity))
                real_weight = "{:,}".format(int(real_weight))

                driver_name = '-'
                driver_mobile = '-'
                driver_pelak = '-'
                driver_health_code = '-'
                if entry.add_car and entry.add_car.driver:
                    driver_name = entry.add_car.driver.driver_name or '-'
                    driver_mobile = entry.add_car.driver.driver_mobile or '-'
                    driver_pelak = entry.add_car.driver.pelak or '-'
                    driver_health_code = entry.add_car.driver.health_code or '-'

                if entry.province_request.poultry_request.direct_buying == True:
                    province_type = 'خرید مستقیم'
                elif entry.province_request.poultry_request.export == True:
                    province_type = 'فروش به خارج استان'
                else:
                    province_type = 'اتحادیه'

                driver_info = f' - راننده: {driver_name} ({driver_mobile}) پلاک: {driver_pelak} کد حمل: {driver_health_code}'

                new_message_part = f'{m}. کد بار: {order_code} - حجم بار: {main_quantity} قطعه - وزن بار: {real_weight} - میانگین وزن: {weight} - مرغدار: {poultry_name} ({poultry_mobile}) - شهر: {city} - نوع فروش: {province_type} - خریدار: {buyer} ({buyer_mobile}) - شهر خریدار: {buyer_city}{driver_info} - تاریخ بار: ({recive_date_shamsi}) *** ***'
                m += 1

                if len(current_message) + len(new_message_part) > 4000:
                    messages.append(current_message)
                    current_message = base_message

                current_message += new_message_part
            except Exception as e:
                continue

        if current_message and current_message != base_message:
            messages.append(current_message)

        chat_id_eitaa_token = chat_id_eitaa.token
        # for message in messages:
        #     try:
        user = SystemUserProfile.objects.filter(trash=False, mobile=chat_id_eitaa.vet_mobile).last()
        new_ticket = TicketSupport(
            user=user,
            title="گزارش بارها",
            status='open',
            read_only=True,
            type_ticket='single',
            parent=None,
            last_message='Admin',
        )
        new_ticket.save()
        new_ticket.to_user.add(user)
        msg = MessageSupport(
            ticket=new_ticket,
            message=messages,
            created_by=user,
            sender='Admin'
        )
        msg.save()
                # data = {
                #     'chat_id': chat_id_eitaa_token,
                #     'text': message,
                # }
                # response = requests.post(url, data=data, verify=False)


    return HttpResponse('پیام‌ها ارسال شد.')