from datetime import datetime, timedelta
import utm
from django.contrib.auth.models import User, Group
from django.db.models.functions import Abs
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.worksheet.datavalidation import DataValidation
from openpyxl.utils import get_column_letter
from io import BytesIO

from authentication.sahandsms.sms import USERNAME_SMS_FINANCIAL, PASSWORD_SMS_FINANCIAL, OUT_SMS_PASS, OUT_SMS_USER, \
    PASSWORD_SMS_HAMEDAN, USERNAME_SMS_HAMEDAN
from authentication.sms_management import send_sms_request
from authentication.views import ARTA_URL_CHANGE_MOBILE_NUMBER, ARTA_URL_CHANGE_PASSWORD
from general_urls import base_user_gate_way_id, base_url_for_sms_report
from panel.KillHouse.helpers import kill_house_free_sale_product_warehousing, kill_house_requests_product_warehousing, \
    kill_house_free_buying_product_warehousing, kill_house_allocations_product_warehousing
from panel.ProvinceOperator.helpers import guild_steward_allocations_product_warehousing, \
    guild_steward_free_buying_product_warehousing, guild_steward_free_sale_product_warehousing, \
    guild_steward_product_segmentation
from panel.admin import PROJECT_API_KEY
from panel.convert_date import convert_to_miladi
from panel.helper import UNION_NUMBER, check_mobile_number
from panel.helper_excel import percent_of_losses, shamsi_date, to_locale_str
from panel.models import KillHouseDriver, Poultry, PoultryRequest, Wallet, LastUpdate, \
    KillHouseAssignmentInformation, KillHouseRequest, KillHouse, InternalTransaction, Guilds, Steward, GuildSteward, \
    RolesProducts, StewardAllocation, NewProduct, KillHouseFreeBarInformation, KillHouseFreeSaleBarInformation, \
    ColdHouseAllocations, CityOperatorCheckRequest, KillRequest, StewardFreeBarInformation, \
    StewardFreeSaleBarInformation, ChainAllocation, KillHouseWareHouse, VetFarm, CityOperator, CityGuild, \
    BarDifferenceRequest, PosSegmentation, PosMachineTransactions, WarehouseArchive, ProductsTransactions
from authentication.models import SystemUserProfile, City, Province, ExternalTransaction
import requests
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny
from django.db.models import Q, F, Count, Sum

from panel.poultry.helpers import poultry_prediction
from ticket.models import TicketSupport, MessageSupport

ARTA_REGISTER = "https://userbackend.rasadyar.com/api/register_all/"
from rest_framework.response import Response
import hashlib


# pk_assigment = [4990, 4991, 4992, 4385, 4386, 4387, 4447, 4448, 4449, 4839, 4840, 5084, 5109, 5111, 3875, 4895, 4897,
#                 4899, 4900, 4901, 4902, 4530, 4531, 4532, 4533, 4534, 4583, 4585, 4630, 4632, 4635, 4034, 3130, 3132,
#                 4707, 4708, 4709, 4710, 4711, 3173, 3174, 3176, 3177, 3178, 3179, 3180]
#
# pk_kill_house_request = [12291, 12289, 12288, 11568, 11569, 11567, 11669, 11667, 11671, 12053, 12055, 12368, 12401,
#                          12421, 10918, 12124, 12136, 12135, 12137, 12132, 12134, 11734, 11731, 11732, 11733, 11735,
#                          11779, 11782, 11875, 11873, 11871, 11142, 10104, 10106, 11886, 11887, 11889, 11891, 11893,
#                          10084, 10085, 10080, 10082, 10075, 10077, 10116]
#
# pk_province_kill_request = [4289, 4275, 4275, 4041, 4041, 4038, 4076, 4076, 4055, 4195, 4195, 4316, 4334, 4335, 3811, 4215,
#                          4217, 4217, 4217, 4218, 4218, 4104,
#                          4104, 4104, 4104, 4104, 4114, 4114, 4136, 4136, 4148, 3877, 3546, 3545, 4151, 4151, 4151, 4151,
#                          4151, 3530, 3530, 3542, 3542, 3535, 3535, 3542]
#
# pk_hatching = [1273, 1251, 1251, 1206, 1206, 1252, 1247, 1247, 1206, 1203, 1203, 1276, 1307, 1249, 1143, 1281, 1232,
#                1232, 1232, 1273, 1273, 1240,
#                1240, 1240, 1240, 1240, 1234, 1234, 1200, 1200, 1247, 1186, 1085, 1098, 1251, 1251, 1251, 1251, 1251,
#                1336, 1336, 1113, 1113, 1253, 1253, 1113]
#


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def create_driver_excel_template(request):
    """
    ایجاد فایل اکسل قالب برای ثبت راننده‌ها
    پارامتر: kill_house_ids - لیست id کشتارگاه‌ها (کاما جدا شده)
    """
    # دریافت id های کشتارگاه از پارامترهای درخواست
    kill_house_ids_param = request.GET.get('kill_house_ids', '')

    if kill_house_ids_param:
        kill_house_ids = [int(x.strip()) for x in kill_house_ids_param.split(',') if x.strip()]
        kill_houses = KillHouse.objects.filter(trash=False, id__in=kill_house_ids)
    else:
        kill_houses = KillHouse.objects.filter(trash=False)

    # ساخت workbook
    workbook = openpyxl.Workbook()
    worksheet = workbook.active
    worksheet.title = "رانندگان"
    worksheet.sheet_view.rightToLeft = True

    # تعریف هدرهای اکسل
    headers = [
        'کشتارگاه',
        'مدل خودرو',
        'نوع خودرو',
        'پلاک خودرو',
        'کد بهداشتی حمل',
        'تاریخ اعتبار بهداشتی',
        'ظرفیت خودرو(قفس)',
        'کد ملی راننده',
        'شماره تماس راننده',
        'ملاحظات'
    ]

    # استایل‌ها
    header_fill = PatternFill(start_color="1E487B", fill_type="solid")
    header_font = Font(size=11, bold=True, color="FFFFFF")
    header_alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    thin_border = Border(
        left=Side(style='thin'),
        right=Side(style='thin'),
        top=Side(style='thin'),
        bottom=Side(style='thin')
    )

    # نوشتن هدرها
    for col_num, header in enumerate(headers, 1):
        cell = worksheet.cell(row=1, column=col_num, value=header)
        cell.fill = header_fill
        cell.font = header_font
        cell.alignment = header_alignment
        cell.border = thin_border
        worksheet.column_dimensions[get_column_letter(col_num)].width = 18

    # تنظیم عرض ستون‌ها
    worksheet.column_dimensions['A'].width = 30  # کشتارگاه
    worksheet.column_dimensions['D'].width = 22  # پلاک خودرو
    worksheet.column_dimensions['F'].width = 20  # تاریخ اعتبار بهداشتی
    worksheet.column_dimensions['J'].width = 25  # ملاحظات

    # ارتفاع ردیف هدر
    worksheet.row_dimensions[1].height = 25

    # ایجاد شیت جدید برای لیست کشتارگاه‌ها
    kill_house_sheet = workbook.create_sheet(title="لیست کشتارگاه‌ها")
    kill_house_sheet.sheet_view.rightToLeft = True

    # هدر شیت کشتارگاه‌ها
    kill_house_headers = ['شناسه (ID)', 'نام کشتارگاه']
    for col_num, header in enumerate(kill_house_headers, 1):
        cell = kill_house_sheet.cell(row=1, column=col_num, value=header)
        cell.fill = header_fill
        cell.font = header_font
        cell.alignment = header_alignment
        cell.border = thin_border

    kill_house_sheet.column_dimensions['A'].width = 15
    kill_house_sheet.column_dimensions['B'].width = 35

    # لیست برای dropdown
    kill_house_list = []

    # پر کردن لیست کشتارگاه‌ها
    for row_num, kill_house in enumerate(kill_houses, 2):
        # فرمت: "id - نام کشتارگاه"
        display_value = f"{kill_house.id} - {kill_house.name or 'بدون نام'}"
        kill_house_list.append(display_value)

        kill_house_sheet.cell(row=row_num, column=1, value=kill_house.id).border = thin_border
        kill_house_sheet.cell(row=row_num, column=2, value=kill_house.name or 'بدون نام').border = thin_border

    # ایجاد dropdown برای ستون کشتارگاه
    if kill_house_list:
        # اگر تعداد کشتارگاه‌ها زیاد باشد، از reference به شیت دیگر استفاده می‌کنیم
        if len(kill_house_list) <= 100:
            # استفاده از لیست مستقیم
            dv = DataValidation(
                type="list",
                formula1='"' + ','.join(kill_house_list) + '"',
                allow_blank=True
            )
        else:
            # استفاده از reference به شیت کشتارگاه‌ها
            dv = DataValidation(
                type="list",
                formula1=f"'لیست کشتارگاه‌ها'!$A$2:$A${len(kill_house_list) + 1}",
                allow_blank=True
            )

        dv.error = 'لطفاً از لیست کشتارگاه‌ها انتخاب کنید'
        dv.errorTitle = 'ورودی نامعتبر'
        dv.prompt = 'یک کشتارگاه از لیست انتخاب کنید'
        dv.promptTitle = 'انتخاب کشتارگاه'

        # اضافه کردن validation به ستون اول (کشتارگاه) برای 1000 ردیف
        dv.add('A2:A1001')
        worksheet.add_data_validation(dv)

    # ذخیره فایل در BytesIO
    output = BytesIO()
    workbook.save(output)
    output.seek(0)

    # ارسال فایل به عنوان response
    response = HttpResponse(
        content=output.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = 'attachment; filename="driver_template.xlsx"'

    return response


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def upload_driver_excel(request):
    from panel.models import KillHouseADDCAR

    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Driver")

    success_count = 0
    error_list = []

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i == 1:
            continue

        try:
            kill_house_value = row[0]
            type_car = row[2]  # مدل خودرو
            pelak = row[3]  # پلاک خودرو
            health_code = row[4]  # کد بهداشتی حمل
            health_code_expiry = row[5]  # تاریخ اعتبار بهداشتی
            capacity = row[6]  # ظرفیت خودرو (قفس)
            national_code = row[7]  # کد ملی راننده
            driver_mobile = row[8]  # شماره تماس راننده
            notes = row[9] if len(row) > 9 else None  # ملاحظات

            kill_house_id = None
            if kill_house_value:
                if isinstance(kill_house_value, int):
                    kill_house_id = kill_house_value
                elif isinstance(kill_house_value, str):
                    if ' - ' in str(kill_house_value):
                        kill_house_id = int(str(kill_house_value).split(' - ')[0].strip())
                    else:
                        kill_house_id = int(kill_house_value)

            kill_house = None
            if kill_house_id:
                kill_house = KillHouse.objects.filter(trash=False, id=kill_house_id).first()

            driver_mobile = str(driver_mobile) if driver_mobile else None
            if driver_mobile and len(driver_mobile) <= 10:
                driver_mobile = '0' + driver_mobile

            if not driver_mobile:
                error_list.append(f"ردیف {i + 1}: شماره تماس راننده خالی است")
                continue

            driver_name = ""
            if kill_house:
                existing_drivers_count = KillHouseADDCAR.objects.filter(
                    trash=False,
                    kill_house=kill_house,
                    archive=False
                ).count()

                kill_house_name = kill_house.name or f"کشتارگاه {kill_house.id}"
                driver_number = existing_drivers_count + 1
                driver_name = f"راننده {kill_house_name} {driver_number}"

            system_profile = None
            try:
                system_profile = SystemUserProfile.objects.get(trash=False, mobile=driver_mobile)
                if group not in system_profile.role.all():
                    system_profile.role.add(group)

                if not system_profile.first_name and driver_name:
                    system_profile.first_name = driver_name
                    system_profile.fullname = driver_name
                    system_profile.save()

            except SystemUserProfile.DoesNotExist:
                password = '123456'
                hashed_password = hashlib.sha256(str(password).encode()).hexdigest()

                data = {
                    "username": driver_mobile,
                    "first_name": driver_name,
                    "last_name": "",
                    "password": hashed_password,
                    "national_code": str(national_code) if national_code else "",
                    "role": "Driver",
                    "api_key": PROJECT_API_KEY
                }
                req = requests.post(
                    url=ARTA_REGISTER,
                    data=data,
                    verify=False
                )

                if req.status_code == 200:
                    user = User(username=driver_mobile, first_name=driver_name, last_name="", password=hashed_password)
                    user.save()

                    base_id = SystemUserProfile.objects.all()
                    if base_id.count() > 0:
                        base_id = int(base_id.last().base_order) + 1
                    else:
                        base_id = 1000

                    province_obj = None
                    city_obj = None
                    if kill_house and kill_house.system_address:
                        province_obj = kill_house.system_address.province
                        city_obj = kill_house.system_address.city

                    system_profile = SystemUserProfile(
                        mobile=driver_mobile,
                        first_name=driver_name,
                        last_name="",
                        fullname=driver_name,
                        user=user,
                        base_order=base_id,
                        password=password,
                        national_code=str(national_code) if national_code else None,
                        city=city_obj,
                        province=province_obj
                    )
                    system_profile.save()
                    system_profile.role.add(group)
                else:
                    error_list.append(f"ردیف {i + 1}: خطا در ثبت کاربر در سیستم مرکزی")
                    continue

            province_name = None
            province_number = 0
            city_name = None
            city_number = 0

            if kill_house:
                province_name = kill_house.province_name
                province_number = kill_house.province_number or 0
                city_name = kill_house.city_name
                city_number = kill_house.city_number or 0

            driver = KillHouseDriver(
                type_car=str(type_car) if type_car else None,
                type='exclusive',
                capocity=str(capacity) if capacity else None,
                pelak=str(pelak) if pelak else None,
                health_code=str(health_code) if health_code else None,
                driver_name=driver_name,
                driver_mobile=driver_mobile,
                user=system_profile,
            )
            driver.save()

            if kill_house:
                if not KillHouseADDCAR.objects.filter(
                        trash=False,
                        kill_house=kill_house,
                        driver=driver,
                        archive=False
                ).exists():
                    add_car = KillHouseADDCAR(
                        kill_house=kill_house,
                        driver=driver,
                        kill_house_id_foreign_key=kill_house.id,
                        driver_id_foreign_key=driver.id,
                        province_name=province_name,
                        province_number=province_number,
                        city_name=city_name,
                        city_number=city_number
                    )
                    add_car.save()

            success_count += 1

        except Exception as e:
            error_list.append(f"ردیف {i + 1}: {str(e)}")
            continue

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


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_driver_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Driver")

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        first_name = row[1]
        last_name = row[2]
        mobile = row[3]
        birthday = row[4]
        province = row[5]
        city = row[6]
        password = row[7]
        national_code = row[8]
        car = row[9]
        capacity = row[10]
        plaque = row[11]
        health_code = row[12]
        hashed_password = hashlib.sha256(str(password).encode()).hexdigest()

        province = Province.objects.filter(name=province)
        province = province.last()
        city = City.objects.filter(name=city)
        city = city.last()

        if i == 0:
            continue
        mobile = str(mobile)
        if len(mobile) <= 10:
            mobile = '0' + mobile
        try:
            system_profile = SystemUserProfile.objects.get(trash=False, mobile=mobile)
            if 'Driver' not in system_profile.role.all():
                system_profile.role.add(group)

        except:

            data = {
                "username": mobile,
                "first_name": first_name,
                "last_name": last_name,
                "password": hashed_password,
                "national_code": national_code,
                "role": "Driver",
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                system_profile = SystemUserProfile(
                    mobile=mobile,
                    first_name=first_name,
                    last_name=last_name,
                    fullname=first_name + '' + last_name,
                    user=user,
                    base_order=base_id,
                    password=password,
                    birthday=birthday,
                    city=city,
                    province=province
                )
                system_profile.save()
                system_profile.role.add(group)

            else:
                return Response({"result": "مشکلی پیش آمده!"}, status=status.HTTP_401_UNAUTHORIZED)

        if KillHouseDriver.objects.filter(trash=False, user=system_profile, health_code=health_code,
                                          pelak=plaque).exists():
            continue
        else:
            driver = KillHouseDriver(
                type_car=car,
                capocity=capacity,
                pelak=plaque,
                health_code=health_code,
                driver_name=first_name + '' + last_name,
                driver_mobile=mobile,
                user=system_profile,
            )
            driver.save()

    return Response({"result": "register"}, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_poultry_hatching_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename='BytesIO(file)', data_only=True)
    sheet = wb_obj.active
    sheet.delete_rows(sheet.max_row)

    not_find_list = []

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        breeding_uniq_id = row[4]
        licence_number = row[7]
        hatching_quantity = row[11]
        poultry_name = row[5]
        losses = row[22]
        if i <= 6:
            continue

        poultry = Poultry.objects.filter(trash=False, breeding_unique_id=breeding_uniq_id).first()

        if not poultry:
            not_find_list.append(breeding_uniq_id)
            continue
        poultry.unit_name = poultry_name
        poultry.save()
        hatch = PoultryHatching.objects.filter(trash=False, poultry=poultry).order_by('id')
        if hatch:
            period = hatch.last().period + 1
        else:
            period = 1

        hatching_date = row[9].split('/')
        date = convert_to_miladi(
            year=int(hatching_date[0]),
            month=int(hatching_date[1]),
            day=int(hatching_date[2])
        )

        poultry_hatching = hatch.filter(trash=False, archive=False, state='pending',
                                        allow_hatching='pending').order_by('id')

        if not poultry_hatching.exists():
            if not hatch.filter(archive=True, state='complete',
                                allow_hatching="True", licence_number=licence_number).exists():
                hatching = PoultryHatching(
                    poultry=poultry,
                    date=date,
                    quantity=hatching_quantity,
                    breed=[
                        {"breed": 'آرین', "main_quantity": hatching_quantity, "remain_quantity": hatching_quantity}],
                    period=period,
                    chicken_breed='*ترکیبی',
                    hall=1,
                    left_over=hatching_quantity,
                    latest_hatching_change={
                        "role": "UnitWindow",
                        "date": str(datetime.now().date()),
                        "full_name": ""
                    },
                    licence_number=licence_number,
                    breeding_unique_id=breeding_uniq_id,
                    losses=losses

                )
                hatching.save()

        else:
            previouse_hatching = poultry_hatching.last()

            hatchings = poultry_hatching.filter(licence_number=licence_number)
            if not hatchings:
                if previouse_hatching.left_over > (previouse_hatching.quantity * percent_of_losses):
                    previouse_hatching.violation = True
                    previouse_hatching.save()

                hatching = PoultryHatching(
                    poultry=poultry,
                    date=date,
                    quantity=hatching_quantity,
                    breed=[
                        {"breed": 'آرین', "main_quantity": hatching_quantity, "remain_quantity": hatching_quantity}],
                    period=period,
                    chicken_breed='*ترکیبی',
                    hall=1,
                    left_over=hatching_quantity,
                    latest_hatching_change={
                        "role": "UnitWindow",
                        "date": str(datetime.now().date()),
                        "full_name": ""
                    },
                    licence_number=licence_number,
                    breeding_unique_id=breeding_uniq_id,
                    losses=losses

                )
                hatching.save()
            else:
                last_hatchings = hatchings.first()
                last_hatchings.date = date
                last_hatchings.quantity = hatching_quantity
                last_hatchings.losses = losses
                last_hatchings.save()

        update = LastUpdate.objects.first()
        update.update_date = datetime.now()
        update.save()
    return Response(not_find_list, status=status.HTTP_201_CREATED)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def check_poultry_hatching_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    inter = []
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        breeding_uniq_id = row[3]

        if i == 7:
            continue
        poultry = Poultry.objects.filter(trash=False, breeding_unique_id=breeding_uniq_id)
        if poultry:
            poultry = poultry.last()
        else:
            continue
        poultry_hatching = PoultryHatching.objects.filter(trash=False, poultry=poultry, state='pending')
        for poultry_hatchings in poultry_hatching:
            dict_1 = {
                "poultry": poultry_hatchings.poultry.unit_name,
                "date": poultry_hatchings.date,
                "quantity": poultry_hatchings.quantity,
                "breed": poultry_hatchings.chicken_breed,

            }
            inter.append(dict_1)
            # dict_1.clear()

    return Response(inter, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def check_poultry_in_db(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    list1 = []
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        try:
            poultry = Poultry.objects.get(breeding_unique_id=row[6])
            if poultry:
                continue
        except:
            dict1 = {
                'نام مرغدار': row[0],
                'شناسه یکتا': row[6]
            }
            list1.append(dict1)
    return Response(list1, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def reset_hatching_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    l = 0
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 7:
            continue
        date = row[8].split('/')
        miladi_date = convert_to_miladi(
            year=int(date[0]),
            month=int(date[1]),
            day=int(date[2])
        )
        poultrys = Poultry.objects.filter(trash=False, breeding_unique_id=row[3])
        # return HttpResponse(poultrys.count())
        if poultrys:
            for poultry in poultrys:
                poultry_hatchings = PoultryHatching.objects.filter(poultry=poultry, date__year=miladi_date.year,
                                                                   date__month=miladi_date.month,
                                                                   date__day=miladi_date.day,
                                                                   archive=False, trash=False, state='pending',
                                                                   allow_hatching='pending')
                if poultry_hatchings:
                    for poultry_hatching in poultry_hatchings:
                        l += 1
                        if poultry_hatching.quantity - poultry_hatching.left_over == 0:
                            poultry_hatching.quantity = row[9]
                            poultry_hatching.left_over = row[9]
                            poultry_hatching.save()
                        else:
                            continue

                else:
                    continue
    return Response(l)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def enter_driver_hamedan(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Driver")
    l = 0
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 2:
            continue
        mobile = str(row[2])
        if len(mobile) == 10:
            mobile = '0' + str.zfill(mobile, 10)
        health_code = 0
        if row[8] is not None:
            health_code = row[8]
        first_name = row[0]
        last_name = [1]
        password = '00100'
        hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
        province = Province.objects.filter(name='همدان')
        province = province.last()
        city = City.objects.filter(name='همدان')
        city = city.last()

        system_profile = SystemUserProfile.objects.filter(mobile=mobile, trash=False).last()
        if not system_profile:
            data = {
                "username": mobile,
                "first_name": first_name,
                "last_name": last_name,
                "password": hashed_password,
                "national_code": '0',
                "role": "Driver",
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                system_profile = SystemUserProfile(
                    mobile=mobile,
                    first_name=first_name,
                    last_name=last_name,
                    fullname=first_name + '' + last_name,
                    user=user,
                    base_order=base_id,
                    password=password,
                    birthday=str(datetime.now().date()),
                    city=city,
                    province=province
                )
                system_profile.save()
                system_profile.role.add(group)
                l += 1
        kill_drivers = KillHouseDriver.objects.filter(trash=False, health_code=health_code, user__mobile=mobile,
                                                      driver_mobile=mobile)
        if not kill_drivers:
            wallet = Wallet()
            wallet.save()
            KillHouseDriver(
                user=system_profile,
                driver_name=first_name + ' ' + last_name,
                driver_mobile=mobile,
                type_car='کامیون',
                type='exclusive',
                pelak=row[9],
                capocity=row[7],
                health_code=health_code,
                wallet=wallet,
            )
            l += 1
    return Response(l)


def add_zero_for_user_mobile(request):
    users = SystemUserProfile.objects.all()
    l = 0
    for user in users:
        if len(user.mobile) == 10:
            user.mobile = '0' + user.mobile
            user.save()
            l += 1

    return HttpResponse(l, status=status.HTTP_200_OK)


def integration_of_hatching(request):
    poultry = Poultry.objects.filter(trash=False)
    for user in poultry:
        poultry_hatching = PoultryHatching.objects.filter(trash=False, poultry=user, archive=False,
                                                          allow_hatching='pending').order_by('id')
        if poultry_hatching:
            first_hatching = poultry_hatching.first()
            for hatching in poultry_hatching:
                if first_hatching != hatching:
                    first_hatching.quantity += hatching.quantity
                    first_hatching.left_over += hatching.left_over
                    first_hatching.killed_quantity += hatching.killed_quantity
                    p_requests = PoultryRequest.objects.filter(trash=False, hatching=hatching)
                    if p_requests:
                        for p_request in p_requests:
                            p_request.hatching = first_hatching
                            p_request.save()
                    hatching.trash = True
                    hatching.save()
                    first_hatching.save()
        else:
            pass
    return HttpResponse('ok')


def period_to_fix(request):
    poultries = Poultry.objects.filter(trash=False).order_by('id')

    for poultry in poultries:
        hatch = PoultryHatching.objects.filter(trash=False, poultry=poultry).order_by('id')
        # if len(hatch) > 1:
        #     period = len(hatch) + 1
        # else:
        period = 1
        for hatching in hatch:
            hatching.period = period
            hatching.save()
            period += 1
    return HttpResponse('ok')


# from panel.models import KillHouseAssignmentInformation, KillHouseRequest
#
#
# def assignment_information_fix_bar_info(request):
#     kill_request=KillHouseRequest.objects.filter(trash=False,accepted_real_quantity=0,accepted_real_weight=0).select_related('province_request__poultry_request').only('accepted_real_weight','accepted_real_quantity','province_request__poultry_request')
#     for kill in kill_request:
#         kill.accepted_real_quantity=kill.quantity
#         kill.accepted_real_weight=int(kill.quantity * kill.province_request.poultry_request.Index_weight)
#         kill.save()
#
#     return HttpResponse('ok')


# from panel.models import ProvinceKillRequest, KillHouseRequest
# from django.db.models import Sum
# def assignment_information_fix_bar_info(request):
#     province = ProvinceKillRequest.objects.filter(total_killed_quantity=0,trash=False,state__in=('pending','accepted'))
#
#     for p in province:
#         p.total_killed_quantity=p.main_quantity
#         p.total_killed_weight=int(p.main_quantity * p.province_request.poultry_request.Index_weight)
#         p.save()
#     return HttpResponse('ok')


# from panel.models import KillHouseAssignmentInformation, KillHouseRequest
#
#
# def assignment_information_fix_bar_info(request):
#     kill_request=KillHouseRequest.objects.filter(trash=False,accepted_real_quantity=0,accepted_real_weight=0).select_related('province_request__poultry_request')
#     for kill in kill_request:
#         kill.accepted_real_quantity=kill.quantity
#         kill.accepted_real_weight=int(kill.quantity * kill.province_request.poultry_request.Index_weight)
#         kill.save()
#
#     return HttpResponse('ok')
#
#
# def assignment_information_fix_bar_info(request):
#     bar_information = KillHouseAssignmentInformation.objects.filter(trash=False).only(
#         'net_weight', 'real_quantity', 'kill_house_request__key').values('net_weight', 'real_quantity',
#                                                                          'kill_house_request__key')
#
#     for bar in bar_information:
#         try:
#             kill_request = KillHouseRequest.objects.get(trash=False, key=bar['kill_house_request__key'])
#
#             kill_request.accepted_real_quantity = bar['real_quantity']
#             kill_request.accepted_real_weight = bar['net_weight']
#             kill_request.save()
#         except:
#             pass
#
#
#     return HttpResponse('ok')

#
# from panel.models import KillHouseAssignmentInformation, KillHouseRequest
# #
# #
# def assignment_information_fix_bar_info(request):
#     bar_information = KillHouseAssignmentInformation.objects.filter(pk__in=pk_assigment,trash=False).select_related('kill_house_request')
#     for bar in bar_information:
#         try:
#             kill_request = KillHouseRequest.objects.get(trash=False, key=bar.kill_house_request.key)
#
#             kill_request.accepted_real_quantity = bar.real_quantity
#             kill_request.accepted_real_weight = bar.net_weight
#             kill_request.save()
#         except:
#             pass
#
#     return HttpResponse(len(bar_information))
#
# from panel.models import ProvinceKillRequest, KillHouseRequest
# from django.db.models import Sum
#
#
# def assignment_information_fix_bar_info(request):
#     province = ProvinceKillRequest.objects.filter(trash=False,state__in=('pending','accepted'))
#
#     for p in province:
#         kill_request = KillHouseRequest.objects.filter(trash=False, province_kill_request=p).only(
#             'accepted_real_quantity', 'accepted_real_weight')
#         total_killed_quantity = kill_request.aggregate(total=Sum('accepted_real_quantity'))[
#             'total']
#         total_killed_weight = kill_request.aggregate(total=Sum('accepted_real_weight'))[
#             'total']
#
#         total_first_car = kill_request.aggregate(total=Sum('quantity'))[
#             'total']
#
#         p.total_killed_quantity = total_killed_quantity if total_killed_quantity != None else 0
#         p.total_killed_weight = total_killed_weight if total_killed_weight != None else 0
#         p.first_car_allocated_quantity= total_first_car if total_first_car != None else 0
#
#         if p.main_quantity < p.total_killed_quantity:
#             p.extra_killed_quantity = p.total_killed_quantity - p.main_quantity
#
#         p.save()
#
#         p.quantity=p.main_quantity - p.first_car_allocated_quantity if(p.main_quantity - p.first_car_allocated_quantity) > 0 else 0
#         p.save()
#     return HttpResponse('ok')

# from panel.models import ProvinceKillRequest, PoultryHatching
# from django.db.models import Sum
#
#
# def assignment_information_fix_bar_info(request):
#     hatchings = PoultryHatching.objects.filter(trash=False).order_by('id')
#
#     for hatching in hatchings:
#         province_kills = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
#                                                             province_request__poultry_request__hatching=hatching).order_by(
#             'id')
#
#         total_extra = province_kills.aggregate(total=Sum('extra_killed_quantity'))[
#             'total']
#
#         total_killed_quantity = province_kills.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_weight = province_kills.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#
#         hatching.killed_quantity = total_killed_quantity if total_killed_quantity != None else 0
#         hatching.total_killed_weight = total_killed_weight if total_killed_weight != None else 0
#
#         province_kill_free = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=True)
#         total_killed_free_quantity = province_kill_free.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_free_weight = province_kill_free.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.free_quantity = total_killed_free_quantity if total_killed_free_quantity != None else 0
#         hatching.free_killed_quantity = total_killed_free_weight if total_killed_free_weight != None else 0
#
#         province_kill_goverment = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=False)
#
#         total_killed_goverment_quantity = province_kill_goverment.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_goverment_weight = province_kill_goverment.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.governmental_quantity = total_killed_goverment_quantity if total_killed_goverment_quantity != None else 0
#         hatching.governmental_killed_quantity = total_killed_goverment_weight if total_killed_goverment_weight != None else 0
#
#         hatching.extra_killed_quantity = total_extra if total_extra != None else 0
#
#         hatching.save()
#     return HttpResponse('ok')


# from panel.models import ProvinceKillRequest, PoultryHatching
# from django.db.models import Sum
# from panel.models import ProvinceKillRequest, KillHouseRequest
#
#
# def assignment_information_fix_bar_info(request):
#     list1 = [1336,1146,1120,1253,1141,1098,1112,1145,1163,1155,1134,1087,1172,1072,1113,1089,1115,1072,1123,1085,1109]
#
#     hatchings = PoultryHatching.objects.filter(trash=False, id__in=list1)
#
#     province = ProvinceKillRequest.objects.filter(trash=False,state__in=('accepted','pending') ,province_request__poultry_request__hatching__in=hatchings)
#     for p in province:
#         kill_requests=KillHouseRequest.objects.filter(trash=False,province_kill_request=p)
#         total_killed_quantity = kill_requests.aggregate(total=Sum('accepted_real_quantity'))[
#                     'total']
#         total_killed_weight = kill_requests.aggregate(total=Sum('accepted_real_weight'))[
#             'total']
#         total_car = kill_requests.aggregate(total=Sum('quantity'))[
#             'total']
#         p.total_killed_quantity=total_killed_quantity if total_killed_quantity !=None else 0
#         p.total_killed_weight=total_killed_weight if total_killed_weight !=None else 0
#         p.first_car_allocated_quantity=total_car if total_car != None else 0
#
#         if p.main_quantity < p.total_killed_quantity:
#             p.extra_killed_quantity = p.total_killed_quantity - p.main_quantity
#
#         p.save()
#     for hatching in hatchings:
#         province_kills = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
#                                                                     province_request__poultry_request__hatching=hatching).order_by(
#                     'id')
#
#         total_extra = province_kills.aggregate(total=Sum('extra_killed_quantity'))[
#             'total']
#
#         total_killed_quantity = province_kills.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_weight = province_kills.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#
#         hatching.killed_quantity = total_killed_quantity if total_killed_quantity != None else 0
#         hatching.total_killed_weight = total_killed_weight if total_killed_weight != None else 0
#
#         province_kill_free = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=True)
#         total_killed_free_quantity = province_kill_free.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_free_weight = province_kill_free.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.free_quantity = total_killed_free_quantity if total_killed_free_quantity != None else 0
#         hatching.free_killed_quantity = total_killed_free_weight if total_killed_free_weight != None else 0
#
#         province_kill_goverment = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=False)
#
#         total_killed_goverment_quantity = province_kill_goverment.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_goverment_weight = province_kill_goverment.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.governmental_quantity = total_killed_goverment_quantity if total_killed_goverment_quantity != None else 0
#         hatching.governmental_killed_quantity = total_killed_goverment_weight if total_killed_goverment_weight != None else 0
#
#         hatching.extra_killed_quantity = total_extra if total_extra != None else 0
#
#         hatching.save()
#
#
#     return HttpResponse('ok')
#
# from panel.models import ProvinceKillRequest, PoultryHatching
# from django.db.models import Sum
# from panel.models import ProvinceKillRequest, KillHouseRequest
# def assignment_information_fix_bar_info_3_day_ago(request):
#     date=datetime.now().date() - timedelta(days=3)
#     kill_house_reqs = KillHouseRequest.objects.filter(Q(vet_state= 'pending')|Q(assignment_state_archive='pending')
#                                                       ,clearance_code__isnull=True,kill_request__recive_date__date__lte=date, trash=False)
#
#     list1=[]
#     for kill_house_req in kill_house_reqs:
#         kill_house_req.trash = True
#         kill_house_req.save()
#         hatching = PoultryHatching.objects.get(key=kill_house_req.province_request.poultry_request.hatching.key, trash=False)
#         if hatching.id not in list1:
#             list1.append(hatching.id)
#
#     hatchings = PoultryHatching.objects.filter(trash=False, id__in=list1)
#
#     province = ProvinceKillRequest.objects.filter(trash=False,state__in=('accepted','pending') ,province_request__poultry_request__hatching__in=hatchings)
#     for p in province:
#         kill_requests=KillHouseRequest.objects.filter(trash=False,province_kill_request=p)
#         total_killed_quantity = kill_requests.aggregate(total=Sum('accepted_real_quantity'))[
#                     'total']
#         total_killed_weight = kill_requests.aggregate(total=Sum('accepted_real_weight'))[
#             'total']
#         total_car = kill_requests.aggregate(total=Sum('quantity'))[
#             'total']
#         p.total_killed_quantity=total_killed_quantity if total_killed_quantity !=None else 0
#         p.total_killed_weight=total_killed_weight if total_killed_weight !=None else 0
#         p.first_car_allocated_quantity=total_car if total_car != None else 0
#
#         if p.main_quantity < p.total_killed_quantity:
#             p.extra_killed_quantity = p.total_killed_quantity - p.main_quantity
#
#         p.save()
#     for hatching in hatchings:
#         province_kills = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
#                                                                     province_request__poultry_request__hatching=hatching).order_by(
#                     'id')
#
#         total_extra = province_kills.aggregate(total=Sum('extra_killed_quantity'))[
#             'total']
#
#         total_killed_quantity = province_kills.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_weight = province_kills.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#
#         hatching.killed_quantity = total_killed_quantity if total_killed_quantity != None else 0
#         hatching.total_killed_weight = total_killed_weight if total_killed_weight != None else 0
#
#         province_kill_free = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=True)
#         total_killed_free_quantity = province_kill_free.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_free_weight = province_kill_free.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.free_quantity = total_killed_free_quantity if total_killed_free_quantity != None else 0
#         hatching.free_killed_quantity = total_killed_free_weight if total_killed_free_weight != None else 0
#
#         province_kill_goverment = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=False)
#
#         total_killed_goverment_quantity = province_kill_goverment.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_goverment_weight = province_kill_goverment.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.governmental_quantity = total_killed_goverment_quantity if total_killed_goverment_quantity != None else 0
#         hatching.governmental_killed_quantity = total_killed_goverment_weight if total_killed_goverment_weight != None else 0
#
#         hatching.extra_killed_quantity = total_extra if total_extra != None else 0
#
#         hatching.save()
#
#
#     return HttpResponse('ok')

# def assignment_information_fix_bar_info(request):
#     kill_house_requests=(KillHouseRequest.objects.filter(trash=True,clearance_code__isnull=True,message__isnull=False,
#                                                         bar_remover__isnull=False)).only('message')
#     for kill_house_request in kill_house_requests:
#         kill_house_request.message='عدم دریافت کد قرنطینه'
#         # kill_house_request.bar_remover={
#         #     "date": str(kill_house_request.create_date.date()),
#         #     "role":"KillHouse",
#         #     "mobile": kill_house_request.killhouse_user.kill_house_operator.user.mobile,
#         #     "full_name": kill_house_request.killhouse_user.kill_house_operator.user.fullname,
#         # }
#         kill_house_request.save()
#     return HttpResponse('ok')
#
from panel.models import ProvinceKillRequest, PoultryHatching


# def assignment_information_fix_bar_info(request):
#     today = datetime.now().date() - timedelta(days=2)
#     province_kill_requests = (ProvinceKillRequest.objects.filter(kill_request__recive_date__date__lte=today,
#                                                                  first_car_allocated_quantity=0, trash=False)
#                               .select_related('province_request__poultry_request'))
#     if province_kill_requests:
#         for province_kill_request in province_kill_requests:
#             poultry_request = PoultryRequest.objects.get(key=province_kill_request.province_request.poultry_request.key,
#                                                          trash=False)
#             hatching = PoultryHatching.objects.get(key=poultry_request.hatching.key, trash=False)
#
#             if province_kill_request.main_quantity - province_kill_request.quantity == 0:
#                 province_check = ProvinceCheckOperatorRequest.objects.get(poultry_request=poultry_request)
#                 province_check.quantity += province_kill_request.main_quantity
#                 province_check.save()
#                 poultry_request.remain_quantity += province_kill_request.main_quantity
#                 poultry_request.save()
#
#                 if poultry_request.free_sale_in_province == True:
#                     hatching.free_killed_quantity -= province_kill_request.total_killed_weight
#                     hatching.free_quantity -= province_kill_request.total_killed_quantity
#                 else:
#                     hatching.governmental_killed_quantity -= province_kill_request.total_killed_weight
#                     hatching.governmental_quantity -= province_kill_request.total_killed_quantity
#
#                 hatching.save()
#                 province_kill_request.quantity = 0
#                 province_kill_request.total_killed_quantity = 0
#                 province_kill_request.total_killed_weight = 0
#                 province_kill_request.return_to_province = True
#                 province_kill_request.save()
#     return HttpResponse({'msg': 'all done'})


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

            # if not Product.objects.filter(guild__exact=guild):
            #     l+=1
            #
            #     additional_products = AdditionalProducts.objects.filter(trash=False).exclude(
            #         name='سایر محصولات').order_by('id')
            #     if additional_products:
            #         for additional_product in additional_products:
            #             show = True if additional_product.name == 'مرغ گرم' else False
            #             product = Product(
            #                 name=additional_product.name,
            #                 image=additional_product.image,
            #                 unit_of_measurement=additional_product.unit_of_measurement,
            #                 priority=additional_product.priority,
            #                 guild=guild,
            #                 selling_free_price=additional_product.selling_free_price,
            #                 selling_approved_price=additional_product.selling_approved_price,
            #                 selling_more_than_inventory=additional_product.selling_more_than_inventory,
            #                 selling_other_products=additional_product.selling_other_products,
            #                 price=additional_product.price,
            #                 show=show,
            #             )
            #             product.save()
            # company = PosCompany.objects.get(id=1)
            # pos_machine=POSMachine.objects.filter(guild__exact=guild).first()
            # if not pos_machine:
            #     while (True):
            #         res = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
            #         res = base_pos_id + res
            #         if not POSMachine.objects.filter(pos_id=res).exists():
            #             break
            #     pos_machine=POSMachine(
            #         pos_id=res,
            #         user=guild.user,
            #         guild=guild,
            #         pos_company=company
            #     )
            #     pos_machine.save()
            #     guild.has_pos = True
            #     guild.save()
            #     l+=1
    # return Response(l)


# from panel.models import ProvinceKillRequest, PoultryHatching
# from django.db.models import Sum
# from panel.models import ProvinceKillRequest, KillHouseRequest
# def assignment_information_fix_bar_info(request):
#     hatchings = PoultryHatching.objects.filter(trash=False, pk__in=pk_hatching)
#
#     province = ProvinceKillRequest.objects.filter(trash=False ,pk__in=pk_province_kill_request )
#     for p in province:
#         kill_requests=KillHouseRequest.objects.filter(trash=False,province_kill_request=p)
#         total_killed_quantity = kill_requests.aggregate(total=Sum('accepted_real_quantity'))[
#                     'total']
#         total_killed_weight = kill_requests.aggregate(total=Sum('accepted_real_weight'))[
#             'total']
#         total_car = kill_requests.aggregate(total=Sum('quantity'))[
#             'total']
#         p.total_killed_quantity=total_killed_quantity if total_killed_quantity !=None else 0
#         p.total_killed_weight=total_killed_weight if total_killed_weight !=None else 0
#         p.first_car_allocated_quantity=total_car if total_car != None else 0
#
#         if p.main_quantity < p.total_killed_quantity:
#             p.extra_killed_quantity = p.total_killed_quantity - p.main_quantity
#
#         p.save()
#     for hatching in hatchings:
#         province_kills = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
#                                                                     province_request__poultry_request__hatching=hatching).order_by(
#                     'id')
#
#         total_extra = province_kills.aggregate(total=Sum('extra_killed_quantity'))[
#             'total']
#
#         total_killed_quantity = province_kills.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_weight = province_kills.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#
#         hatching.killed_quantity = total_killed_quantity if total_killed_quantity != None else 0
#         hatching.total_killed_weight = total_killed_weight if total_killed_weight != None else 0
#
#         province_kill_free = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=True)
#         total_killed_free_quantity = province_kill_free.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_free_weight = province_kill_free.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.free_quantity = total_killed_free_quantity if total_killed_free_quantity != None else 0
#         hatching.free_killed_quantity = total_killed_free_weight if total_killed_free_weight != None else 0
#
#         province_kill_goverment = province_kills.filter(
#             province_request__poultry_request__free_sale_in_province=False)
#
#         total_killed_goverment_quantity = province_kill_goverment.aggregate(total=Sum('total_killed_quantity'))[
#             'total']
#         total_killed_goverment_weight = province_kill_goverment.aggregate(total=Sum('total_killed_weight'))[
#             'total']
#         hatching.governmental_quantity = total_killed_goverment_quantity if total_killed_goverment_quantity != None else 0
#         hatching.governmental_killed_quantity = total_killed_goverment_weight if total_killed_goverment_weight != None else 0
#
#         hatching.extra_killed_quantity = total_extra if total_extra != None else 0
#
#         hatching.save()
#
#
#     return HttpResponse('ok')


def update_chicken_age_from_login():
    poultry_hatching = PoultryHatching.objects.filter(trash=False).only('date', 'chicken_age', 'last_change').order_by(
        '-id')
    now = datetime.now().date()
    for hatching in poultry_hatching:
        now_age = (now - hatching.date.date()).days + 1
        if hatching.archive == False and hatching.allow_hatching == 'pending':
            hatching.chicken_age = now_age
            hatching.save()
        elif hatching.archive == True and hatching.allow_hatching == 'True':
            if hatching.last_change:
                date = datetime.strptime((hatching.last_change['date'].split(' ')[0]), '%Y-%m-%d').date()
                age = (date - hatching.date.date()).days + 1
                if age < 80:
                    hatching.chicken_age = (date - hatching.date.date()).days + 1
                    hatching.save()
        else:
            continue
        if now_age <= 120:
            hatching.now_age = now_age
            hatching.save()


def violation_archive_true(request):
    poultry_haching = PoultryHatching.objects.filter(allow_hatching='True', archive=True,
                                                     trash=False, left_over__gt=F('quantity') * percent_of_losses,
                                                     violation=False).only('quantity', 'left_over', 'violation')
    l = 0
    for hatching in poultry_haching:
        hatching.violation = True
        hatching.save()
        l += 1
    return HttpResponse(l)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def update_chicken_breed_from_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file), data_only=True)
    sheet = wb_obj.active

    sheet.delete_rows(sheet.max_row)
    done = 0
    not_done = 0

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 7:
            continue
        breeding_uniq_id = row[3]
        breed = row[10]
        licence_number = row[5]
        try:
            poultry_hatching = PoultryHatching.objects.filter(violation=False, trash=False, allow_hatching='pending',
                                                              state='pending',
                                                              poultry__breeding_unique_id=breeding_uniq_id,
                                                              licence_number=licence_number).order_by(
                'id').last()

            if poultry_hatching:
                if poultry_hatching.chicken_breed == '*ترکیبی':
                    poultry_hatching.chicken_breed = breed
                elif poultry_hatching.chicken_breed != breed and poultry_hatching.chicken_breed != '*ترکیبی':
                    poultry_hatching.chicken_breed = 'ترکیبی'
                else:
                    continue

            poultry_hatching.save()
            done += 1
        except:
            not_done += 1
            continue
            # hatching.save()
    return Response(f'موفق:{done}\n ناموفق ها:{not_done}', status=status.HTTP_201_CREATED)


def ye_chee_bani(request):
    kill_assigment = KillHouseAssignmentInformation.objects.filter(
        ~Q(real_quantity=F('kill_house_request__accepted_real_quantity'))).select_related('kill_house_request')

    list1 = kill_assigment.values_list('kill_house_request__province_request__poultry_request__hatching__pk', flat=True)
    # print(list(list1))
    return HttpResponse(list(list1))


def dedicated_killer(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    l = 0
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 1:
            continue
        bar_code = row[1]
        mobile = str(row[12])
        if len(mobile) == 10:
            mobile = '0' + str.zfill(mobile, 10)
        try:
            kill_req = KillHouseRequest.objects.get(bar_code=bar_code)
            killer = KillHouse.objects.get(kill_house_operator__user__mobile=mobile)
            kill_req.killer = killer
            kill_req.save()
        except:
            l += 1
            continue
    return HttpResponse(l)


def valem_kin2(request):
    kill_req = KillHouseRequest.objects.filter(archive_wage=True, create_date__date__gte='2024-03-20').only(
        'archive_wage').order_by('id')
    m = kill_req.values_list('pk', flat=True)
    print(len(m))
    for i in kill_req:
        i.archive_wage = False
        i.save()
    # kill_req = ProvinceKillRequest.objects.filter(archive_wage=True, create_date__date__gte='2024-03-20').only(
    #     'archive_wage').order_by('id')
    # for i in kill_req:
    #     i.archive_wage = False
    #     i.save()

    # kill_req = KillHouseFreeBarInformation.objects.filter(archive_wage=False, create_date__date__lte='2024-04-19').only(
    #     'archive_wage').order_by('id')
    # for i in kill_req:
    #     i.archive_wage = True
    #     i.save()

    return HttpResponse('ok')


def transaction_company_for_freezing(request):
    poultry_request = PoultryRequest.objects.filter(trash=False, freezing=True).order_by('id')
    province_request = ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                          state__in=('pending', 'accepted')
                                                          , archive_wage=False,
                                                          province_request__poultry_request__in=poultry_request).only(
        'total_killed_weight', 'total_wage_amount', 'company_share', 'wage', 'company_share_percent'
    )
    for p in province_request:
        amount = int(p.total_killed_weight * 500)
        p.total_wage_amount = amount
        p.wage = 500
        p.company_share = amount
        p.guilds_share = 0
        p.union_share = 0
        p.company_share_percent = 100
        p.union_share_percent = 0
        p.guilds_share_percent = 0
        p.save()

    return HttpResponse('ok')


import string
import random


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def make_gate_way_id(request):
    users = SystemUserProfile.objects.filter(user_gate_way_id__isnull=True).order_by('id')
    for user in users:
        while (True):
            res = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
            res = base_user_gate_way_id + res
            if not SystemUserProfile.objects.filter(user_gate_way_id=res).exists():
                break
        user.user_gate_way_id = res
        user.save()
    return HttpResponse('done!')


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def get_server_time(request):
    date = datetime.now()
    return Response(date)


def transaction_fix(request):
    province_request = ProvinceKillRequest.objects.filter(trash=False, return_to_province=False,
                                                          state__in=('pending', 'accepted')
                                                          , archive_wage=False,
                                                          ).only(
        'total_killed_weight', 'total_wage_amount', 'company_share', 'wage', 'company_share_percent', 'other_share',
        'other_share_percent'
    ).exclude(id=3868)
    for p in province_request:
        amount = p.total_wage_amount

        p.guilds_share = amount - (p.company_share + p.union_share)
        p.save()

    return HttpResponse('ok')


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def internal_transaction_fix(request):
    internals = InternalTransaction.objects.filter(trash=False, status='completed', date__date__gt='2024-06-01'
                                                   , transaction_type='wage-gateway-auto') \
        .order_by('date')
    for internal in internals:
        if internal.amount != (
                internal.company_share + internal.guilds_share + internal.union_share + internal.other_share):
            internal.company_share = internal.company_share + ((internal.amount * 1) / 100)
            internal.save()

    return Response('ok')


def utm_to_loc(easting, northing):
    zone_number = 39
    zone_letter = 'N'
    lat, lon = utm.to_latlon(easting, northing, zone_number, zone_letter)
    zone_number = int((lon + 180) // 6) + 1
    zone_letter = 'CDEFGHJKLMNPQRSTUVWXX'[(int(lat) + 80) // 8]
    lat, lon = utm.to_latlon(easting, northing, zone_number, zone_letter)

    return lat, lon


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def convert_utm_to_location(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    list1 = []
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 1:
            continue
        else:
            utm = row[14]
            breeding_uniq_id = row[5]
            utm = utm.split('/')
            easting = int(utm[0])
            northing = int(utm[1])
            lat, long = utm_to_loc(easting, northing)
            poultry = Poultry.objects.filter(trash=False, breeding_unique_id=breeding_uniq_id).first()
            if poultry:
                poultry.lat = lat
                poultry.long = long
                poultry.save()
            else:
                list1.append(breeding_uniq_id)

    return HttpResponse('ok')


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def fix_internal_transactions(request):
    internal = InternalTransaction.objects.filter(trash=False, kill_house__isnull=False)
    for i in internal:
        i.payer_fullname = i.kill_house.kill_house_operator.user.fullname
        i.payer_mobile = i.kill_house.kill_house_operator.user.mobile
        i.save()
    return Response('ok')


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_hatching(request):
    poultryes = Poultry.objects.filter(trash=False)
    list1 = []

    for p in poultryes:
        # پیدا کردن تاریخ‌هایی که دوبار یا بیشتر تکرار شده‌اند
        repeated_dates = PoultryHatching.objects.values('date__year', 'date__month').annotate(
            date_count=Count('id')
        ).filter(trash=False, poultry=p, date_count__gt=1)

        # فیلتر کردن رکوردهایی که سال و ماه آنها در لیست تکراری‌ها قرار دارند
        query = Q()
        for date in repeated_dates:
            query |= Q(date__year=date['date__year'], date__month=date['date__month'])

        poultry_hatchings = PoultryHatching.objects.filter(query, trash=False, poultry=p, killed_quantity=0)
        # for p in poultry_hatchings:
        #     p.trash=True
        #     p.save()

    return Response(list1)


def change_last_digit_to_six(request):
    user_profile = SystemUserProfile.objects.filter(trash=False, mobile='09216919296').order_by('id')
    for u in user_profile:
        first_mobile_number = u.mobile
        second_mobile_number = '09011110911'
        data = {
            "first_mobile_number": str(first_mobile_number),
            "second_mobile_number": '09011110911',
        }
        req = requests.post(
            url=ARTA_URL_CHANGE_MOBILE_NUMBER,
            data=data,
            verify=False
        )
        # return Response(req.status_code)
        if req.status_code == 200:
            print('ok')
            second_mobile_number = second_mobile_number

            user = User.objects.filter(id=u.user.id).first()
            user.username = second_mobile_number
            user.save()
            u.mobile = second_mobile_number
            u.save()
    return HttpResponse('ok')


def canceled_out_province_request():
    province_requests = PoultryRequest.objects.filter(state_process__in=('accepted', 'pending'),
                                                      province_state__in=('accepted', 'pending'), trash=False,
                                                      archive=False,
                                                      out_province_request_cancel=False, out=True, wage_pay=False,
                                                      has_wage=True)
    data = {"date": str(datetime.now()), "role": "SuperAdmin", "mobile": "-",
            "fullname": "کنسل شده توسط سیستم به دلیل عدم پرداخت"}
    for province_request in province_requests:
        if province_request.state_process == 'accepted' and province_request.province_state == 'accepted':
            hatching = PoultryHatching.objects.get(key=province_request.hatching.key, trash=False)
            hatching.out_province_killed_weight -= int(province_request.quantity * province_request.Index_weight)
            hatching.out_province_killed_quantity -= province_request.quantity
            hatching.save()
        province_request.out_province_request_cancel = True
        province_request.out_province_request_canceller = data
        province_request.archive = True
        province_request.state_process = 'rejected'
        province_request.province_state = 'rejected'
        province_request.save()

        message = f'بار خارج از استان به شماره {province_request.order_code} به علت عدم پرداخت کنسل شد.' \
                  f'\n' \
                  f'(سامانه رصدیار)'
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={UNION_NUMBER}&message={message}")


def fix_guild_kill_house(request):
    guilds = Guilds.objects.filter(trash=False, kill_house_centers_allocation__isnull=False)
    for guild in guilds:
        list1 = []
        for i in guild.kill_house_centers_allocation:
            list1.append(i['value'])
        kill_house1 = KillHouse.objects.filter(key__in=list1)
        guild.kill_house.set(kill_house1)

    return HttpResponse('ok')


def fix_guild_steward_kill_house(request):
    stewards = Steward.objects.filter(trash=False, centers_allocation__isnull=False)
    for steward in stewards:
        guild = Guilds.objects.get(trash=False, id=steward.guilds.id)
        list1 = []
        for i in steward.centers_allocation:
            list1.append(i['value'])
        kill_house1 = KillHouse.objects.filter(key__in=list1)
        guild.steward_kill_house.set(kill_house1)

    return HttpResponse('ok')


def fix_guild_steward(request):
    guild = Guilds.objects.get(id=26, trash=False)
    stewards = guild.stewards.all()
    list1 = [i['value'] for i in guild.centers_allocation]

    # واکشی مباشرین مرتبط
    stewardss = Guilds.objects.filter(
        pk__in=Steward.objects.filter(key__in=list1).values_list('guilds', flat=True),
        trash=False
    )

    # حذف رابطه‌های قبلی در مدل میانی
    GuildSteward.objects.filter(guild=guild).delete()

    # اضافه کردن روابط جدید در مدل میانی
    guild_stewards = [GuildSteward(guild=guild, steward=steward) for steward in stewardss]
    GuildSteward.objects.bulk_create(guild_stewards)

    return HttpResponse('done!')


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def check_product(request):
    product = RolesProducts.objects.get(id=1)
    return Response(kill_house_free_sale_product_warehousing(product))


def add_to_steward_temp_key(request):
    stewards_allocations = StewardAllocation.objects.filter(steward__isnull=False).order_by('id')
    for stewards_allocation in stewards_allocations:
        stewards_allocation.steward_temp_key = stewards_allocation.steward.guilds.id
        stewards_allocation.save()
    return HttpResponse('ok')


def add_to_steward(request):
    stewards_allocations = StewardAllocation.objects.filter(steward_temp_key__isnull=False).order_by('id')
    for stewards_allocation in stewards_allocations:
        guild = Guilds.objects.get(id=stewards_allocation.steward_temp_key)
        stewards_allocation.steward = guild
        stewards_allocation.save()
    return HttpResponse('ok')


def make_role_prodoct(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False).order_by('id')
    guilds = Guilds.objects.filter(trash=False)
    product = NewProduct.objects.all().first()
    for kill_house in kill_houses:
        role_product = RolesProducts(
            kill_house=kill_house,
            parent_product=product,
            name='مرغ گرم',
        )
        role_product.save()
    for guild in guilds:
        role_product = RolesProducts(
            guild=guild,
            parent_product=product,
            name='مرغ گرم',
        )
        role_product.save()

    return HttpResponse('ok')


def fix_steward_allocation(request):
    steward_allocations = StewardAllocation.objects.filter(kill_house__isnull=False).order_by('id')
    for steward_allocation in steward_allocations:
        product = RolesProducts.objects.filter(kill_house=steward_allocation.kill_house).first()
        if steward_allocation.guilds is not None:
            steward_allocation.to_guilds = steward_allocation.guilds
            steward_allocation.allocation_type = 'killhouse_guild'
            steward_allocation.guilds = None
        elif steward_allocation.steward is not None:
            steward_allocation.to_steward = steward_allocation.steward
            steward_allocation.allocation_type = 'killhouse_steward'
            steward_allocation.steward = None
        else:
            continue
        steward_allocation.product = product

        steward_allocation.save()
    return HttpResponse('ok')


def fix_KillHouseFreeSaleBarInformation(request):
    free_kills = KillHouseFreeSaleBarInformation.objects.filter(trash=False, kill_house__isnull=False).order_by('id')
    for free_kill in free_kills:
        product = RolesProducts.objects.filter(kill_house=free_kill.kill_house).first()
        free_kill.product = product
        free_kill.save()
    return HttpResponse('ok')


def fix_KillHouseFreeBarInformation(request):
    free_kills = KillHouseFreeBarInformation.objects.filter(trash=False, kill_house__isnull=False).order_by('id')
    for free_kill in free_kills:
        product = RolesProducts.objects.filter(kill_house=free_kill.kill_house).first()
        free_kill.product = product
        free_kill.save()
    return HttpResponse('ok')


# @api_view(["GET"])
# @permission_classes([AllowAny])
# @csrf_exempt
# def kill_house_requests_product_warehousing(request):
#     kill_house=KillHouse.objects.get(id=int(request.GET['id']))
#     product=RolesProducts.objects.get(kill_house=kill_house)
#     kill_house_requests = KillHouseRequest.objects.filter(killhouse_user=product.kill_house,
#                                                           ware_house_confirmation=True, trash=False,calculate_status=True)
#
#     governmental_kill_house_requests = kill_house_requests.filter(province_request__poultry_request__free_sale_in_province=False)
#     free_kill_house_requests = kill_house_requests.filter(province_request__poultry_request__free_sale_in_province=True)
#     # governmental_kill_house_requests = kill_house_requests.filter(
#     #     province_request__poultry_request__free_sale_in_province=False,
#     #     province_request__poultry_request__direct_buying=False)
#     # free_kill_house_requests = kill_house_requests.filter(
#     #     Q(province_request__poultry_request__free_sale_in_province=True) | Q(
#     #         province_request__poultry_request__direct_buying=True))
#     product.province_governmental_carcasses_quantity = \
#         governmental_kill_house_requests.aggregate(total=Sum('ware_house_accepted_real_quantity'))['total'] or 0
#     product.province_governmental_carcasses_weight = \
#     governmental_kill_house_requests.aggregate(total=Sum('ware_house_accepted_real_weight'))[
#         'total'] or 0
#     product.province_free_carcasses_quantity = \
#         free_kill_house_requests.aggregate(total=Sum('ware_house_accepted_real_quantity'))['total'] or 0
#     product.province_free_carcasses_weight = \
#     free_kill_house_requests.aggregate(total=Sum('ware_house_accepted_real_weight'))[
#         'total'] or 0
#
#     product.save()
#     return Response("done!")


# @api_view(["GET"])
# @permission_classes([AllowAny])
# @csrf_exempt
# def kill_house_free_buying_product_warehousing(request):
#     kill_house=KillHouse.objects.get(id=int(request.GET['id']))
#     product=RolesProducts.objects.get(kill_house=kill_house)
#     kill_house_free_buying_bars = KillHouseFreeBarInformation.objects.filter(kill_house=product.kill_house, trash=False,calculate_status=True)
#     product.free_buying_carcasses_quantity = \
#         kill_house_free_buying_bars.aggregate(total=Sum('number_of_carcasses'))['total'] or 0
#     product.free_buying_carcasses_weight = \
#         kill_house_free_buying_bars.aggregate(total=Sum('weight_of_carcasses'))[
#             'total'] or 0
#     product.save()
#     return Response("done!")

@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def kill_house_cold_house_allocations_product_warehousing(request):
    kill_house = KillHouse.objects.get(id=int(request.GET['id']))
    product = RolesProducts.objects.get(kill_house=kill_house)
    cold_house_allocations = ColdHouseAllocations.objects.filter(kill_house=product.kill_house,
                                                                 state__in=('pending', 'accepted'),
                                                                 trash=False)

    product.freezing_quantity = cold_house_allocations.aggregate(total=Sum('real_quantity'))[
                                    'total'] or 0
    product.freezing_weight = cold_house_allocations.aggregate(total=Sum('real_weight'))[
                                  'total'] or 0
    product.save()
    return Response("done!")


# @api_view(["GET"])
# @permission_classes([AllowAny])
# @csrf_exempt
# def kill_house_allocations_product_warehousing(request):
#     kill_house=KillHouse.objects.get(id=int(request.GET['id']))
#     product=RolesProducts.objects.get(kill_house=kill_house)
#     kill_house_allocations = StewardAllocation.objects.filter(
#         Q(kill_house=product.kill_house) | Q(to_kill_house=product.kill_house), trash=False,calculate_status=True)
#     kill_house_allocated = kill_house_allocations.filter(kill_house__isnull=False)
#     kill_house_allocated_from = kill_house_allocations.filter(kill_house__isnull=True)
#     governmental_kill_house_allocated_from = kill_house_allocated_from.filter(approved_price_status=True)
#     free_kill_house_allocated_from = kill_house_allocated_from.filter(approved_price_status=False)
#
#
#     product.province_allocated_quantity = kill_house_allocated.filter(receiver_state__in=('pending', 'accepted')).aggregate(
#         total=Sum('real_number_of_carcasses'))[
#                                           'total'] or 0
#     product.province_allocated_weight = kill_house_allocated.filter(receiver_state__in=('pending', 'accepted')).aggregate(
#         total=Sum('real_weight_of_carcasses'))[
#                                         'total'] or 0
#
#     product.receive_governmental_carcasses_quantity = \
#         governmental_kill_house_allocated_from.filter(receiver_state='accepted').aggregate(
#             total=Sum('receiver_real_number_of_carcasses'))[
#             'total'] or 0
#     product.receive_governmental_carcasses_weight = \
#         governmental_kill_house_allocated_from.filter(receiver_state='accepted').aggregate(
#             total=Sum('receiver_real_weight_of_carcasses'))[
#             'total'] or 0
#
#
#     product.receive_free_carcasses_quantity = \
#         free_kill_house_allocated_from.filter(receiver_state='accepted').aggregate(
#             total=Sum('receiver_real_number_of_carcasses'))[
#             'total'] or 0
#     product.receive_free_carcasses_weight = \
#         free_kill_house_allocated_from.filter(receiver_state='accepted').aggregate(
#             total=Sum('receiver_real_weight_of_carcasses'))[
#             'total'] or 0
#
#     product.save()
#     return Response("done!")
#


# @api_view(["GET"])
# @permission_classes([AllowAny])
# @csrf_exempt
# def kill_house_free_sale_product_warehousing(request):
#     kill_house=KillHouse.objects.get(id=int(request.GET['id']))
#     product=RolesProducts.objects.get(kill_house=kill_house)
#     kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(kill_house=product.kill_house,
#
#                                                                                trash=False,calculate_status=True)
#
#     product.out_province_allocated_quantity = kill_house_free_sale_bars.aggregate(total=Sum('real_number_of_carcasses'))[
#                                      'total'] or 0
#     product.out_province_allocated_weight = kill_house_free_sale_bars.aggregate(total=Sum('real_weight_of_carcasses'))[
#                                    'total'] or 0
#     # return ({"len(1)":product.out_province_allocated_quantity,"2":product.out_province_allocated_weight})
#     product.save()
#     return Response("done!")
#


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def check_kill_house_request_calculate(request):
    check_date = '2024-06-01'
    check_date = datetime.strptime(check_date, '%Y-%m-%d').date()
    kill_house_requests = KillHouseRequest.objects.filter(kill_request__recive_date__date__lt=check_date, trash=False)
    for kill_house_request in kill_house_requests:
        kill_house_request.calculate_status = False
        kill_house_request.save()
    return Response("done!")


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def check_kill_house_free_bar_information_calculate(request):
    check_date = '2024-06-01'
    check_date = datetime.strptime(check_date, '%Y-%m-%d').date()
    kill_house_free_bars = KillHouseFreeBarInformation.objects.filter(date__date__lt=check_date, trash=False)
    for kill_house_free_bar in kill_house_free_bars:
        kill_house_free_bar.calculate_status = False
        kill_house_free_bar.save()
    return Response("done!")


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def check_kill_house_free_sale_bar_information_calculate(request):
    check_date = '2024-06-01'
    check_date = datetime.strptime(check_date, '%Y-%m-%d').date()
    kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(date__date__lt=check_date, trash=False)
    for kill_house_free_sale_bar in kill_house_free_sale_bars:
        kill_house_free_sale_bar.calculate_status = False
        kill_house_free_sale_bar.save()
    return Response("done!")


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def check_steward_allocations_calculate(request):
    check_date = '2024-06-01'
    check_date = datetime.strptime(check_date, '%Y-%m-%d').date()
    steward_allocations = StewardAllocation.objects.filter(date__date__lt=check_date, trash=False)
    for steward_allocation in steward_allocations:
        steward_allocation.calculate_status = False
        steward_allocation.save()
    return Response("done!")


def update_trash_status(model, filter_kwargs):
    """
    به‌روزرسانی فیلدهای `trash`, `temporary_trash` و `temporary_deleted` برای یک مدل مشخص.
    """
    queryset = model.objects.filter(**filter_kwargs).only('temporary_deleted', 'trash', 'temporary_trash')
    for item in queryset:
        if item.trash == True:
            item.temporary_deleted = True
        item.trash = True
        item.temporary_trash = True
        item.save()


def temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (PoultryRequest, {"send_date__date__lt": check_date}),
        (CityOperatorCheckRequest, {"poultry_request__send_date__date__lt": check_date}),
        (KillRequest, {"recive_date__date__lt": check_date}),
        (ProvinceKillRequest, {"kill_request__recive_date__date__lt": check_date}),
        (KillHouseRequest, {"kill_request__recive_date__date__lt": check_date}),
        (KillHouseAssignmentInformation, {"kill_house_request__kill_request__recive_date__date__lt": check_date}),
        (KillHouseFreeBarInformation, {"date__date__lt": check_date}),
        (KillHouseFreeSaleBarInformation, {"date__date__lt": check_date}),
        (StewardAllocation, {"date__date__lt": check_date}),
        (ColdHouseAllocations, {"date__date__lt": check_date}),
        (StewardFreeBarInformation, {"date__date__lt": check_date}),
        (StewardFreeSaleBarInformation, {"date__date__lt": check_date}),
        (InternalTransaction, {"date__date__lt": check_date}),
        (ExternalTransaction, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def PoultryRequest_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (PoultryRequest, {"send_date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def CityOperatorCheckRequest_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (CityOperatorCheckRequest, {"poultry_request__send_date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def KillRequest_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (KillRequest, {"recive_date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def ProvinceKillRequest_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (ProvinceKillRequest, {"kill_request__recive_date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def KillHouseRequest_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (KillHouseRequest, {"kill_request__recive_date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def KillHouseAssignmentInformation_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (KillHouseAssignmentInformation, {"kill_house_request__kill_request__recive_date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def KillHouseFreeBarInformation_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (KillHouseFreeBarInformation, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def StewardAllocation_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (StewardAllocation, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def ColdHouseAllocations_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (ColdHouseAllocations, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def StewardFreeBarInformation_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (StewardFreeBarInformation, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def StewardFreeSaleBarInformation_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (StewardFreeSaleBarInformation, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def InternalTransaction_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (InternalTransaction, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def ExternalTransaction_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (ExternalTransaction, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def ChainAllocation_temporary_trash_true(request):
    check_date = datetime.strptime('2024-11-10', '%Y-%m-%d').date()

    models_and_filters = [
        (ChainAllocation, {"date__date__lt": check_date}),
    ]

    for model, filter_kwargs in models_and_filters:
        update_trash_status(model, filter_kwargs)

    return HttpResponse('ok')


def archive_hatching_temporary_true(request):
    filtered_poultry_hatch = PoultryHatching.objects.filter(
        Q(allow_hatching='True', state='complete') | Q(archive=True))
    for filtered_poultry in filtered_poultry_hatch:
        if filtered_poultry.trash == True:
            filtered_poultry.temporary_deleted = True
        filtered_poultry.trash = True
        filtered_poultry.temporary_trash = True
        filtered_poultry.save()
    return HttpResponse('ok')


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def duplicate_order_code(request):
    from django.db.models import Count

    duplicate_order_codes = PoultryRequest.objects.values('order_code').annotate(count=Count('id')).filter(count__gt=1,
                                                                                                           trash=False).values_list(
        'order_code', flat=True)

    return Response(duplicate_order_codes)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_duplicate_order_code(request):
    duplicate_order_codes = (
        PoultryRequest.objects
            .values('order_code')
            .annotate(count=Count('id'))
            .filter(count__gt=1, trash=False)
            .values_list('order_code', flat=True)
    )

    # استخراج شناسه‌های مرغ‌های مرتبط با کدهای تکراری
    poultry_ids = (
        PoultryRequest.objects
            .filter(order_code__in=duplicate_order_codes, trash=False)
            .values_list('poultry__id', flat=True)
            .distinct()
    )

    # مرتب‌سازی مرغ‌ها بر اساس شناسه
    poultries = Poultry.objects.filter(trash=False, id__in=poultry_ids).order_by('id')
    list1 = []
    # بررسی درخواست‌های مرتبط با هر مرغ
    for poultry in poultries:
        requests = PoultryRequest.objects.filter(trash=False, poultry=poultry).order_by('order_code')
        base_order_code = str(poultry.user.base_order)  # فرض بر این است که "user" به درستی تعریف شده است
        last_order = []
        for req in requests:
            if str(req.order_code)[:4] == base_order_code:
                last_order.clear()
                last_order.append(req.order_code)
            # if str(req.order_code)[:4] != base_order_code:
            #     list1.append(req.id)
        if last_order:
            last_num = last_order[0] + 1
            for req in requests:
                if str(req.order_code)[:4] != base_order_code:
                    base_order_code = last_num
                    req.order_code = base_order_code
                    req.save()
                    last_num += 1
            last_order.clear()

    return Response(list1)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_duplicate_order_code_new(request):
    duplicate_order_codes = (
        PoultryRequest.objects
            .values('order_code')
            .annotate(count=Count('id'))
            .filter(count__gt=1, trash=False)
            .values_list('order_code', flat=True)
    )

    # استخراج شناسه‌های مرغ‌های مرتبط با کدهای تکراری
    poultry_ids = (
        PoultryRequest.objects
            .filter(order_code__in=duplicate_order_codes, trash=False)
            .values_list('poultry__user__id', flat=True)
            .distinct()
    )

    # مرتب‌سازی مرغ‌ها بر اساس شناسه
    poultries = SystemUserProfile.objects.filter(trash=False, id__in=poultry_ids).order_by('id')
    list1 = []
    for user in poultries:
        print(user.id)
        order_code = int(str(user.base_order) + '0001')
        requests = PoultryRequest.objects.filter(trash=False, poultry__user=user).order_by('id')
        for req in requests:
            req.order_code = order_code
            req.save()
            order_code += 1
    # # بررسی درخواست‌های مرتبط با هر مرغ
    # for poultry in poultries:
    #     requests = PoultryRequest.objects.filter(trash=False,poultry=poultry).order_by('order_code')
    #     base_order_code = str(poultry.user.base_order)  # فرض بر این است که "user" به درستی تعریف شده است
    #     last_order=[]
    #     for req in requests:
    #         if str(req.order_code)[:4] == base_order_code:
    #             last_order.clear()
    #             last_order.append(req.order_code)
    #         # if str(req.order_code)[:4] != base_order_code:
    #         #     list1.append(req.id)
    #     if last_order:
    #         last_num=last_order[0] + 1
    #         for req in requests:
    #             if str(req.order_code)[:4] != base_order_code:
    #                 base_order_code = last_num
    #                 req.order_code=base_order_code
    #                 req.save()
    #                 last_num+=1
    #         last_order.clear()

    return Response(list1)


def add_free_bar_to_warehouse():
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    date = datetime.now().date() - timedelta(days=3)
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(buy_type='live', trash=False, weight_of_carcasses=0,
                                                               create_date__date__lt=date, kill_house=kill_house,
                                                               ware_house=False)

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0
            for free_bar in free_bars:
                product = free_bar.product
                real_weight = round((free_bar.live_weight * 75) / 100)
                free_bar.number_of_carcasses = int(real_weight / 1.5)
                free_bar.weight_of_carcasses = real_weight
                free_bar.weight_loss = 25
                free_bar.ware_house = True
                free_bar.date = str(datetime.now())
                free_bar.entered_message = 'ورود به انبار توسط سیستم'
                free_bar.total_wage_amount = free_bar.wage * int(
                    free_bar.live_weight) if free_bar.buy_type == 'live' else free_bar.wage * int(
                    free_bar.weight_of_carcasses)

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

                mobile = kill_house.kill_house_operator.user.mobile
                if kill_house.killer == False:
                    killer = 'کشتارگاه'
                else:
                    killer = 'کشتارکن'
                message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                          f'\n' \
                          f'تعداد {len(free_bars)} بار (خارج استان) با حجم {wieght} به علت گذشتن زمان لازم برای ورود به انبار توسط سیستم وارد انبار شدند.' \
                          f'\n' \
                          f'(سامانه رصدیار)'
                check_mobile = check_mobile_number(mobile)
                if check_mobile:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to={mobile}&message={message}")


def change_password_poultry(request):
    poultries = SystemUserProfile.objects.filter(role__name='Poultry')
    for poultry in poultries:
        password = random.randint(1000, 9999)
        print(password)
        data = {
            'username': poultry.mobile,
            'password': str(password)
        }
        req_change_pass = requests.post(
            url=ARTA_URL_CHANGE_PASSWORD,
            data=data,
            verify=False
        )
        if req_change_pass.status_code == 200:
            poultry.password = str(password)
            poultry.save()


def add_vet_farm_to_poultry_request(request):
    from django.db.models import F, ExpressionWrapper, DurationField

    requests = PoultryRequest.objects.filter(trash=False, vet_farm__isnull=True).order_by('id')
    for r in requests:
        vet_farms = VetFarm.objects.filter(poultry=r.poultry).order_by('id')
        if len(vet_farms) == 1:

            r.vet_farm = vet_farms.first().vet
            r.save()
        elif len(vet_farms) > 1:
            # محاسبه اختلاف زمان و مرتب‌سازی بر اساس آن
            vet_farms_with_diff = vet_farms.annotate(
                date_diff=ExpressionWrapper(
                    F('create_date') - r.send_date,
                    output_field=DurationField()
                )
            ).order_by('-date_diff')
            closest_vet_farm = vet_farms_with_diff.first()
            if closest_vet_farm:
                r.vet_farm = closest_vet_farm.vet
                r.save()
    return HttpResponse("ok")


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def fix_kill_req_njsndb(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 6 or row is None:
            continue
        poultry = row[3]
        date = row[6]
        quantity = row[13]
        wieght = row[14]
        accepterde = row[19]
        date = date.split('-')

        date = convert_to_miladi(
            year=int(date[0]),
            month=int(date[1]),
            day=int(date[2])
        )
        kill_req = KillHouseFreeBarInformation.objects.get(trash=False, kill_house=5,
                                                           poultry_name=poultry, quantity=int(quantity),
                                                           live_weight=int(wieght), date__date=date,
                                                           acceptor_rejector=accepterde,

                                                           )

        kill_house = KillHouse.objects.get(id=int(row[21]))
        if kill_house:
            print(kill_req.id)
            kill_req.exclusive_killer = kill_house
            kill_req.save()

        # print(date.date())
        # for kill in kill_req:
        #     if kill.poultry_name == poultry and kill.quantity== quantity and \
        #         kill.live_weight== wieght and kill.date.date() ==date and kill.acceptor_rejector == accepterde:
        #         print(kill.id)
    return HttpResponse('ok')


def create_city_guild(request):
    city_operator = CityOperator.objects.filter(trash=False, id=1)
    prefix = "0918000"  # قسمت ثابت شماره موبایل
    random_part = random.randint(0, 9999)  # تولید یک عدد تصادفی بین ۰ تا ۹۹۹۹
    random_part_str = f"{random_part:04d}"  # اطمینان از چهار رقمی بودن (مثلاً ۰۱۲۳ به جای ۱۲۳)
    phone_number = prefix + random_part_str
    list1 = []
    group = Group.objects.get(name__exact="CityGuild")
    for i in city_operator:
        first_name = 'شرکت'
        last_name = str(i.unit_name.strip().split()[-1])
        password = '2025'
        hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
        province = Province.objects.filter(id=i.user.province.id).last()
        city = City.objects.filter(id=i.user.city.id).last()
        data = {
            "username": phone_number,
            "first_name": first_name,
            "last_name": last_name,
            "password": hashed_password,
            "national_code": '0',
            "role": "CityGuild",
            "api_key": PROJECT_API_KEY
        }
        while True:
            system_profile = SystemUserProfile.objects.filter(mobile=phone_number, trash=False).last()
            if not system_profile:
                req = requests.post(
                    url=ARTA_REGISTER,
                    data=data,
                    verify=False
                )
                if req.status_code == 200:
                    break
                else:
                    phone_number = str(int(phone_number) + 1)
            else:
                phone_number = str(int(phone_number) + 1)

        user = User(username=phone_number, first_name=first_name, last_name=last_name, password=hashed_password)
        user.save()
        base_id = SystemUserProfile.objects.all()
        if base_id.count() > 0:
            base_id = int(base_id.last().base_order) + 1
        else:
            base_id = 1000
        system_profile = SystemUserProfile(
            mobile=phone_number,
            first_name=first_name,
            last_name=last_name,
            fullname=first_name + '' + last_name,
            user=user,
            base_order=base_id,
            password=password,
            birthday=str(datetime.now().date()),
            city=city,
            province=province
        )
        system_profile.save()
        system_profile.role.add(group)
        wallet = Wallet()
        wallet.save()
        guild = CityGuild(
            user=system_profile,
            address=i.address,
            unit_name=f'شرکت پروتئین {last_name}',
            wallet=wallet,
            wallet_amount=0,
        )
        guild.save()

    return HttpResponse('ok')


def add_killing_age_to_poultry_request(request):
    poultry_requests = PoultryRequest.objects.filter(trash=False, out_province_request_cancel=False).order_by('id')
    for poultry_request in poultry_requests:
        age = (poultry_request.send_date.date() - poultry_request.hatching.date.date()).days + 1
        poultry_request.killing_age = age
        poultry_request.save()
    return HttpResponse('ok')


def add_poultry_prediction(request):
    poultry_hatching = PoultryHatching.objects.filter(trash=False, temporary_trash=False,
                                                      temporary_deleted=False).values_list('poultry__id',
                                                                                           flat=True).distinct()
    poultrys = Poultry.objects.filter(id__in=poultry_hatching, trash=False)
    for poultry in poultrys:
        poultry_prediction(poultry)
    return HttpResponse('ok')


def fix_out_quantity_hatching(request):
    hatchings = PoultryHatching.objects.filter(trash=False, allow_hatching='pending',
                                               state='pending')
    l = 0
    for hatching in hatchings:
        out_poultry_requests = PoultryRequest.objects.filter(trash=False, out=True,
                                                             state_process__in=('accepted', 'pending'),
                                                             province_state__in=('accepted', 'pending'),
                                                             out_province_request_cancel=False,
                                                             hatching=hatching)

        total_killed_quantity = out_poultry_requests.aggregate(total=Sum('quantity'))[
            'total']
        total_killed_weight = out_poultry_requests.aggregate(total=Sum('Index_weight'))[
            'total']
        total_killed_weight = total_killed_weight / len(out_poultry_requests)
        if total_killed_quantity != hatching.out_province_killed_quantity:
            hatching.out_province_killed_quantity = total_killed_quantity
            hatching.out_province_killed_weight = int(total_killed_weight * total_killed_quantity)
            hatching.save()
    return HttpResponse(l)


def accept_bar_difference_request_pending_cron_job():
    date = datetime.now().date() - timedelta(days=2)
    bar_requests = BarDifferenceRequest.objects.filter(trash=False,
                                                       state='pending', create_date__date__lt=date).order_by('id')
    for bar_request in bar_requests:
        bar_request.state = 'accepted'
        bar_request.acceptor_fullname = 'سیستمی'
        bar_request.acceptor_mobile = '00000000000'
        bar_request.acceptor_date = datetime.now()
        bar_request.hatching.bar_difference_request_quantity += bar_request.quantity
        bar_request.hatching.bar_difference_request_weight += bar_request.weight
        bar_request.hatching.save()
        bar_request.save()


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def live_chicken_transportation(request):
    import requests

    url = "https://www.samasat.ir/Report/BroilerCarryChickenAccordingToCarriage/_AjaxBinding"
    headers = {
        "authority": "www.samasat.ir",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "en-US,en;q=0.9",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    }

    cookies = {
        "ASP.NET_SessionId": "dl1fj1ad2m4ys1doyjr0gi1c",
        ".ASPXAUTH": "01BF39FE4507AAA7C63455A5B32B87A86145C672877A8ACAB074E87A89F13CDA40489ECD2E6732763758CD61528A0AE6BB390A8B3603BDAAA31CDD3AE7509F7885088F9CB51F56128C497F58ADEEFB54791C2F08ACF11AC1662DC1052430AA26E3EF29C1390FEC77C0C27908CC7A7AC9B62D7809419BE9639C848D10EB00022DCEE2B53039E8C13A59E7D50F3BC45D8C2328368285EF992B6FCF076CECFE8EFBE570F3A1FD0831D0B64EB8C9BBD326E088A40BCF3602C565FD00E78309AF4A4B75BA4E99A5A968F2FE666CCB4F176CAD2D9AC75D100EB69EBE4EA832C23C6EC8442B501BE3A014B50B711167292D3934C86843AC8CF151913575473BFE6003332B0DE69FDEAF78993B986CF8766682AC35E7B8A0492CBD59859E94DDABCC0FE6696C4703772CCEA19B05BE641B3F2DB636D79E8AEDB97E81792D9F357E8C8B3A843364032098683E90B61E90A3C2E647AD68BC067624EEB5328D0A22B8D38F9BC2A032C654DEE193580793A0CB0EDA4C65123EF59FC27D44E304FCCD8DB1548A944BEC5D1EE489C95EDBC406E61C603FC479D004DD705AAFE5FC1D10883E416D30AA11A1FF048DC92F41613B54E04F25D63D951F89380518D71CEC42C0E4207B66F0E0A940DF387782BD54A10E84A4F1E0266AB096538577CFA49A64092BC6CEBFED30B4E4F29D1D16EFB78BBF9B54D8047DD8919555906C98D0BFA11D81EDB0C938EAC11561EF3BB403D07A67C32D5F2202FC21881356CC3F954291FCF3C80653C46102A9C45C417D8241569D6D5ABEA8BB26DDA2E8A1E1D2A406A7EBD94F5E2349B5A18FB7C6CFE4E4FAD6C40201EC27F64DB539B964B18BEEA6A1DC188E3981053C0C1572325E54218AB20E663A194C78CEF2716D126456346B8323CCA4387D827AF775C055F7DF1D6131B2AB4B8C4CCC2B5AE7C025A4F6726B42E6BDCB99B8D695E091766B4C61BD16FE16DC8BF096010C6F1C077B12BD702B71C96D46D37670E40056337F971E3B2B8A72E50A64334B0DD480CC2B4E3F658255DF7C5880D6A5B673AE17EDECB65FDB34EF71E378DC1971389FEA8C89F01F96E75E30C4E5B3F42C07823C5AE78A720F71F15BA90FDEE9EE5D22920EB0F9052D083992D3430FCA0D327B365D734E7BBDCACEAAB6C8",
        "leggedOut": "-"
    }

    payload = {
        "sort": "RemoveDateMax-desc",
        "page": "1",
        "pageSize": "25",
        "group": "",
        "aggregate": "HatchingCount-sum~RemoveCount-sum",
        "filter": "",
        "searchVm.ProvinceLocationId": "65550",
        "searchVm.UnitName": "",
        "searchVm.PersonFullName": "",
        "searchVm.PartIdCode": "",
        "searchVm.PostalCode": "",
        "searchVm.EpidemiologicCode": "",
        "searchVm.CapacityFemale": "",
        "searchVm.BfrCode": "",
        "searchVm.SourceCertId": "",
        "searchVm.HatchingCount": "",
        "searchVm.RemoveCount": "",
        "searchVm.HatchingDateFrom": "",
        "searchVm.HatchingDateTo": "",
        "searchVm.PercentRemoveTakhlieFromHatchingFrom": "",
        "searchVm.PercentRemoveTakhlieFromHatchingTo": "",
        "searchVm.RemoveDateMinFrom": "",
        "searchVm.RemoveDateMinTo": "",
        "searchVm.RemoveDateMaxFrom": "1403/11/24",
        "searchVm.RemoveDateMaxTo": "1403/12/04",
        "searchVm.RemoveAgeAvgFrom": "",
        "searchVm.RemoveAgeAvgTo": "",
        "searchVm.RemoveAgeAvgSamasatFrom": "",
        "searchVm.RemoveAgeAvgSamasatTo": "",
        "searchVm.RemovePartyCountFrom": "",
        "searchVm.RemovePartyCountTo": ""
    }

    response = requests.post(url, headers=headers, cookies=cookies, data=payload)

    return Response(response.json())


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def heards_meat_flow(request):
    import requests
    url = "https://www.samasat.ir/Report/BroilerOnFlowFlocksHealthPermitReport/_AjaxBinding"
    headers = {
        "authority": "www.samasat.ir",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "en-US,en;q=0.9",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    }

    cookies = {
        "ASP.NET_SessionId": "dl1fj1ad2m4ys1doyjr0gi1c",
        ".ASPXAUTH": "01BF39FE4507AAA7C63455A5B32B87A86145C672877A8ACAB074E87A89F13CDA40489ECD2E6732763758CD61528A0AE6BB390A8B3603BDAAA31CDD3AE7509F7885088F9CB51F56128C497F58ADEEFB54791C2F08ACF11AC1662DC1052430AA26E3EF29C1390FEC77C0C27908CC7A7AC9B62D7809419BE9639C848D10EB00022DCEE2B53039E8C13A59E7D50F3BC45D8C2328368285EF992B6FCF076CECFE8EFBE570F3A1FD0831D0B64EB8C9BBD326E088A40BCF3602C565FD00E78309AF4A4B75BA4E99A5A968F2FE666CCB4F176CAD2D9AC75D100EB69EBE4EA832C23C6EC8442B501BE3A014B50B711167292D3934C86843AC8CF151913575473BFE6003332B0DE69FDEAF78993B986CF8766682AC35E7B8A0492CBD59859E94DDABCC0FE6696C4703772CCEA19B05BE641B3F2DB636D79E8AEDB97E81792D9F357E8C8B3A843364032098683E90B61E90A3C2E647AD68BC067624EEB5328D0A22B8D38F9BC2A032C654DEE193580793A0CB0EDA4C65123EF59FC27D44E304FCCD8DB1548A944BEC5D1EE489C95EDBC406E61C603FC479D004DD705AAFE5FC1D10883E416D30AA11A1FF048DC92F41613B54E04F25D63D951F89380518D71CEC42C0E4207B66F0E0A940DF387782BD54A10E84A4F1E0266AB096538577CFA49A64092BC6CEBFED30B4E4F29D1D16EFB78BBF9B54D8047DD8919555906C98D0BFA11D81EDB0C938EAC11561EF3BB403D07A67C32D5F2202FC21881356CC3F954291FCF3C80653C46102A9C45C417D8241569D6D5ABEA8BB26DDA2E8A1E1D2A406A7EBD94F5E2349B5A18FB7C6CFE4E4FAD6C40201EC27F64DB539B964B18BEEA6A1DC188E3981053C0C1572325E54218AB20E663A194C78CEF2716D126456346B8323CCA4387D827AF775C055F7DF1D6131B2AB4B8C4CCC2B5AE7c025A4F6726B42E6BDCB99B8D695E091766B4C61BD16FE16DC8BF096010C6F1C077B12BD702B71C96D46D37670E40056337F971E3B2B8A72E50A64334B0DD480CC2B4E3F658255DF7C5880D6A5B673AE17EDECB65FDB34EF71E378DC1971389FEA8C89F01F96E75E30C4E5B3F42C07823C5AE78A720F71F15BA90FDEE9EE5D22920EB0F9052D083992D3430FCA0D327B365D734E7BBDCACEAAB6C8",
        "leggedOut": "-"
    }

    payload = {
        "sort": "HatchingDate-desc",
        "page": "1",
        "pageSize": "25",
        "group": "",
        "aggregate": "HatchingCount-sum~HatchingCountInBargiri-sum~HatchingCountInTakhlie-sum~TrackingBargiriCount-sum~DiffHamlThanTakhlieCount-sum~DiffTakhlieThanHamlCount-sum~HamlMorghTotalCount-sum~HamlMorghTakhlieCount-sum~EvacuationCount-sum",
        "filter": "",
        "searchVm.FromDate": "01/09/1403 12:00:00 ق.ظ",
        "searchVm.ToDate": "04/12/1403 12:00:00 ق.ظ",
        "searchVm.TableName": "Z_002_ReportTempTable_5a2f0974ec3542d4b92ac87e75ef5549",
        "searchVm.ProvinceLocationId": "65550",
        "searchVm.PartIdCode": "",
        "searchVm.UnitName": "",
        "searchVm.PostalCode": "",
        "searchVm.EpidemiologicCode": "",
        "searchVm.PersonFullName": "",
        "searchVm.CapacityFemaleFrom": "",
        "searchVm.CapacityFemaleTo": "",
        "searchVm.RequestCode": "",
        "searchVm.DesCertId": "",
        "searchVm.FlockAgeDayFrom": "1",
        "searchVm.FlockAgeDayTo": "60",
        "searchVm.HatchingDateFromPersian": "",
        "searchVm.HatchingDateToPersian": "",
        "searchVm.MaxHatchingDateFromPersian": "",
        "searchVm.MaxHatchingDateToPersian": "",
        "searchVm.TrackingStatusId": "",
        "searchVm.PercentMorghToJoojeTotalFrom": "",
        "searchVm.PercentMorghToJoojeTotalTo": "",
        "searchVm.PercentMorghToJoojeTakhlieFrom": "",
        "searchVm.PercentMorghToJoojeTakhlieTo": ""
    }

    # Send the POST request
    response = requests.post(url, headers=headers, cookies=cookies, data=payload)

    return Response(response.json())


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def detail_heards_meat_flow(request):
    import requests

    url = "https://www.samasat.ir/WinBroilerFlockRequest/WinBroilerFlockRequestHatchingTrackingRep/_AjaxBindingWinBroilerFlockRequestHatchingTrackingRepVw"
    headers = {
        "authority": "www.samasat.ir",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "en-US,en;q=0.9",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    }

    cookies = {
        "ASP.NET_SessionId": "i2l4rxgagljnsecfg4smvbwg",
        ".ASPXAUTH": "681FA227EBBFA8AFFA02E6C23A8B52159139B3D2E6AB49D18E71D6E568273F013CC434A01E2E9B27F6594D01A3B5FBC3923AA876642555D6FDD209306CB9336FE1CC172797B46B72274BDEBFCCD7EAD1EC6C69A30A871BE40FF5C9EDC025E10569533963A92F00B03A3495622A962FBE0FFDAF4B4EC513AF1458BF6282C2C7D2618DCA2A1394D5E1BF34EA50FED6490AD29AA63749DC0EA8849792A6834139F6EDA2C5C938AC36A92371B542C576FEA94A81F3D7274F6EFFCD8FD08820B871D4BD588CB415DCC3D86B5408577D50C1C36B00D6032BE82D85BD80453D5C1FF719C186000C379CB43FB794AE9C91838A0D04D744BEC9E7ADDCCB0668B0326F1B1F50EAE3128537F4ECB07A5453AFBCDD22A5509A1DDE5AA7EF25CBAFBEB06182E468E80BB28C7DEE72D1990FCDE24C6B4E1621E77BCF221A25783CD87D15777C1698052EA6193725C5CB0B3DF1788D1C15DF2AB14357A6051DA5810B948EEDC7697E701EED1D1A69E268742EB63A133F5667D23D2191ABC60C8A0C828A61CBF8432DD6F49DA32B7D9FAE4DA4AF0D7A175A6CCAFDB2DAB13DA6A5AD802945F0A9DB3E9FE8D4694449600109EF2656993993C14F269C8E61747696480B0079765B99386F7A218E38C37A32E9D14C97B246E3102FCFD5E298C11A1955D88FC2D94F5795B7245B62611965C2A46B3E9B0E906D5879B6D3AFF76401E7F5F1CE6E7215CF6AF52D313A3A57853E23F0E2402B9101F482BA857A987EAC5B2895FB29C49840EA2AB0F4A316A3223F8E67967A2ADFB43CFE47109A70A98725EFAB57F68A57E42F5E0DB306339BE841861A094399A8BA9CD98ED065A20CFB30C5ECC46A3CBD9C7B03DFDD603C0C143D353EC1A8A2CE0AB9ADB69A3EFB0B6B953520B133026355CC4FAAFD9D380FE436CD8B87471ED0B507663192A4B35A2D085BAD0A47C9DBC5E813EFF7BE2BB64A2A10A5A8EFE0D80CBE2EE81E2DC0F86DAD4A5D9F2A1F7E32EAFF8669E95616DB93CCF5FD801B293D47AEFAB1EE5C2801D2E916868687226315BAF13A971ED0382D75EF0EA69271962959DD05AB22B2A6397980B026B59A8A38A1385689258D7BB05E0DFAF7E4DF9868A50088D044003FB55A6D20E8EBAF92F457C1BBCD7BFB5E15A0795445A11ECA",
        "leggedOut": "-"
    }

    payload = {
        "sort": "IssueDate-desc",
        "page": "1",
        "pageSize": "25",
        "group": "",
        "filter": "",
        "certId": "140313016425"
    }

    response = requests.post(url, headers=headers, cookies=cookies, data=payload)

    return Response(response.json())


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def breed(request):
    import requests

    url = "https://www.samasat.ir/Report/BroilerFlockRequestDetailReport/_AjaxBinding"
    headers = {
        "authority": "www.samasat.ir",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "en-US,en;q=0.9",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    }

    cookies = {
        "ASP.NET_SessionId": "i2l4rxgagljnsecfg4smvbwg",
        ".ASPXAUTH": "681FA227EBBFA8AFFA02E6C23A8B52159139B3D2E6AB49D18E71D6E568273F013CC434A01E2E9B27F6594D01A3B5FBC3923AA876642555D6FDD209306CB9336FE1CC172797B46B72274BDEBFCCD7EAD1EC6C69A30A871BE40FF5C9EDC025E10569533963A92F00B03A3495622A962FBE0FFDAF4B4EC513AF1458BF6282C2C7D2618DCA2A1394D5E1BF34EA50FED6490AD29AA63749DC0EA8849792A6834139F6EDA2C5C938AC36A92371B542C576FEA94A81F3D7274F6EFFCD8FD08820B871D4BD588CB415DCC3D86B5408577D50C1C36B00D6032BE82D85BD80453D5C1FF719C186000C379CB43FB794AE9C91838A0D04D744BEC9E7ADDCCB0668B0326F1B1F50EAE3128537F4ECB07A5453AFBCDD22A5509A1DDE5AA7EF25CBAFBEB06182E468E80BB28C7DEE72D1990FCDE24C6B4E1621E77BCF221A25783CD87D15777C1698052EA6193725C5CB0B3DF1788D1C15DF2AB14357A6051DA5810B948EEDC7697E701EED1D1A69E268742EB63A133F5667D23D2191ABC60C8A0C828A61CBF8432DD6F49DA32B7D9FAE4DA4AF0D7A175A6CCAFDB2DAB13DA6A5AD802945F0A9DB3E9FE8D4694449600109EF2656993993C14F269C8E61747696480B0079765B99386F7A218E38C37A32E9D14C97B246E3102FCFD5E298C11A1955D88FC2D94F5795B7245B62611965C2A46B3E9B0E906D5879B6D3AFF76401E7F5F1CE6E7215CF6AF52D313A3A57853E23F0E2402B9101F482BA857A987EAC5B2895FB29C49840EA2AB0F4A316A3223F8E67967A2ADFB43CFE47109A70A98725EFAB57F68A57E42F5E0DB306339BE841861A094399A8BA9CD98ED065A20CFB30C5ECC46A3CBD9C7B03DFDD603C0C143D353EC1A8A2CE0AB9ADB69A3EFB0B6B953520B133026355CC4FAAFD9D380FE436CD8B87471ED0B507663192A4B35A2D085BAD0A47C9DBC5E813EFF7BE2BB64A2A10A5A8EFE0D80CBE2EE81E2DC0F86DAD4A5D9F2A1F7E32EAFF8669E95616DB93CCF5FD801B293D47AEFAB1EE5C2801D2E916868687226315BAF13A971ED0382D75EF0EA69271962959DD05AB22B2A6397980B026B59A8A38A1385689258D7BB05E0DFAF7E4DF9868A50088D044003FB55A6D20E8EBAF92F457C1BBCD7BFB5E15A0795445A11ECA",
        "leggedOut": "-"
    }

    payload = {
        "sort": "SendDate-desc",
        "page": "1",
        "pageSize": "25",
        "group": "",
        "aggregate": "RequestCountLong-sum~ChickCountLong-sum",
        "filter": "",
        "searchVm.FlockRequestId": "",
        "searchVm.Islegal": "True",
        "searchVm.HatcheryId": "",
        "searchVm.ProvinceLocationId": "65550",
        "searchVm.PartIdCode": "",
        "searchVm.UnitName": "",
        "searchVm.BfrRequestCode": "",
        "searchVm.CertId": "",
        "searchVm.BroilerPedigreeTypeId": "",
        "searchVm.SendDateFrom": "1403/11/28",
        "searchVm.SendDateTo": "1403/12/05",
        "searchVm.ChickCountFrom": "",
        "searchVm.ChickCountTo": "",
        "searchVm.PedigreeType": "",
        "searchVm.SenderUnitName": "",
        "searchVm.StartDateFrom": "",
        "searchVm.StartDateTo": "",
        "searchVm.EndDateFrom": "",
        "searchVm.EndDateTo": "",
        "searchVm.RequestCountFrom": "",
        "searchVm.RequestCountTo": "",
        "searchVm.SystemCode": "",
        "searchVm.EpidemiologicCode": "",
        "searchVm.PostalCode": "",
        "searchVm.CapacityFemaleFrom": "",
        "searchVm.CapacityFemaleTo": "",
        "searchVm.PersonNationalCodeOrId": "",
        "searchVm.PersonName": "",
        "searchVm.RegDateFrom": "",
        "searchVm.RegDateTo": ""
    }

    response = requests.post(url, headers=headers, cookies=cookies, data=payload)

    return Response(response.json())


@api_view(["GET"])
@permission_classes([AllowAny])
@csrf_exempt
def chat_bot_info(request):
    hatchings = PoultryHatching.objects.filter(trash=False, archive=False, state='pending').order_by('date')
    poultry = Poultry.objects.filter(pk__in=hatchings.values_list('poultry', flat=True))
    province_kill_requests = ProvinceKillRequest.objects.filter(trash=False, state__in=('pending', 'accepted'),
                                                                return_to_province=False,
                                                                province_request__poultry_request__hatching__in=hatchings)
    kill_house_requests = KillHouseRequest.objects.filter(trash=False,
                                                          province_request__poultry_request__hatching__in=hatchings)

    result = {
        "number_of_hatchings": len(hatchings),
        "number_of_poultry": len(poultry),
        "hatching_quantity": hatchings.aggregate(total=Sum('quantity'))['total'] or 0,
        "number_province_kill_requests": len(province_kill_requests),
        "province_kill_requests_quantity": province_kill_requests.aggregate(total=Sum('total_killed_quantity'))[
                                               'total'] or 0,
        "number_of_kill_house_requests": len(kill_house_requests),
        "kill_house_requests_quantity": kill_house_requests.aggregate(total=Sum('accepted_real_quantity'))[
                                            'total'] or 0,
    }

    return Response(result, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def add_interest_license_id_to_poultry(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    list1 = []
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 6 or row is None:
            continue
        breeding = row[5]
        licenc = row[13]
        try:
            poultry = Poultry.objects.get(breeding_unique_id=breeding, trash=False)
            poultry.interest_license_id = licenc
            poultry.save()
        except:
            list1.append(breeding)
        # print(date.date())
        # for kill in kill_req:
        #     if kill.poultry_name == poultry and kill.quantity== quantity and \
        #         kill.live_weight== wieght and kill.date.date() ==date and kill.acceptor_rejector == accepterde:
        #         print(kill.id)
    return HttpResponse(list1)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def add_asddasasd(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    list1 = []
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 1 or row is None:
            continue

        east = row[16]
        west = row[17]
        licenc = row[3]
        poultry = Poultry.objects.filter(Lat__isnull=True, interest_license_id=licenc).first()
        if poultry:
            if east and west is not None:
                lon, lat = utm_to_loc(east, west)
                poultry.Lat = lon
                poultry.Long = lat
                poultry.save()
        # تبدیل مختصات
        # breeding=row[5]
        # licenc=row[13]
        # try:
        #     poultry=Poultry.objects.get(breeding_unique_id=breeding,trash=False)
        #     poultry.interest_license_id=licenc
        #     poultry.save()
        # except:
        #     list1.append(breeding)
        # # print(date.date())
        # for kill in kill_req:
        #     if kill.poultry_name == poultry and kill.quantity== quantity and \
        #         kill.live_weight== wieght and kill.date.date() ==date and kill.acceptor_rejector == accepterde:
        #         print(kill.id)
    return HttpResponse(list1)


# def add_to_warehouse_manual(request):
#     kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
#         'system_address__province')
#     for kill_house in kill_houses:
#         kill_house_requests = KillHouseRequest.objects.filter(
#             Q(killhouse_user=kill_house) | Q(killer=kill_house),
#             ware_house_confirmation=False, trash=False, calculate_status=True)
#         if kill_house_requests:
#             # wieght = \
#             #     kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
#             #         'total'] or 0
#             for kill_house_request in kill_house_requests:
#                 kill_house = kill_house_request.killhouse_user
#                 product = RolesProducts.objects.filter(parent_product__product_id=2, kill_house=kill_house).first()
#
#
#
#                 kill_house_request.ware_house_accepted_real_quantity = kill_house_request.accepted_real_quantity
#                 kill_house_request.ware_house_accepted_real_weight = int(kill_house_request.accepted_real_weight - (
#                         (kill_house_request.accepted_real_weight * 25) / 100))
#                 kill_house_request.weight_loss = 25
#                 kill_house_request.ware_house_input_type = 'loss_weight'
#                 kill_house_request.ware_house_confirmation = True
#                 kill_house_request.date_of_ware_house = str(datetime.now())
#                 kill_house_request.entered_message='ورود به انبار توسط سیستم'
#                 kill_house_request.save()
#                 kill_house_requests_product_warehousing(product)
#
#             # mobile=kill_house.kill_house_operator.user.mobile
#             # if kill_house.killer == False:
#             #     killer = 'کشتارگاه'
#             # else:
#             #     killer = 'کشتارکن'
#             # message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
#             #           f'\n' \
#             #           f'تعداد {len(kill_house_requests)} بار با حجم {wieght} به علت گذشتن زمان لازم برای ورود به انبار توسط سیستم وارد انبار شدند.' \
#             #           f'\n' \
#             #           f'(سامانه رصدیار)'
#             # check_mobile = check_mobile_number(mobile)
#             # if check_mobile:
#             #     req = requests.get(
#             #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to={mobile}&message={message}")
#     return HttpResponse('ok')

def add_free_bar_to_warehouse_automatic_type_manual(request):
    if base_url_for_sms_report == 'ha' or base_url_for_sms_report == 'ku':
        send_day = 2
        send_time = 48
    else:
        send_day = 1
        send_time = 24
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(
            create_date__date__lt=datetime.now().date() - timedelta(days=send_day), buy_type='live', trash=False,
            weight_of_carcasses=0, kill_house=kill_house, ware_house=False, register_type='automatic')

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0

            len_kill_house_requests = len(free_bars)
            ware_house_accepted_real_weight = int((wieght * 75) / 100)
            bars_info = []
            for free_bar in free_bars:
                product = free_bar.product
                real_weight = round((free_bar.live_weight * 75) / 100)
                free_bar.number_of_carcasses = int(real_weight / 1.5)
                free_bar.weight_of_carcasses = real_weight
                free_bar.weight_loss = 25
                free_bar.ware_house = True
                free_bar.date = str(datetime.now())
                # free_bar.entered_message = 'ورود به انبار توسط سیستم'
                # free_bar.entered_message = 'ورود به انبار مجازی'
                free_bar.total_wage_amount = free_bar.wage * int(
                    free_bar.live_weight) if free_bar.buy_type == 'live' else free_bar.wage * int(
                    free_bar.weight_of_carcasses)

                union_percent = free_bar.union_share_percent / 100 if free_bar.union_share_percent > 0 else 0
                company_percent = free_bar.company_share_percent / 100 if free_bar.company_share_percent > 0 else 0
                guilds_percent = free_bar.guilds_share_percent / 100 if free_bar.guilds_share_percent > 0 else 0
                city_share_percent = free_bar.city_share_percent / 100 if free_bar.city_share_percent > 0 else 0
                wallet_share_percent = free_bar.wallet_share_percent / 100 if free_bar.wallet_share_percent > 0 else 0
                other_share_percent = free_bar.other_share_percent / 100 if free_bar.other_share_percent > 0 else 0
                free_bar.union_share = int(union_percent * free_bar.total_wage_amount)
                free_bar.company_share = int(company_percent * free_bar.total_wage_amount)
                free_bar.guilds_share = int(guilds_percent * free_bar.total_wage_amount)
                free_bar.city_share = int(city_share_percent * free_bar.total_wage_amount)
                free_bar.wallet_share = int(wallet_share_percent * free_bar.total_wage_amount)
                free_bar.other_share = int(other_share_percent * free_bar.total_wage_amount)
                free_bar.save()
                kill_house_free_buying_product_warehousing(product)
                bars_info.append(
                    'کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - وزن لاشه: {2} کیلوگرم - تاریخ بار: ({3})'.format(
                        free_bar.bar_clearance_code,
                        to_locale_str(int(free_bar.live_weight)),
                        to_locale_str(int(real_weight)),
                        shamsi_date(free_bar.create_date)
                    ))
                # mobile=kill_house.kill_house_operator.user.mobile
                # if kill_house.killer == False:
                #     killer = 'کشتارگاه'
                # else:
                #     killer = 'کشتارکن'
                # message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                #           f'\n' \
                #           f'تعداد {len(free_bars)} بار (خارج استان) با حجم {wieght} به علت گذشتن زمان لازم برای ورود به انبار توسط سیستم وارد انبار شدند.' \
                #           f'\n' \
                #           f'(سامانه رصدیار)'
                # check_mobile = check_mobile_number(mobile)
                # if check_mobile:
                #     req = requests.get(
                #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to={mobile}&message={message}")
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:اعلام ورود بار به انبار مجازی به دلیل انقضای مهلت زمانی",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد. ***' \
                      '\n' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار خارج استانی به تعداد {to_locale_str(len_kill_house_requests)} بار  و وزن زنده {to_locale_str(int(wieght))} کیلوگرم و وزن لاشه {to_locale_str(int(ware_house_accepted_real_weight))} کیلوگرم متعلق به شما، به دلیل گذشت مهلت {send_time} ساعته و عدم اقدام به موقع، به‌صورت خودکار به انبار مجازی منتقل گردید.*** ' \
                      '\n' \
                      f' جزئیات بارهای منتقل شده:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f' جهت مشاهده بارها به بخش انبار و توزیع مراجعه نمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()
    return HttpResponse('ok')


def add_free_bar_to_warehouse_automatic_type_cron():
    # if base_url_for_sms_report == 'ha':
    send_day = 2
    send_time = 48
    # else:
    #     send_day = 1
    #     send_time = 24
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(
            register_date__date__lt=datetime.now().date() - timedelta(days=send_day), buy_type='live', trash=False,
            weight_of_carcasses=0, kill_house=kill_house, ware_house=False, register_type='automatic')

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0

            len_kill_house_requests = len(free_bars)
            ware_house_accepted_real_weight = int((wieght * 75) / 100)
            bars_info = []
            for free_bar in free_bars:
                product = free_bar.product
                real_weight = round((free_bar.live_weight * 75) / 100)
                free_bar.number_of_carcasses = int(real_weight / 1.5)
                free_bar.weight_of_carcasses = real_weight
                free_bar.weight_loss = 25
                free_bar.ware_house = True
                free_bar.date = str(datetime.now())
                # free_bar.entered_message = 'ورود به انبار توسط سیستم'
                # free_bar.entered_message = 'ورود به انبار مجازی'
                free_bar.total_wage_amount = free_bar.wage * int(
                    free_bar.live_weight) if free_bar.buy_type == 'live' else free_bar.wage * int(
                    free_bar.weight_of_carcasses)

                union_percent = free_bar.union_share_percent / 100 if free_bar.union_share_percent > 0 else 0
                company_percent = free_bar.company_share_percent / 100 if free_bar.company_share_percent > 0 else 0
                guilds_percent = free_bar.guilds_share_percent / 100 if free_bar.guilds_share_percent > 0 else 0
                city_share_percent = free_bar.city_share_percent / 100 if free_bar.city_share_percent > 0 else 0
                wallet_share_percent = free_bar.wallet_share_percent / 100 if free_bar.wallet_share_percent > 0 else 0
                other_share_percent = free_bar.other_share_percent / 100 if free_bar.other_share_percent > 0 else 0
                free_bar.union_share = int(union_percent * free_bar.total_wage_amount)
                free_bar.company_share = int(company_percent * free_bar.total_wage_amount)
                free_bar.guilds_share = int(guilds_percent * free_bar.total_wage_amount)
                free_bar.city_share = int(city_share_percent * free_bar.total_wage_amount)
                free_bar.wallet_share = int(wallet_share_percent * free_bar.total_wage_amount)
                free_bar.other_share = int(other_share_percent * free_bar.total_wage_amount)
                free_bar.save()
                kill_house_free_buying_product_warehousing(product)
                bars_info.append(
                    'کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - وزن لاشه: {2} کیلوگرم - تاریخ بار: ({3})'.format(
                        free_bar.bar_clearance_code,
                        to_locale_str(int(free_bar.live_weight)),
                        to_locale_str(int(real_weight)),
                        shamsi_date(free_bar.create_date)
                    ))
                # mobile=kill_house.kill_house_operator.user.mobile
                # if kill_house.killer == False:
                #     killer = 'کشتارگاه'
                # else:
                #     killer = 'کشتارکن'
                # message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                #           f'\n' \
                #           f'تعداد {len(free_bars)} بار (خارج استان) با حجم {wieght} به علت گذشتن زمان لازم برای ورود به انبار توسط سیستم وارد انبار شدند.' \
                #           f'\n' \
                #           f'(سامانه رصدیار)'
                # check_mobile = check_mobile_number(mobile)
                # if check_mobile:
                #     req = requests.get(
                #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to={mobile}&message={message}")
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:اعلام ورود بار به انبار مجازی به دلیل انقضای مهلت زمانی",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد. ***' \
                      '\n' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار خارج استانی به تعداد {to_locale_str(len_kill_house_requests)} بار  و وزن زنده {to_locale_str(int(wieght))} کیلوگرم و وزن لاشه {to_locale_str(int(ware_house_accepted_real_weight))} کیلوگرم متعلق به شما، به دلیل گذشت مهلت {send_time} ساعته و عدم اقدام به موقع، به‌صورت خودکار به انبار مجازی منتقل گردید.*** ' \
                      '\n' \
                      f' جزئیات بارهای منتقل شده:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f' جهت مشاهده بارها به بخش انبار و توزیع مراجعه نمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()


def add_free_bar_to_warehouse_manual(request):
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(
            create_date__date__lt=datetime.now().date() - timedelta(days=2), buy_type='live', trash=False,
            weight_of_carcasses=0, kill_house=kill_house, ware_house=False, register_type='manual')

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0

            len_kill_house_requests = len(free_bars)
            ware_house_accepted_real_weight = int((wieght * 75) / 100)
            bars_info = []
            for free_bar in free_bars:
                product = free_bar.product
                real_weight = round((free_bar.live_weight * 75) / 100)
                free_bar.number_of_carcasses = int(real_weight / 1.5)
                free_bar.weight_of_carcasses = real_weight
                free_bar.weight_loss = 25
                free_bar.ware_house = True
                free_bar.date = str(datetime.now())
                free_bar.entered_message = 'ورود به انبار توسط سیستم'
                free_bar.total_wage_amount = free_bar.wage * int(
                    free_bar.live_weight) if free_bar.buy_type == 'live' else free_bar.wage * int(
                    free_bar.weight_of_carcasses)

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

                bars_info.append(
                    'کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - وزن لاشه: {2} کیلوگرم - تاریخ بار: ({3})'.format(
                        free_bar.bar_clearance_code,
                        to_locale_str(int(free_bar.live_weight)),
                        to_locale_str(int(real_weight)),
                        shamsi_date(free_bar.date)
                    ))
                # mobile=kill_house.kill_house_operator.user.mobile
                # if kill_house.killer == False:
                #     killer = 'کشتارگاه'
                # else:
                #     killer = 'کشتارکن'
                # message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                #           f'\n' \
                #           f'تعداد {len(free_bars)} بار (خارج استان) با حجم {wieght} به علت گذشتن زمان لازم برای ورود به انبار توسط سیستم وارد انبار شدند.' \
                #           f'\n' \
                #           f'(سامانه رصدیار)'
                # check_mobile = check_mobile_number(mobile)
                # if check_mobile:
                #     req = requests.get(
                #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to={mobile}&message={message}")
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:اعلام ورود بار به انبار به دلیل انقضای مهلت زمانی",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد. ***' \
                      '\n' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار خارج استانی به تعداد {to_locale_str(len_kill_house_requests)} بار  و وزن زنده {to_locale_str(int(wieght))} کیلوگرم و وزن لاشه {to_locale_str(int(ware_house_accepted_real_weight))} کیلوگرم متعلق به شما، به دلیل گذشت مهلت ۴۸ ساعته و عدم اقدام به موقع، به‌صورت خودکار به انبار منتقل گردید.*** ' \
                      '***' \
                      f' جزئیات بارهای منتقل شده:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f' جهت مشاهده بارها به بخش انبار و توزیع مراجعه نمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()

    return HttpResponse('ok')


def add_free_bar_to_warehouse_cron():
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(create_date__date__lt=datetime.now().date() -
                                                                                     timedelta(days=2), buy_type='live',
                                                               trash=False,
                                                               weight_of_carcasses=0, kill_house=kill_house,
                                                               ware_house=False
                                                               , register_type='manual')

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0

            len_kill_house_requests = len(free_bars)
            ware_house_accepted_real_weight = int((wieght * 75) / 100)
            bars_info = []
            for free_bar in free_bars:
                product = free_bar.product
                real_weight = round((free_bar.live_weight * 75) / 100)
                free_bar.number_of_carcasses = int(real_weight / 1.5)
                free_bar.weight_of_carcasses = real_weight
                free_bar.weight_loss = 25
                free_bar.ware_house = True
                free_bar.date = str(datetime.now())
                free_bar.entered_message = 'ورود به انبار توسط سیستم'
                free_bar.total_wage_amount = free_bar.wage * int(
                    free_bar.live_weight) if free_bar.buy_type == 'live' else free_bar.wage * int(
                    free_bar.weight_of_carcasses)

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

                bars_info.append(
                    'کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - وزن لاشه: {2} کیلوگرم - تاریخ بار: ({3})'.format(
                        free_bar.bar_clearance_code,
                        to_locale_str(int(free_bar.live_weight)),
                        to_locale_str(int(real_weight)),
                        shamsi_date(free_bar.date)
                    ))
                # mobile=kill_house.kill_house_operator.user.mobile
                # if kill_house.killer == False:
                #     killer = 'کشتارگاه'
                # else:
                #     killer = 'کشتارکن'
                # message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                #           f'\n' \
                #           f'تعداد {len(free_bars)} بار (خارج استان) با حجم {wieght} به علت گذشتن زمان لازم برای ورود به انبار توسط سیستم وارد انبار شدند.' \
                #           f'\n' \
                #           f'(سامانه رصدیار)'
                # check_mobile = check_mobile_number(mobile)
                # if check_mobile:
                #     req = requests.get(
                #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to={mobile}&message={message}")
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:اعلام ورود بار به انبار به دلیل انقضای مهلت زمانی",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد. ***' \
                      '\n' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار خارج استانی به تعداد {to_locale_str(len_kill_house_requests)} بار  و وزن زنده {to_locale_str(int(wieght))} کیلوگرم و وزن لاشه {to_locale_str(int(ware_house_accepted_real_weight))} کیلوگرم متعلق به شما، به دلیل گذشت مهلت ۴۸ ساعته و عدم اقدام به موقع، به‌صورت خودکار به انبار منتقل گردید.*** ' \
                      '***' \
                      f' جزئیات بارهای منتقل شده:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f' جهت مشاهده بارها به بخش انبار و توزیع مراجعه نمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()


def fix_poultry_request_script(request):
    hatchings = PoultryHatching.objects.filter(trash=False, archive=False,
                                               allow_hatching='pending')
    for hatching in hatchings:

        province_requests = PoultryRequest.objects.filter(
            Q(wage_pay=False, has_wage=False) | Q(wage_pay=True, has_wage=True), hatching=hatching
            , state_process='accepted', province_state='accepted', trash=False, archive=False,
            out_province_request_cancel=False, out=True)
        if province_requests:
            hatching.out_province_killed_quantity = province_requests.aggregate(total=Sum('quantity'))[
                                                        'total'] or 0
            hatching.out_province_killed_weight = province_requests.aggregate(
                total=Sum(F('quantity') * F('Index_weight')))[
                'total']
            hatching.save()

    return HttpResponse('ok')


def add_to_warehouse():
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()

    kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
    date = datetime.now().date() - timedelta(days=2)
    for kill_house in kill_houses:
        kill_house_requests = KillHouseRequest.objects.filter(
            Q(killhouse_user=kill_house) | Q(killer=kill_house),
            kill_request__recive_date__date__lt=date,
            ware_house_confirmation=False, trash=False, calculate_status=True)
        if kill_house_requests:
            wieght = \
                kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                    'total'] or 0
            len_kill_house_requests = len(kill_house_requests)
            ware_house_accepted_real_weight = int((wieght * 75) / 100)
            bars_info = []
            for kill_house_request in kill_house_requests:
                kill_house = kill_house_request.killhouse_user
                kill_house_request.ware_house_accepted_real_quantity = kill_house_request.accepted_real_quantity
                kill_house_request.ware_house_accepted_real_weight = int(
                    (kill_house_request.accepted_real_weight * 75) / 100)
                kill_house_request.weight_loss = 25
                kill_house_request.ware_house_input_type = 'loss_weight'
                kill_house_request.ware_house_confirmation = True
                kill_house_request.date_of_ware_house = str(datetime.now())
                kill_house_request.entered_message = 'ورود به انبار توسط سیستم'
                kill_house_request.save()

                bars_info.append(
                    'کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - وزن لاشه: {2} کیلوگرم - تاریخ بار: ({3})'.format(
                        kill_house_request.clearance_code,
                        to_locale_str(int(kill_house_request.accepted_real_weight)),
                        to_locale_str(int(kill_house_request.ware_house_accepted_real_weight)),
                        shamsi_date(kill_house_request.kill_request.recive_date)
                    ))
            product = RolesProducts.objects.filter(kill_house=kill_house).first()
            kill_house_requests_product_warehousing(product)

            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:اعلام ورود بار به انبار به دلیل انقضای مهلت زمانی",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد.' \
                      '***' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار داخل استانی به تعداد {to_locale_str(len_kill_house_requests)} بار  و وزن زنده {to_locale_str(int(wieght))} کیلوگرم و وزن لاشه {to_locale_str(int(ware_house_accepted_real_weight))} کیلوگرم متعلق به جنابعالی، به دلیل گذشت مهلت ۴۸ ساعته و عدم اقدام به موقع، به‌صورت خودکار به انبار منتقل گردید.' \
                      f'***' \
                      f' جزئیات بارهای منتقل شده:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f' جهت مشاهده بارها به بخش انبار و توزیع مراجعه نمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()


def add_to_warehouse_manual(request):
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()

    kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
    date = datetime.now().date() - timedelta(days=2)
    for kill_house in kill_houses:
        kill_house_requests = KillHouseRequest.objects.filter(
            Q(killhouse_user=kill_house) | Q(killer=kill_house),
            kill_request__recive_date__date__lt=date,
            ware_house_confirmation=False, trash=False, calculate_status=True)
        if kill_house_requests:
            wieght = \
                kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                    'total'] or 0
            len_kill_house_requests = len(kill_house_requests)
            ware_house_accepted_real_weight = int((wieght * 75) / 100)
            bars_info = []
            for kill_house_request in kill_house_requests:
                kill_house = kill_house_request.killhouse_user
                kill_house_request.ware_house_accepted_real_quantity = kill_house_request.accepted_real_quantity
                kill_house_request.ware_house_accepted_real_weight = int(
                    (kill_house_request.accepted_real_weight * 75) / 100)
                kill_house_request.weight_loss = 25
                kill_house_request.ware_house_input_type = 'loss_weight'
                kill_house_request.ware_house_confirmation = True
                kill_house_request.date_of_ware_house = str(datetime.now())
                kill_house_request.entered_message = 'ورود به انبار توسط سیستم'
                kill_house_request.save()

                bars_info.append(
                    'کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - وزن لاشه: {2} کیلوگرم - تاریخ بار: ({3})'.format(
                        kill_house_request.clearance_code,
                        to_locale_str(int(kill_house_request.accepted_real_weight)),
                        to_locale_str(int(kill_house_request.ware_house_accepted_real_weight)),
                        shamsi_date(kill_house_request.kill_request.recive_date)
                    )
                )

            product = RolesProducts.objects.filter(kill_house=kill_house).first()
            kill_house_requests_product_warehousing(product)

            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:اعلام ورود بار به انبار به دلیل انقضای مهلت زمانی",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد.' \
                      '***' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار داخل استانی به تعداد {to_locale_str(len_kill_house_requests)} بار  و وزن زنده {to_locale_str(int(wieght))} کیلوگرم و وزن لاشه {to_locale_str(int(ware_house_accepted_real_weight))} کیلوگرم متعلق به جنابعالی، به دلیل گذشت مهلت ۴۸ ساعته و عدم اقدام به موقع، به‌صورت خودکار به انبار منتقل گردید.' \
                      f'***' \
                      f' جزئیات بارهای منتقل شده:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f' جهت مشاهده بارها به بخش انبار و توزیع مراجعه نمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()
    return HttpResponse('ok')


def return_from_archive_poultry_hatching_with_cron_job():
    now_date = datetime.now().date()
    hatching = PoultryHatching.objects.filter(trash=False,
                                              allow_hatching='True', input_archiver__isnull=True,
                                              last_change__role="automatic-archive",
                                              state='complete', archive=True, last_change__isnull=False).only(
        'allow_hatching',
        'left_over', 'quantity', 'state',
        'archive')
    for hatch in hatching:
        archive_date = hatch.last_change['date']
        date1 = datetime.strptime(archive_date, '%Y-%m-%d %H:%M:%S.%f').date()
        if now_date == date1:
            if hatch.left_over > (hatch.quantity * percent_of_losses):
                hatch.violation = False
            hatch.allow_hatching = 'pending'
            hatch.state = 'pending'
            hatch.archive = False
            if hatch.first_date_input_archive is not None:
                hatch.first_date_input_archive = None

            hatch.last_change = None
            hatch.save()


def warning_free_bar_to_warehouse_manual(request):
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(buy_type='live', trash=False,
                                                               weight_of_carcasses=0, kill_house=kill_house,
                                                               ware_house=False)

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0

            len_kill_house_requests = len(free_bars)
            bars_info = ['کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - تاریخ بار: ({2})'.format
                         (free_bar.bar_clearance_code,
                          to_locale_str(int(free_bar.live_weight)),
                          shamsi_date(free_bar.date))
                         for free_bar in free_bars]
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:یادآوری بارهای وارد نشده به انبار",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد. ***' \
                      '\n' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار خارج استانی به تعداد {to_locale_str(len_kill_house_requests)} بار و وزن زنده {to_locale_str(int(wieght))} کیلوگرم وارد انبار نگردیده است.' \
                      '\n' \
                      f' جزئیات بارهای وارد نشده به انبار:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f'لطفاً در اسرع وقت نسبت به تعیین تکلیف بارهای مربوطه در سامانه اقدام فرمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()
    return HttpResponse('ok')


def warning_free_bar_to_warehouse_cron():
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False).select_related(
        'system_address__province')
    for kill_house in kill_houses:
        free_bars = KillHouseFreeBarInformation.objects.filter(buy_type='live', trash=False,
                                                               weight_of_carcasses=0, kill_house=kill_house,
                                                               ware_house=False)

        if free_bars:
            wieght = \
                free_bars.aggregate(total=Sum('live_weight'))[
                    'total'] or 0

            len_kill_house_requests = len(free_bars)
            bars_info = ['کد قرنطینه: {0} - وزن زنده: {1} کیلوگرم - تاریخ بار: ({2})'.format
                         (free_bar.bar_clearance_code,
                          to_locale_str(int(free_bar.live_weight)),
                          shamsi_date(free_bar.date))
                         for free_bar in free_bars]

            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:یادآوری بارهای وارد نشده به انبار",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد. ***' \
                      '\n' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار خارج استانی به تعداد {to_locale_str(len_kill_house_requests)} بار و وزن زنده {to_locale_str(int(wieght))} کیلوگرم وارد انبار نگردیده است.' \
                      '\n' \
                      f' جزئیات بارهای وارد نشده به انبار:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f'لطفاً در اسرع وقت نسبت به تعیین تکلیف بارهای مربوطه در سامانه اقدام فرمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()


def warning_to_warehouse_cron():
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()

    kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
    for kill_house in kill_houses:
        kill_house_requests = KillHouseRequest.objects.filter(
            Q(killhouse_user=kill_house) | Q(killer=kill_house),
            ware_house_confirmation=False, trash=False, calculate_status=True)
        if kill_house_requests:
            wieght = \
                kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                    'total'] or 0
            len_kill_house_requests = len(kill_house_requests)
            bars_info = ['کد بار: {0} - وزن زنده: {1} کیلوگرم - تاریخ بار: {2}'.format(
                bar.bar_code,
                to_locale_str(int(bar.accepted_real_weight)),
                shamsi_date(bar.kill_request.recive_date))
                for bar in kill_house_requests]

            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:یادآوری بارهای وارد نشده به انبار",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد.' \
                      '***' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار داخل استانی به تعداد {to_locale_str(len_kill_house_requests)} بار و وزن زنده {to_locale_str(int(wieght))} کیلوگرم وارد انبار نگردیده است.' \
                      f'***' \
                      f' جزئیات بارهای وارد نشده به انبار:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f'لطفاً در اسرع وقت نسبت به تعیین تکلیف بارهای مربوطه در سامانه اقدام فرمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()


def warning_to_warehouse_manual(request):
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()

    kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
    for kill_house in kill_houses:
        kill_house_requests = KillHouseRequest.objects.filter(
            Q(killhouse_user=kill_house) | Q(killer=kill_house),
            ware_house_confirmation=False, trash=False, calculate_status=True)
        if kill_house_requests:
            wieght = \
                kill_house_requests.aggregate(total=Sum('accepted_real_weight'))[
                    'total'] or 0
            len_kill_house_requests = len(kill_house_requests)
            bars_info = ['کد بار: {0} - وزن زنده: {1} کیلوگرم - تاریخ بار: ({2})'.format(
                bar.bar_code,
                to_locale_str(int(bar.accepted_real_weight)),
                shamsi_date(bar.kill_request.recive_date))
                for bar in kill_house_requests]
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:یادآوری بارهای وارد نشده به انبار",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد.' \
                      '***' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، محموله بار داخل استانی به تعداد {to_locale_str(len_kill_house_requests)} بار و وزن زنده {to_locale_str(int(wieght))} کیلوگرم وارد انبار نگردیده است.' \
                      f'***' \
                      f' جزئیات بارهای وارد نشده به انبار:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f'لطفاً در اسرع وقت نسبت به تعیین تکلیف بارهای مربوطه در سامانه اقدام فرمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()
    return HttpResponse('ok')


def warning_province_kill_request_without_bar_manual(request):
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
    for kill_house in kill_houses:
        province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
                                                                   state__in=('pending', 'accepted'),
                                                                   archive_wage=False,
                                                                   return_to_province=False,
                                                                   trash=False, first_car_allocated_quantity=0)
        if province_kill_request:
            wieght = province_kill_request.aggregate(total=Sum('quantity'))['total'] or 0
            len_province_kill_request = len(province_kill_request)
            bars_info = []
            for bar in province_kill_request:
                try:
                    order_code = bar.province_request.poultry_request.order_code
                    quantity = to_locale_str(int(bar.quantity))
                    kill_request = getattr(bar.province_request, 'kill_request', None)
                    recive_date = getattr(kill_request, 'recive_date', None)
                    date_str = shamsi_date(recive_date) if recive_date else ''
                    info = 'کد سفارش:{0} - وزن:{1} کیلوگرم - تاریخ تخصیص:{2}'.format(
                        order_code,
                        quantity,
                        date_str
                    )
                    bars_info.append(info)
                except Exception:
                    continue
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:یادآوری تخصیصات بدون بار",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد.' \
                      '***' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، تخصیصات بدون بار به تعداد {to_locale_str(len_province_kill_request)} تخصیص و وزن {to_locale_str(int(wieght))} کیلوگرم فاقد تخصیص ماشین میباشد.' \
                      f'***' \
                      f' جزئیات تخصیصات بدون بار:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f'لطفاً در اسرع وقت نسبت به تعیین تکلیف بارهای مربوطه در سامانه اقدام فرمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()
    return HttpResponse('ok')


def warning_province_kill_request_without_bar_cron():
    user = SystemUserProfile.objects.filter(trash=False, role__name='AdminX').first()
    kill_houses = KillHouse.objects.filter(out_province=False, trash=False)
    for kill_house in kill_houses:
        province_kill_request = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
                                                                   state__in=('pending', 'accepted'),
                                                                   archive_wage=False,
                                                                   return_to_province=False,
                                                                   trash=False, first_car_allocated_quantity=0)
        if province_kill_request:
            wieght = province_kill_request.aggregate(total=Sum('quantity'))['total'] or 0
            len_province_kill_request = len(province_kill_request)
            bars_info = []
            for bar in province_kill_request:
                try:
                    order_code = bar.province_request.poultry_request.order_code
                    quantity = to_locale_str(int(bar.quantity))
                    kill_request = getattr(bar.province_request, 'kill_request', None)
                    recive_date = getattr(kill_request, 'recive_date', None)
                    date_str = shamsi_date(recive_date) if recive_date else ''
                    info = 'کد سفارش:{0} - وزن:{1} کیلوگرم - تاریخ تخصیص:{2}'.format(
                        order_code,
                        quantity,
                        date_str
                    )
                    bars_info.append(info)
                except Exception:
                    continue
            new_ticket = TicketSupport(
                user=kill_house.kill_house_operator.user,
                title="پیام سیستمی:یادآوری تخصیصات بدون بار",
                status='open',
                read_only=True,
                type_ticket='single',
                parent=None,
                last_message='Admin',
            )
            new_ticket.save()
            new_ticket.to_user.add(kill_house.kill_house_operator.user)
            bars_details = "***".join([f"{i + 1}. {info}" for i, info in enumerate(bars_info)])

            message = 'با سلام و احترام این پیام از طرف سامانه میباشد.' \
                      '***' \
                      f'به استحضار می‌رساند مطابق سیستم‌مانیتورینگ سامانه، تخصیصات بدون بار به تعداد {to_locale_str(len_province_kill_request)} تخصیص و وزن {to_locale_str(int(wieght))} کیلوگرم فاقد تخصیص ماشین میباشد.' \
                      f'***' \
                      f' جزئیات تخصیصات بدون بار:' \
                      f'***' \
                      f'{bars_details}' \
                      f'***' \
                      f'لطفاً در اسرع وقت نسبت به تعیین تکلیف بارهای مربوطه در سامانه اقدام فرمایید.' \
                      f'***' \
                      f'با تشکر -ربات هوشمند سامانه رصدیار'
            msg = MessageSupport(
                ticket=new_ticket,
                message=message,
                created_by=user,
                sender='Admin'
            )
            msg.save()


def update_chicken_age_from_login_manual(request):
    poultry_hatching = PoultryHatching.objects.filter(trash=False).only('date', 'chicken_age', 'last_change').order_by(
        '-id')
    now = datetime.now().date()
    for hatching in poultry_hatching:
        now_age = (now - hatching.date.date()).days + 1
        if hatching.archive == False and hatching.allow_hatching == 'pending':
            hatching.chicken_age = now_age
            hatching.save()
        elif hatching.archive == True and hatching.allow_hatching == 'True':
            if hatching.last_change:
                date = datetime.strptime((hatching.last_change['date'].split(' ')[0]), '%Y-%m-%d').date()
                age = (date - hatching.date.date()).days + 1
                if age < 80:
                    hatching.chicken_age = (date - hatching.date.date()).days + 1
                    hatching.save()
        else:
            continue
        if now_age <= 120:
            hatching.now_age = now_age
            hatching.save()

    return HttpResponse('ok')


def fix_duplicate_order_code_cron():
    duplicate_order_codes = (
        PoultryRequest.objects
            .values('order_code')
            .annotate(count=Count('id'))
            .filter(count__gt=1, trash=False)
            .values_list('order_code', flat=True)
    )

    # استخراج شناسه‌های مرغ‌های مرتبط با کدهای تکراری
    poultry_ids = (
        PoultryRequest.objects
            .filter(order_code__in=duplicate_order_codes, trash=False)
            .values_list('poultry__id', flat=True)
            .distinct()
    )

    # مرتب‌سازی مرغ‌ها بر اساس شناسه
    poultries = Poultry.objects.filter(trash=False, id__in=poultry_ids).order_by('id')
    list1 = []
    # بررسی درخواست‌های مرتبط با هر مرغ
    for poultry in poultries:
        requests = PoultryRequest.objects.filter(trash=False, poultry=poultry).order_by('order_code')
        base_order_code = str(poultry.user.base_order)  # فرض بر این است که "user" به درستی تعریف شده است
        last_order = []
        for req in requests:
            if str(req.order_code)[:4] == base_order_code:
                last_order.clear()
                last_order.append(req.order_code)
            # if str(req.order_code)[:4] != base_order_code:
            #     list1.append(req.id)
        if last_order:
            last_num = last_order[0] + 1
            for req in requests:
                if str(req.order_code)[:4] != base_order_code:
                    base_order_code = last_num
                    req.order_code = base_order_code
                    req.save()
                    last_num += 1
            last_order.clear()


def fix_duplicate_order_code_new_cron():
    duplicate_order_codes = (
        PoultryRequest.objects
            .values('order_code')
            .annotate(count=Count('id'))
            .filter(count__gt=1, trash=False)
            .values_list('order_code', flat=True)
    )

    # استخراج شناسه‌های مرغ‌های مرتبط با کدهای تکراری
    poultry_ids = (
        PoultryRequest.objects
            .filter(order_code__in=duplicate_order_codes, trash=False)
            .values_list('poultry__user__id', flat=True)
            .distinct()
    )

    # مرتب‌سازی مرغ‌ها بر اساس شناسه
    poultries = SystemUserProfile.objects.filter(trash=False, id__in=poultry_ids).order_by('id')
    list1 = []
    for user in poultries:
        print(user.id)
        order_code = int(str(user.base_order) + '0001')
        requests = PoultryRequest.objects.filter(trash=False, poultry__user=user).order_by('id')
        for req in requests:
            req.order_code = order_code
            req.save()
            order_code += 1
    # # بررسی درخواست‌های مرتبط با هر مرغ
    # for poultry in poultries:
    #     requests = PoultryRequest.objects.filter(trash=False,poultry=poultry).order_by('order_code')
    #     base_order_code = str(poultry.user.base_order)  # فرض بر این است که "user" به درستی تعریف شده است
    #     last_order=[]
    #     for req in requests:
    #         if str(req.order_code)[:4] == base_order_code:
    #             last_order.clear()
    #             last_order.append(req.order_code)
    #         # if str(req.order_code)[:4] != base_order_code:
    #         #     list1.append(req.id)
    #     if last_order:
    #         last_num=last_order[0] + 1
    #         for req in requests:
    #             if str(req.order_code)[:4] != base_order_code:
    #                 base_order_code = last_num
    #                 req.order_code=base_order_code
    #                 req.save()
    #                 last_num+=1
    #         last_order.clear()


# def fine_cron():
#     now = datetime.now().date()
#     province_kill_requests = ProvinceKillRequest.objects.filter(tarsh=False, return_to_province=False,
#                                                                 kill_request__recive_date__date=now,
#                                                                 state__in=('pending', 'accepted'),
#                                                                 first_car_allocated_quantity=0).select_related(
#         'kill_request', 'province_request', 'province_request__poultry_request',
#         'province_request__poultry_request__hatching')
#     for province_kill_request in province_kill_requests:
#         poultry_request = province_kill_request.province_request.poultry_request
#         hatching = province_kill_request.province_request.poultry_request.hatching
#         province_check = province_kill_request.province_request
#         province_check.quantity += province_kill_request.main_quantity
#         province_check.save()
#         poultry_request.remain_quantity += province_kill_request.main_quantity
#         poultry_request.save()
#         kill_request = KillRequest.objects.get(key=province_kill_request.kill_request.key)
#         kill_request.remain_quantity += province_kill_request.main_quantity
#         kill_request.save()
#         if poultry_request.export == True:
#             hatching.export_killed_weight -= int(int(request.data['quantity']) * poultry_request.Index_weight)
#             hatching.export_killed_quantity -= int(request.data['quantity'])
#         elif poultry_request.free_sale_in_province == True:
#             hatching.free_killed_quantity -= province_kill_request.total_killed_weight
#             # hatching.free_killed_quantity -= int(amount * poultry_request.Index_weight)
#             hatching.free_quantity -= province_kill_request.total_killed_quantity
#             # hatching.free_quantity -= amount
#         else:
#             hatching.governmental_killed_quantity -= province_kill_request.total_killed_weight
#             hatching.governmental_quantity -= province_kill_request.total_killed_quantity
#         hatching.save()
#         province_kill_request.quantity = 0
#         province_kill_request.total_killed_quantity = 0
#         province_kill_request.total_killed_weight = 0
#         province_kill_request.return_to_province = True
#         province_kill_request.returner = {"fullname": user.fullname, "mobile": user.mobile,
#                                           "date": str(datetime.now())}
#         province_kill_request.save()

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import requests
from concurrent.futures import ThreadPoolExecutor


class KillHouseStressTestView(APIView):
    """
    اندپوینتی برای تست فشار (concurrent requests) روی KillHouseMarketInfoViewSet
    """

    def get(self, request):
        # آدرس ویوست اصلی (اینجا تغییر بده به آدرس واقعی خودت)
        target_url = "http://127.0.0.1:8000/kill-house-market-info/?role=KillHouse"
        headers = {
            "Authorization": f"Bearer {request.auth}",  # یا توکن ثابت بذار
        }

        def fetch(i):
            try:
                resp = requests.get(target_url, headers=headers, timeout=10)
                return {"req": i, "status": resp.status_code, "len": len(resp.text)}
            except Exception as e:
                return {"req": i, "error": str(e)}

        results = []
        with ThreadPoolExecutor(max_workers=10) as executor:  # چند تا ریکوست همزمان
            futures = [executor.submit(fetch, i) for i in range(20)]  # 20 بار
            for f in futures:
                results.append(f.result())

        return Response(results, status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user__in=kill_houses, trash=False)
    province_kill_requests.update(warehouse=False)
    kill_house_requests = KillHouseRequest.objects.filter(killhouse_user__in=kill_houses, trash=False)
    kill_house_requests.update(warehouse=False)
    steward_allocations = StewardAllocation.objects.filter(kill_house__in=kill_houses, trash=False)
    steward_allocations.update(warehouse=False)
    kill_house_free_bars = KillHouseFreeBarInformation.objects.filter(kill_house__in=kill_houses, trash=False)
    kill_house_free_bars.update(warehouse=False)
    kill_house_free_sale_bars = KillHouseFreeSaleBarInformation.objects.filter(kill_house__in=kill_houses, trash=False)
    kill_house_free_sale_bars.update(warehouse=False)
    segmentations = PosSegmentation.objects.filter(kill_house__in=kill_houses, trash=False)
    segmentations.update(warehouse=False)
    archives = WarehouseArchive.objects.filter(trash=False, kill_house__in=kill_houses)
    archives.update(warehouse=False)
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_input_province_bars_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(parent_product__name='مرغ گرم', kill_house=kill_house).first()
        kill_house_requests_product_warehousing(product)
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_out_buying_bars_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(parent_product__name='مرغ گرم', kill_house=kill_house).first()
        kill_house_free_buying_product_warehousing(product)
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_in_province_allocations_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(parent_product__name='مرغ گرم', kill_house=kill_house).first()
        kill_house_allocations_product_warehousing(product)
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_free_sale_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(parent_product__name='مرغ گرم', kill_house=kill_house).first()
        kill_house_free_sale_product_warehousing(product)
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_cold_house_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(parent_product__name='مرغ گرم', kill_house=kill_house).first()
        cold_house_allocations = StewardAllocation.objects.filter(kill_house=kill_house, to_cold_house__isnull=False,
                                                                  receiver_state='accepted', warehouse=True)
        kill_house.total_cold_house_governmental_weight = \
            cold_house_allocations.filter(quota='governmental').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0
        kill_house.total_cold_house_free_weight = \
            cold_house_allocations.filter(quota='free').aggregate(total=Sum('real_weight_of_carcasses'))[
                'total'] or 0

        kill_house.save()
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_warehouse_segmentation_for_limitation(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(parent_product__name='مرغ گرم', kill_house=kill_house).first()
        segmentations = PosSegmentation.objects.filter(kill_house=kill_house, trash=False, warehouse=True)
        product.segmentation_weight = \
            segmentations.aggregate(total=Sum('weight'))[
                'total'] or 0
        product.save()
        kill_house.total_segmentation_governmental_weight = \
            segmentations.filter(quota='governmental').aggregate(total=Sum('weight'))[
                'total'] or 0
        kill_house.total_segmentation_free_weight = segmentations.filter(quota='free').aggregate(total=Sum('weight'))[
                                                        'total'] or 0
        kill_house.save()
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_kill_house_archive_warehousing(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        product = RolesProducts.objects.filter(kill_house=kill_house, trash=False, name='مرغ گرم').first()

        archives = WarehouseArchive.objects.filter(kill_house=kill_house, trash=False, warehouse=True)

        archives_info = archives.aggregate(
            archives_weight=Sum('weight'),
            archives_governmental_weight=Sum('weight',
                                             filter=Q(quota='governmental')),
            archives_free_weight=Sum('weight',
                                     filter=Q(quota='free')),

        )
        archives_weight = archives_info['archives_weight'] or 0
        archives_governmental_weight = archives_info['archives_governmental_weight'] or 0
        archives_free_weight = archives_info['archives_free_weight'] or 0
        product.ware_house_archive_weight = archives_weight
        product.save()
        kill_house.ware_house_archive_governmental_weight = archives_governmental_weight
        kill_house.ware_house_archive_free_weight = archives_free_weight
        kill_house.save()
    return Response("ok")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_steward_free_buying_product_warehousing_for_limitation(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.get(parent_product__name='مرغ گرم', guild=steward)
        guild_steward_free_buying_product_warehousing(product)
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_steward_guild_steward_allocations_warehousing_for_limitation(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.get(parent_product__name='مرغ گرم', guild=steward)
        guild_steward_allocations_product_warehousing(product)
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_guild_steward_free_sale_warehousing_for_limitation(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.get(parent_product__name='مرغ گرم', guild=steward)
        guild_steward_free_sale_product_warehousing(product)
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_guild_steward_product_segmentation_warehousing_for_limitation(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.get(parent_product__name='مرغ گرم', guild=steward)
        guild_steward_product_segmentation(product)
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_steward_guild_pos_allocations_warehousing_for_limitation(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.get(parent_product__name='مرغ گرم', guild=steward)
        product.pos_allocated_weight = 0
        product.save()
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_guild_steward_archive_warehousing(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.filter(guild=steward, trash=False, name='مرغ گرم').first()

        archives = WarehouseArchive.objects.filter(Q(steward=steward) | Q(guild=steward), trash=False, warehouse=True)

        archives_info = archives.aggregate(
            archives_weight=Sum('weight'),
            archives_governmental_weight=Sum('weight',
                                             filter=Q(quota='governmental')),
            archives_free_weight=Sum('weight',
                                     filter=Q(quota='free')),

        )
        archives_weight = archives_info['archives_weight'] or 0
        archives_governmental_weight = archives_info['archives_governmental_weight'] or 0
        archives_free_weight = archives_info['archives_free_weight'] or 0
        product.ware_house_archive_weight = archives_weight
        product.save()
        steward.ware_house_archive_governmental_weight = archives_governmental_weight
        steward.ware_house_archive_free_weight = archives_free_weight
        steward.save()
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_guild_steward_pos_allocation_weight_for_product(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    for steward in stewards:
        product = RolesProducts.objects.filter(guild=steward, trash=False, name='مرغ گرم').first()
        transactions = ProductsTransactions.objects.filter(product=product, transaction__paid=True, trash=False,
                                                           warehouse=True)
        product.pos_allocated_weight = transactions.aggregate(total=Sum('cur_weight'))['total'] or 0
        product.save()
        pos_allocated_weight = transactions.aggregate(total=Sum('cur_weight'))['total'] or 0
        pos_governmental_allocated_weight = transactions.filter(price_approved=True).aggregate(total=Sum('cur_weight'))[
                                                'total'] or 0
        pos_free_allocated_weight = transactions.filter(price_approved=False).aggregate(total=Sum('cur_weight'))[
                                        'total'] or 0
        product.guild.pos_allocated_weight = int(pos_allocated_weight / 1000)
        product.guild.pos_governmental_allocated_weight = int(pos_governmental_allocated_weight / 1000)
        product.guild.pos_free_allocated_weight = int(pos_free_allocated_weight / 1000)
        product.guild.save()
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_steward_warehouse_for_limitation(request):
    stewards = Guilds.objects.filter(trash=False, steward=True, active=True)
    guild_steward_allocations = StewardAllocation.objects.filter(
        Q(guilds__in=stewards) | Q(to_guilds__in=stewards) | Q(steward__in=stewards) | Q(to_steward__in=stewards),
        trash=False, calculate_status=True, warehouse=True, steward_warehouse=True)
    guild_steward_allocations.update(steward_warehouse=False)
    guild_steward_free_buying_bars = StewardFreeBarInformation.objects.filter(
        Q(guild__in=stewards) | Q(steward__in=stewards), trash=False, warehouse=True)
    guild_steward_free_buying_bars.update(warehouse=False)

    guild_steward_free_sale_bars = StewardFreeSaleBarInformation.objects.filter(
        Q(guild__in=stewards) | Q(steward__in=stewards), trash=False, warehouse=True)
    guild_steward_free_sale_bars.update(warehouse=False)
    segmentations = PosSegmentation.objects.filter(guild__in=stewards, trash=False)
    segmentations.update(warehouse=False)
    archives = WarehouseArchive.objects.filter(trash=False, steward__in=stewards)
    archives.update(warehouse=False)
    transactions = PosMachineTransactions.objects.filter(pos__guild__in=stewards, paid=True, trash=False)
    transactions.update(warehouse=False)
    product_transactions = ProductsTransactions.objects.filter(transaction__pos__guild__in=stewards,
                                                               transaction__paid=True, trash=False)
    product_transactions.update(warehouse=False)
    return Response("done!")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_time_error(request):
    return Response(datetime.now())


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def fix_pos_owner(request):
    transactions = PosMachineTransactions.objects.filter(live_stock=False, trash=False)
    for transaction in transactions:
        if transaction.pos.kill_house:
            transaction.kill_house = transaction.pos.kill_house

        elif transaction.pos.guild:
            transaction.guild = transaction.pos.guild
        transaction.save()

    return Response("done!")
