from datetime import datetime
import threading

import jdatetime
from django.db.models import Q, Sum, F
from rest_framework import status, viewsets
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny

from authentication.models import SystemUserProfile, UserMessageSend
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.contrib.rest_framework import (
    TokenHasReadWriteScope,
)
from django.http import HttpResponse
import xml.etree.ElementTree as ET

import requests

from rest_framework.response import Response

from deposit_percent import wage_percent
from general_urls import base_url_sms, base_url_for_sms_report, base_pos_id
from panel.KillHouse.helpers import get_finance_info
from panel.helper import UNION_NUMBER, COMPANY_NUMBER, GUILD_NUMBER, UNION_SECOND_NUMBER, SUPPORTER_NUMBER, \
    UNION_THIRD_NUMBER, UNION_FOURTH_NUMBER, UNION_NUMBER_2, COMPANY_NUMBER2, UNION_FIFTH_NUMBER, UNION_SIXTH_NUMBER
from panel.helper_excel import shamsi_date, to_locale_str
from panel.models import KillHouseRequest, VetCheckRequest, KillHouseVet, VetCheckAllocations, KillHouse, \
    KillHouseFreeBarInformation, InternalTransaction, ProvinceKillRequest, Poultry, VetFarm, KillHousePurchaseRequest, \
    OutProvincePoultryRequestBuyer, CityOperator, UserReports, ReportsUsers, LastUpdate, PoultryRequest, \
    CompanyBeneficiaryAccount, ManagementSendSms, StewardAllocation, SmsRecipient
from .sahandsms.sms import USERNAME_SMS, PASSWORD_SMS, USERNAME_SMS_FINANCIAL, PASSWORD_SMS_FINANCIAL, \
    USERNAME_SMS_HAMEDAN, PASSWORD_SMS_HAMEDAN, OUT_SMS_USER, OUT_SMS_PASS
from panel.helper import check_mobile_number
from .serializers import ManagementSendSmsSerializer

management_sms = ManagementSendSms.objects.all()
gate_way = management_sms.filter(name='ارسال بدهی').first()
send_deactivate = management_sms.filter(name='ارسال مسدودی ها').first()
direct_buying = management_sms.filter(name='خرید مستقیم').first()
poultry_request = management_sms.filter(name='درخواست کشتار جدید').first()
poultry_link_out_sale = management_sms.filter(name='ارسال پیامک لینک فروش مرغ به خارج استان').first()
kill_req_market = management_sms.filter(name='پیامک پنل بورسی').first()
poultry_req_market = management_sms.filter(name='پیامک به مرغدار درخواست کشتار مرغدار برای پنل بورسی').first()
steward_allocation = management_sms.filter(name='پیامک کد احراز به مباشر').first()
guild_register = management_sms.filter(name='پیامک کد احراز برای ثبت صنف/مباشر').first()
sms_recipient = management_sms.filter(name='پیامک مرغ زنده و لاشه به شماره های خاص').first()
gate_way_username = gate_way.username
gate_way_password = gate_way.password
send_deactivate_username = send_deactivate.username
send_deactivate_password = send_deactivate.password
direct_buying_username = direct_buying.username
direct_buying_password = direct_buying.password
poultry_request_username = poultry_request.username
poultry_request_password = poultry_request.password
poultry_link_out_sale_username = poultry_link_out_sale.username
poultry_link_out_sale_password = poultry_link_out_sale.password
kill_req_market_username = kill_req_market.username
kill_req_market_password = kill_req_market.password
poultry_req_market_username = poultry_req_market.username
poultry_req_market_password = poultry_req_market.password
steward_allocation_username = steward_allocation.username
steward_allocation_password = steward_allocation.password
guild_register_username = guild_register.username
guild_register_password = guild_register.password
sms_recipient_username = sms_recipient.username
sms_recipient_password = sms_recipient.password


def sanitize_sms_message(message):
    if not message:
        return message
    forbidden_words = {'شاه': 'ش..ه', 'SHAH': 'SH..AH', 'Shah': 'Sh..ah', 'shah': 'sh..ah'}
    cleaned_message = message
    for forbidden, replacement in forbidden_words.items():
        cleaned_message = cleaned_message.replace(forbidden, replacement)
    return cleaned_message


def send_sms_request(url):
    if 'message=' in url:
        parts = url.split('message=')
        if len(parts) == 2:
            before_message = parts[0] + 'message='
            message_and_after = parts[1]
            if '&' in message_and_after:
                message = message_and_after.split('&')[0]
                after_message = '&' + '&'.join(message_and_after.split('&')[1:])
            else:
                message = message_and_after
                after_message = ''
            cleaned_message = sanitize_sms_message(message)
            url = before_message + cleaned_message + after_message
    return requests.get(url)


def transaction_sms_threading(*mobile):
    percentage = CompanyBeneficiaryAccount.objects.filter(trash=False)
    mother_percent = percentage.filter(unique_code=1).first().percent
    for m in mobile:
        for k, v in m.items():
            if k == 'payer':
                payer = v
            if k == 'date':
                date = v
            if k == 'share':
                share = v
                mother_share = ((int(v) * mother_percent) / 100) if mother_percent > 0 else 0

                share = "{:,}".format(int(share))
                mother_share = "{:,}".format(int(mother_share))

            if k == 'mobile':
                phone = v
            if k == 'province':
                province = v
            if k == 'killer':
                killer = v
        check_mobile = check_mobile_number(phone)
        if check_mobile:
            if phone == COMPANY_NUMBER:
                # message = f'تراکنش موفق استان  {province} (سهم شرکت)' \
                #           f'\n' \
                #           f'پرداخت کننده: {killer} {payer} ' \
                #           f'\n' \
                #           f'تاریخ : {date}' \
                #           f'\n' \
                #           f' مبلغ سهم شما : {share} ریال '
                # if COMPANY_NUMBER2 is not None:
                #     req = send_sms_request(
                #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER2}&message={message}")
                message1 = f'تراکنش موفق استان  {province} (سهم شرکت مادر)' \
                           f'\n' \
                           f'پرداخت کننده: {killer} {payer} ' \
                           f'\n' \
                           f'تاریخ : {date}' \
                           f'\n' \
                           f' مبلغ سهم شما : {mother_share} ریال '
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_USER}&from=30002501&to=09121355674&message={message1}")
                # message_kiani = f'تراکنش موفق استان  {province} (سهم محمد کیانی)' \
                #            f'\n' \
                #            f'پرداخت کننده: {killer} {payer} ' \
                #            f'\n' \
                #            f'تاریخ : {date}' \
                #            f'\n' \
                #            f' مبلغ سهم شما : {kiani_share} ریال '
                # req_kiani = send_sms_request(
                #     f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to=09364415690&message={message_kiani}")
                # message_momeni = f'تراکنش موفق استان  {province} (سهم مومنی)' \
                #            f'\n' \
                #            f'پرداخت کننده: {killer} {payer} ' \
                #            f'\n' \
                #            f'تاریخ : {date}' \
                #            f'\n' \
                #            f' مبلغ سهم شما : {momeni_share} ریال '
                # req_momeni = send_sms_request(
                #     f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to=09201917727&message={message_momeni}")

                # req = send_sms_request(
                #     f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message1}")
            # elif phone == UNION_NUMBER:
            #     message = f'تراکنش موفق استان {province} (سهم اتحادیه)' \
            #               f'\n' \
            #               f'پرداخت کننده: {killer} {payer} ' \
            #               f'\n' \
            #               f'تاریخ : {date}' \
            #               f'\n' \
            #               f' مبلغ سهم شما : {share} ریال '
            #     if UNION_THIRD_NUMBER is not None:
            #         req = send_sms_request(
            #             f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")
            #     req = send_sms_request(
            #             f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message}")
            # elif phone == GUILD_NUMBER:
            #     message = f'تراکنش موفق {province} (سهم صنف)' \
            #               f'\n' \
            #               f'پرداخت کننده: {killer} {payer} ' \
            #               f'\n' \
            #               f'تاریخ : {date}' \
            #               f'\n' \
            #               f' مبلغ سهم شما : {share} ریال '
            #     if UNION_THIRD_NUMBER is not None:
            #         req = send_sms_request(
            #             f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")
            #     req = send_sms_request(
            #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message}")
            # else:
            #     message = f'تراکنش موفق' \
            #               f'\n' \
            #               f'پرداخت کننده: {payer}' \
            #               f'\n' \
            #               f'تاریخ : {date}' \
            #               f'\n' \
            #               f' مبلغ سهم شما : {share} ریال '
            # req = send_sms_request(
            #     url=f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendFromUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&message={message}&fromNumber=30002501&toNumber={phone}")


def transaction_sms_threading_in_province(*mobile):
    percentage = CompanyBeneficiaryAccount.objects.filter(trash=False)
    kiani_percent = percentage.filter(unique_code=2).first().percent
    momen_percent = percentage.filter(unique_code=3).first().percent
    for m in mobile:
        for k, v in m.items():
            if k == 'payer':
                payer = v
            if k == 'date':
                date = v
            if k == 'share':
                share = v
                # mother_share=int(v) * 0.06
                kiani_share = ((int(v) * kiani_percent) / 100) if kiani_percent > 0 else 0
                # momeni_share=((int(v) * momen_percent) / 100) if kiani_percent > 0 else 0
                share = "{:,}".format(int(share))
                # mother_share = "{:,}".format(int(mother_share))
                kiani_share = "{:,}".format(int(kiani_share))
                # momeni_share = "{:,}".format(int(momeni_share))
            if k == 'mobile':
                phone = v
            if k == 'province':
                province = v
            if k == 'killer':
                killer = v
        check_mobile = check_mobile_number(phone)
        if check_mobile:
            if phone == COMPANY_NUMBER:
                # message = f'تراکنش موفق استان  {province} (سهم شرکت)' \
                #           f'\n' \
                #           f'پرداخت کننده: {killer} {payer} ' \
                #           f'\n' \
                #           f'تاریخ : {date}' \
                #           f'\n' \
                #           f' مبلغ سهم شما : {share} ریال '
                # if COMPANY_NUMBER2 is not None:
                #     req = send_sms_request(
                #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER2}&message={message}")
                # message1 = f'تراکنش موفق استان  {province} (سهم شرکت مادر)' \
                #           f'\n' \
                #           f'پرداخت کننده: {killer} {payer} ' \
                #           f'\n' \
                #           f'تاریخ : {date}' \
                #           f'\n' \
                #           f' مبلغ سهم شما : {mother_share} ریال '
                # req = send_sms_request(
                #     f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to=09121355674&message={message1}")
                message_kiani = f'تراکنش موفق استان  {province} (سهم محمد کیانی)' \
                                f'\n' \
                                f'پرداخت کننده: {killer} {payer} ' \
                                f'\n' \
                                f'تاریخ : {date}' \
                                f'\n' \
                                f' مبلغ سهم شما : {kiani_share} ریال '
                req_kiani = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to=09364415690&message={message_kiani}")
                # message_momeni = f'تراکنش موفق استان  {province} (سهم مومنی)' \
                #            f'\n' \
                #            f'پرداخت کننده: {killer} {payer} ' \
                #            f'\n' \
                #            f'تاریخ : {date}' \
                #            f'\n' \
                #            f' مبلغ سهم شما : {momeni_share} ریال '
                req_momeni = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={OUT_SMS_USER}&password={OUT_SMS_PASS}&from=30002501&to=09201917727&message={message_kiani}")

                # req = send_sms_request(
                #     f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message1}")
            # elif phone == UNION_NUMBER:
            #     message = f'تراکنش موفق استان {province} (سهم اتحادیه)' \
            #               f'\n' \
            #               f'پرداخت کننده: {killer} {payer} ' \
            #               f'\n' \
            #               f'تاریخ : {date}' \
            #               f'\n' \
            #               f' مبلغ سهم شما : {share} ریال '
            #     if UNION_THIRD_NUMBER is not None:
            #         req = send_sms_request(
            #             f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")
            #     req = send_sms_request(
            #             f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message}")
            # elif phone == GUILD_NUMBER:
            #     message = f'تراکنش موفق {province} (سهم صنف)' \
            #               f'\n' \
            #               f'پرداخت کننده: {killer} {payer} ' \
            #               f'\n' \
            #               f'تاریخ : {date}' \
            #               f'\n' \
            #               f' مبلغ سهم شما : {share} ریال '
            #     if UNION_THIRD_NUMBER is not None:
            #         req = send_sms_request(
            #             f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")
            #     req = send_sms_request(
            #         f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message}")
            # else:
            #     message = f'تراکنش موفق' \
            #               f'\n' \
            #               f'پرداخت کننده: {payer}' \
            #               f'\n' \
            #               f'تاریخ : {date}' \
            #               f'\n' \
            #               f' مبلغ سهم شما : {share} ریال '
            # req = send_sms_request(
            #     url=f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendFromUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&message={message}&fromNumber=30002501&toNumber={phone}")


def transaction_sms_threading_for_company(*mobile):
    pass
    # for m in mobile:
    #     for k, v in m.items():
    #         if k == 'payer':
    #             payer = v
    #         if k == 'date':
    #             date = v
    #         if k == 'share':
    #             share = v
    #             share = "{:,}".format(int(share))
    #         if k == 'mobile':
    #             phone = v
    #         if k == 'province':
    #             province=v
    #         if k == 'killer':
    #             killer=v
    #     message = f'تراکنش موفق استان {province} (کل سهم)' \
    #               f'\n' \
    #               f'پرداخت کننده: {killer} {payer} ' \
    #               f'\n' \
    #               f'تاریخ : {date}' \
    #               f'\n' \
    #               f' مبلغ کل سهم : {share} ریال '
    #     req = send_sms_request(
    #         url=f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendFromUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&message={message}&fromNumber=30002501&toNumber={phone}")


def transaction_sms_threading_appreciation(user, mobile):
    message = f'کاربر گرامی {user}' \
              '\n' \
              'از پرداخت شما سپاسگزاریم.' \
              '\n' \
              '(سامانه رصدیار)'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        req = send_sms_request(
            url=f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendFromUrl?username={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&message={message}&fromNumber=30002501&toNumber={mobile}")


def user_sms_threading(mobile, message):
    for i in mobile:
        check_mobile = check_mobile_number(i)
        if check_mobile:
            req = send_sms_request(
                url=f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendFromUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&message={message}&fromNumber=30002501&toNumber={i}")

    msg = UserMessageSend(

        message=str(message),
    )
    msg.save()


@api_view(["POST"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def user_sms(request):
    operator = SystemUserProfile.objects.get(user=request.user)
    roles = None
    users = None
    message = request.data['message']
    if 'role' in request.data.keys():
        roles = request.data['role']
    if 'user' in request.data.keys():
        users = request.data['user']

    if roles != None and users != None:
        users = SystemUserProfile.objects.filter(role__name__in=roles, key__in=users,
                                                 province=operator.province).only('mobile').order_by('id').values_list(
            'mobile', flat=True)
    elif roles != None:
        users = SystemUserProfile.objects.filter(role__name__in=roles, province=operator.province).only(
            'mobile').order_by('id').values_list('mobile', flat=True)
    else:
        users = SystemUserProfile.objects.filter(key__in=users, province=operator.province).only('mobile').order_by(
            'id').values_list('mobile', flat=True)

    send_sms = threading.Thread(target=user_sms_threading, args=(users, message))
    send_sms.start()

    return Response({'msg': 'send'})


def hatching_sms(mobile, poultry_fullname, quantity, date, chicken_breed, province, city
                 ):
    message = ' ثبت جوجه ریزی جدید:\n مرغدار:{0}\nتعداد:{1}\nتاریخ:{2}\nنژاد:{3}\nآدرس:استان  {4},شهر  {5}'.format(
        poultry_fullname, quantity, date, chicken_breed, province, city)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def operator_hatching_sms(mobile, poultry_fullname, quantity, date, chicken_breed, province, city,

                          ):
    message = ' ثبت جوجه ریزی جدید:\n مرغدار:{0}\nتعداد:{1}\nتاریخ:{2}\nنژاد:{3}\nآدرس:استان  {4},شهر  {5}'.format(
        poultry_fullname, quantity, date, chicken_breed, province, city)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


# USERNAME_SMS
def operator_poultry_request_sms(mobile, poultry_fullname, quantity, chicken_breed,
                                 order_code, send_date, sale_in_province, amount, request_kill_house, poultry_mobile

                                 ):
    sale_type = 'آزاد' if sale_in_province == True else 'دولتی'
    amount = "{:,}".format(int(amount))
    quantity = "{:,}".format(int(quantity))
    message = 'درخواست کشتار جدید' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'نژاد:{chicken_breed}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'نوع فروش:{sale_type}' \
              f'\n' \
              f'مرغدار:{poultry_fullname}' \
              f'\n' \
              f'کدسفارش:{order_code}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'(سامانه رصدیار)' \
        #     message = 'درخواست کشتار\n مرغدار:{0}\nتعداد:{1}\nنژاد:{2}\n  کدسفارش:{3}\nتاریخ کشتار:{4}'.format(
    # poultry_fullname, quantity, chicken_breed,
    # order_code, send_date)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            poultry_request_username, poultry_request_password,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

    if UNION_NUMBER_2 is not None:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={poultry_request_username}&password={poultry_request_password}&from=30002501&to={UNION_NUMBER_2}&message={message}")

    message2 = 'درخواست کشتار جدید' \
               f'\n' \
               f'مرغدار:{poultry_fullname}' \
               f'\n' \
               f'تعداد:{quantity}' \
               f'\n' \
               f'نژاد:{chicken_breed}' \
               f'\n' \
               f'تاریخ کشتار:{send_date}' \
               f'\n' \
               f'نوع فروش:{sale_type}' \
               f'\n' \
               f'کشتارگاه:{request_kill_house}' \
               f'\n' \
               f'کدسفارش:{order_code}' \
               f'\n' \
               f'قیمت :{amount} ریال' \
               f'\n' \
               f'(سامانه رصدیار)'

    req = send_sms_request(
        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={poultry_request_username}&password={poultry_request_password}&from=30002501&to={poultry_mobile}&message={message2}")


# USERNAME_SMS
def operator_out_poultry_request_sms(mobile, poultry_fullname, quantity, chicken_breed,
                                     order_code, send_date, sale_in_province, amount, vet_mobile=None

                                     ):
    sale_type = 'آزاد' if sale_in_province == True else 'دولتی'
    amount = "{:,}".format(int(amount))
    quantity = "{:,}".format(int(quantity))
    message = 'درخواست کشتار آزاد' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'نژاد:{chicken_breed}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'نوع فروش:{sale_type}' \
              f'\n' \
              f'مرغدار:{poultry_fullname}' \
              f'\n' \
              f'کدسفارش:{order_code}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'(سامانه رصدیار)' \
        # message = 'درخواست کشتار آزاد\n مرغدار:{0}\nتعداد:{1}\nنژاد:{2}\n  کدسفارش:{3}\nتاریخ کشتار:{4}'.format(
    #     poultry_fullname, quantity, chicken_breed,
    #     order_code, send_date)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

    if UNION_NUMBER_2 is not None:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_NUMBER_2}&message={message}")
    if vet_mobile is not None:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={vet_mobile}&message={message}")


def poultry_request_receive_city_accept_sms(mobile, send_date, order_code, free_sale_in_province

                                            ):
    sale_type = 'آزاد' if free_sale_in_province == True else 'دولتی'
    message = ' مرغدار گرامی درخواست کشتار شما با نوع:{2} به تاریخ {0} با شماره سفارش:{1} توسط شهرستان تایید شد.'.format(
        send_date, order_code, sale_type)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def poultry_request_receive_province_accept_sms(mobile, order_code
                                                ):
    message = 'درخواست کشتار با کد سفارش:{0} توسط استان تایید شد.'.format(
        order_code)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


# USERNAME_SMS
def confirm_price_poultry_request_sms(mobile, poultry_fullname, quantity, chicken_breed, order_code, send_date,
                                      free_sale_in_province, amount, request_kill_house, confirm_code):
    sale_type = 'آزاد' if free_sale_in_province == True else 'دولتی'

    message = 'درخواست کشتار جدید' \
              f'\n' \
              f'مرغدار:{poultry_fullname}' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'نژاد:{chicken_breed}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'نوع فروش:{sale_type}' \
              f'\n' \
              f'کشتارگاه:{request_kill_house}' \
              f'\n' \
              f'کدسفارش:{order_code}' \
              f'\n' \
              f'قیمت :{amount} ریال' \
              f'\n' \
              f'کداحراز :{confirm_code}' \
              f'\n' \
              f'(سامانه رصدیار)'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            poultry_request_username, poultry_request_password,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


# USERNAME_SMS
def confirm_price_poultry_request_direct_buying_sms(mobile, poultry_fullname, quantity, chicken_breed, send_date,
                                                    free_sale_in_province, amount, request_kill_house, confirm_code):
    sale_type = 'آزاد' if free_sale_in_province == True else 'دولتی'

    message = 'درخواست خرید مستقیم:' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'نوع فروش:{sale_type}' \
              f'\n' \
              f'خریدار:{request_kill_house}' \
              f'\n' \
              f'قیمت :{int(amount)} ریال' \
              f'\n' \
              f'کداحراز :{confirm_code}' \
              f'\n' \
              f'(سامانه رصدیار)'
    # message = 'درخواست خرید مستقیم:' \
    #           f'\n' \
    #           f'مرغدار:{poultry_fullname}' \
    #           f'\n' \
    #           f'تعداد:{quantity}' \
    #           f'\n' \
    #           f'نژاد:{chicken_breed}' \
    #           f'\n' \
    #           f'تاریخ کشتار:{send_date}' \
    #           f'\n' \
    #           f'نوع فروش:{sale_type}' \
    #           f'\n' \
    #           f'خریدار:{request_kill_house}' \
    #           f'\n' \
    #           f'قیمت :{int(amount)} ریال' \
    #           f'\n' \
    #           f'کداحراز :{confirm_code}' \
    #           f'\n' \
    #           f'(سامانه رصدیار)'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            direct_buying_username, direct_buying_password,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)


# USERNAME_SMS
def kill_request_province_sms(mobile, kill_house_name, quantity, chicken_breed, send_date, province, city,

                              ):
    message = ' اعلام نیاز جدید کشتارگاه:\n {0}\n تعداد درخواست:{1}\nنژاد:{2}\nتاریخ کشتار:{3}\nآدرس:استان {4}, شهر {5}\n'.format(
        kill_house_name, quantity, chicken_breed, send_date, province, city)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)
    if UNION_NUMBER_2 is not None:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_NUMBER_2}&message={message}")


def kill_request_delete_province_sms(mobile, kill_house_name, quantity, chicken_breed, send_date, province, city,

                                     ):
    message = 'لغو درخواست کشتار:\n {0}\n تعداد درخواست:{1}\nنژاد:{2}\nتاریخ کشتار:{3}\nآدرس:استان {4}, شهر {5}'.format(
        kill_house_name, quantity, chicken_breed, send_date, province, city)
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def province_kill_request_to_kill_house_sms(mobile, quantity, chicken_breed, send_date, poultry_name,
                                            poultry_mobile, province, city, sale_in_province, amount, kill_house_name

                                            ):
    sale_type = 'آزاد' if sale_in_province == True else 'دولتی'
    amount = "{:,}".format(int(amount))
    quantity = "{:,}".format(int(quantity))
    message = 'تخصیص کشتار جدید' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'نژاد:{chicken_breed}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'نوع فروش:{sale_type}' \
              f'\n' \
              f'خریدار:{kill_house_name}' \
              f'\n' \
              f'مرغدار:{poultry_name}' \
              f'\n' \
              f'تلفن مرغدار:{poultry_mobile}' \
              f'\n' \
              f'آدرس:{province} - {city}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'(سامانه رصدیار)' \
        # message = 'تخصیص کشتار جدید:\n تعداد:{0}\n نژاد: {1}\nتاریخ کشتار:{2}\nمرغدار:{3}\n تلفن مرغدار:{4}\nآدرس:استان {5}, شهر {6}\n '.format(
    #     quantity, chicken_breed, send_date, poultry_name, poultry_mobile, province, city,
    # )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)
    if UNION_NUMBER_2 is not None:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={UNION_NUMBER_2}&message={message}")


def kill_house_province_kill_request_accept_to_province_sms(mobile, provice_operator_name, quantity,
                                                            chicken_breed, send_date, poultry_name,
                                                            poultry_mobile, province, city, kill_house_name,

                                                            ):
    message = ' اپراتور گرامی: {0}\n تعداد {1} مرغ با نژاد: {2}\nدر تاریخ کشتار:{3}\n از مرغدار:{4} با شماره تماس:{5}\nبه آدرس:استان {6}, شهر {7}\n توسط:{8} تایید شد.'.format(
        provice_operator_name, quantity, chicken_breed, send_date, poultry_name, poultry_mobile, province, city,
        kill_house_name
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_request_to_poultry_sms(mobile, quantity, kill_house_name, send_date, driver_name,
                                      driver_mobile,
                                      type_car, pelak

                                      ):
    message = 'اطلاعات تحویل بار:\n تعداد:{0}\nخریدار:{1}\nتاریخ تحویل:{2}\n راننده:{3}\n تلفن راننده:{4}\n ماشین:{5}\n با پلاک {6}'.format(
        quantity, kill_house_name, send_date, driver_name, driver_mobile, type_car, pelak
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_request_to_vet_farm_clearnce_sms(mobile, quantity, index_weight, total_weight, poultry_name,
                                                poultry_mobile, kill_house_user_name, kill_house_user_mobile, send_date,
                                                driver_name,
                                                driver_mobile,
                                                type_car, pelak

                                                ):
    message = 'اطلاعات بار(کد قرنطینه):\n تعداد:{0}\nمیانگین وزن:{1}\nوزن کل:{2}\nفروشنده:{3}-{4}\nخریدار:{5}-{6}\nتاریخ تحویل:{7}\nراننده:{8}-{9}\nماشین:{10}-{11}'.format(
        quantity, index_weight, total_weight, poultry_name, poultry_mobile, kill_house_user_name,
        kill_house_user_mobile, send_date, driver_name,
        driver_mobile,
        type_car, pelak
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_request_to_driver_sms(mobile, send_date, receive_time, quantity, chicken_breed, poultry_name,
                                     poultry_mobile,
                                     poultry_province, poultry_city, poultry_address,
                                     kill_house_name,
                                     kill_house_mobile,
                                     kill_house_province,
                                     kill_house_city, kill_house_address

                                     ):
    message = 'اطلاعات تحویل بار:\nتاریخ:{0}\nازه زمانی:{1}\nتعداد:{2}\nنژاد:{3}\n مبدا:\nمرغدار:{4}\nشماره تماس:{5}\nآدرس:{6},{7},{8}\n مقصد:\nکشتارگاه:{9}\nشماره تماس:{10}\nآدرس:{11},{12},{13}\n'.format(
        send_date, receive_time, quantity, chicken_breed, poultry_name, poultry_mobile,
        poultry_province, poultry_city, poultry_address,
        kill_house_name,
        kill_house_mobile,
        kill_house_province,
        kill_house_city, kill_house_address
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_request_to_vet_farm_sms(mobile, send_date, receive_time, quantity, chicken_breed, poultry_name,
                                       poultry_mobile,
                                       poultry_province, poultry_city, poultry_address,
                                       kill_house_name,
                                       kill_house_mobile,
                                       kill_house_province,
                                       kill_house_city, kill_house_address,
                                       driver_name,
                                       driver_mobile,
                                       driver_car,
                                       pelak,

                                       ):
    message = 'اعلام کد ترخیص:\nتاریخ:{0}\nبازه زمانی:{1}\nتعداد:{2}\nنژاد:{3}\n مبدا:\nمرغدار:{4}\nشماره تماس:{5}\nآدرس:{6},{7},{8}\n مقصد:\nکشتارگاه:{9}\nشماره تماس:{10}\nآدرس:{11},{12},{13}\راننده:{14}\n تلفن راننده:{15}\n ماشین:{16}\n با پلاک {17}'.format(
        send_date, receive_time, quantity, chicken_breed, poultry_name, poultry_mobile,
        poultry_province, poultry_city, poultry_address,
        kill_house_name,
        kill_house_mobile,
        kill_house_province,
        kill_house_city, kill_house_address,
        driver_name,
        driver_mobile,
        driver_car,
        pelak,
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_request_to_kill_house_vet_sms(mobile, send_date, receive_time, quantity, chicken_breed, poultry_name,
                                             driver_name,
                                             driver_car,
                                             pelak,

                                             ):
    message = 'اعلام تحویل بار:\nتاریخ:{0}\nبازه زمانی:{1}\nتعداد:{2}\nنژاد:{3}\nاز مرغدار:{4}\nراننده:{5}\nماشین:{6}\nبا پلاک {7}\nتحویل شما داده میشود.'.format(
        send_date, receive_time, quantity, chicken_breed, poultry_name,
        driver_name,
        driver_car,
        pelak,
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_vet_to_poultry_sms(mobile, send_date, receive_time, quantity, chicken_breed, poultry_name,
                                  driver_name,
                                  driver_car,
                                  pelak,

                                  ):
    message = 'اعلام تاییدتحویل بار:\nتاریخ:{0}\nبازه زمانی:{1}\nتعداد:{2}\nنژاد:{3}\nاز مرغدار:{4}\nراننده:{5}\nماشین:{6}\nبا پلاک {7}\nتحویل کشتارگاه شد.'.format(
        send_date, receive_time, quantity, chicken_breed, poultry_name,
        driver_name,
        driver_car,
        pelak,
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_vet_to_province_sms(mobile, send_date, receive_time, quantity, chicken_breed, poultry_name,
                                   driver_name,
                                   driver_car,
                                   pelak,

                                   ):
    message = 'اعلام تاییدتحویل بار:\nتاریخ:{0}\nبازه زمانی:{1}\nتعداد:{2}\nنژاد:{3}\nاز مرغدار:{4}\nراننده:{5}\nماشین:{6}\nبا پلاک {7}\nتحویل کشتارگاه شد.'.format(
        send_date, receive_time, quantity, chicken_breed, poultry_name,
        driver_name,
        driver_car,
        pelak,
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_vet_to_kill_house_sms(mobile, send_date, receive_time, quantity, chicken_breed, poultry_name,
                                     driver_name,
                                     driver_car,
                                     pelak,

                                     ):
    message = 'اعلام تاییدتحویل بار:\nتاریخ:{0}\nبازه زمانی:{1}\nتعداد:{2}\nنژاد:{3}\nاز مرغدار:{4}\nراننده:{5}\nماشین:{6}\nبا پلاک {7}\nتحویل کشتارگاه شد.'.format(
        send_date, receive_time, quantity, chicken_breed, poultry_name,
        driver_name,
        driver_car,
        pelak,
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def province_kill_request_reject_sms(mobile, kill_house_name
                                     ):
    message = ' کاربر گرامی: {0}\n درخواست اولیه کشتار شما توسط استان رد شد.'.format(
        kill_house_name
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def allow_poultry_city_province_sms(mobile, Poultry_name
                                    ):
    message = ' کاربر گرامی:\nوکالت ثبت درخواست کشتار توسط مرغدار:{} برای شما صادر شد.'.format(
        Poultry_name
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def allow_poultry_city_for_poultry_sms(mobile, Poultry_name
                                       ):
    message = ' مرغدار گرامی:{0}\n وکالت ثبت درخواست کشتار توسط شما برای شهرستان ثیت شد.'.format(
        Poultry_name
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def allow_poultry_province_for_poultry_sms(mobile, Poultry_name
                                           ):
    message = ' مرغدار گرامی:{0}\n وکالت ثبت درخواست کشتار توسط شما برای استان ثیت شد.'.format(
        Poultry_name
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def kill_house_vet_check_receive_sms(request):
    url = 'http://webservice.sahandsms.com/NewSMSWebService.asmx/RecieveSMS'
    params = {'Username': USERNAME_SMS, 'password': PASSWORD_SMS, 'phNo': '30002501', 'startdate': '5/1/2023',
              'enddate': '6/2/2023'}
    response = send_sms_request(url, params=params)
    if response.status_code != 200:
        pass
    else:

        xml_str = response.content
        root = ET.fromstring(xml_str)
        mobile = root.iter('RcvSmsfrom')
        text = root.iter('RcvSmsText')

        for m, t in zip(mobile, text):
            kill_house_request = KillHouseRequest.objects.filter(trash=False, bar_code=t.text).first()
            if kill_house_request:
                vet = KillHouseVet.objects.filter(vet__user__mobile=m.text
                                                  , trash=False,
                                                  kill_house=kill_house_request.killhouse_user).first()
                if vet:
                    kill_house_request.vet_state = "accepted"
                    kill_house_request.save()
                    vet_check_request = VetCheckRequest(
                        kill_house_vet=vet,
                        kill_house_request=kill_house_request,
                        state='accepted'

                    )
                    vet_check_request.save()


def steward_allocation_sms(mobile, date, weight, seller, number,
                           buyer, amount):
    message = 'اطلاعات خرید گوشت مرغ\n' \
              'فروشنده: {0} \n' \
              'تاریخ فروش: {1}\n' \
              'وزن سفارش: {2} (کیلوگرم)\n' \
              'مبلغ هر کیلو: {3} (ریال)\n' \
              'کد احراز: {4}\n' \
              'سامانه رصدیار'.format(seller, date, to_locale_str(weight), to_locale_str(amount), number)

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={steward_allocation_username}"
            f"&password={steward_allocation_password}&from=30002501&to={mobile}&message={message}")


def direct_buying_code_sms(mobile, buyer, buyer_mobile, quantity, kill_place, date, code
                           ):
    message = 'درخواست خرید مستقیم:\nخریدار:{0}-{1}\nتعداد:{2}\nمحل کشتار:{3}\nتاریخ:{4}\nکد احراز:{5}'.format(
        buyer, buyer_mobile, quantity, kill_place, date, code
    )
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


# USERNAME_SMS
def export_code_sms(mobile, buyer, buyer_mobile, quantity, kill_place, date, export_country, code
                    , poultry_name, province_mobile):
    message = f'درخواست خرید برای صادرات:' \
              f'\n' \
              f'مرغدار:{poultry_name}' \
              f'\n' \
              f'تلفن مرغدار:{mobile}' \
              f'\n' \
              f'خریدار:{buyer}' \
              f'\n' \
              f'تلفن خریدار:{buyer_mobile}' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'محل کشتار:{kill_place}' \
              f'\n' \
              f'تاریخ:{date}' \
              f'\n' \
              f'کشور مقصد:{export_country}' \
              f'\n' \
              f'کد احراز:{code}' \
              f'\n' \
              f'(سامانه رصدیار)'

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password="
            f"{PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
        send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password="
            f"{PASSWORD_SMS}&from=30002501&to={province_mobile}&message={message}")


def steward2_allocation_sms(mobile=None):
    message = 'مورخ  تعداد  با وزن کیلوگرم از طرف کشتارگاه به شما تخصیص داده شد \n کد احراز:'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        response = requests.request("GET", url, headers=headers, data=payload)

        print(response.text)


def send_discharge_bar(text, mobile):
    user_name = USERNAME_SMS
    password = PASSWORD_SMS
    message = f' بار با شماره {text} با موفقیت تایید تخلیه شد.'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = (f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username="
             f"{user_name}&password={password}&from=30002501&to={mobile}&message={message}")

        url = u.format()

        payload = {}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}

        requests.request("GET", url, headers=headers, data=payload)


def receive_sms_panel():
    now = datetime.now().date()
    user_name = USERNAME_SMS
    password = PASSWORD_SMS

    url = 'http://webservice.sahandsms.com/NewSMSWebService.asmx/RecieveSMS'
    params = {f'Username': {user_name}, 'password': {password}, 'phNo': '30002501', 'startdate': {now},
              'enddate': {now}}

    response = send_sms_request(url, params=params)

    xml_str = response.content
    root = ET.fromstring(xml_str)
    mobile = root.iter('RcvSmsfrom')
    text = root.iter('RcvSmsText')

    for m, t in zip(mobile, text):
        try:
            kill_house_request = KillHouseRequest.objects.filter(trash=False, bar_code=t.text,
                                                                 vet_state='pending').first()
        except:
            continue
        if kill_house_request:
            kill_house_vet = KillHouseVet.objects.filter(vet__user__mobile=m.text,
                                                         kill_house=kill_house_request.killhouse_user).first()
            if kill_house_vet:
                kill_house_request.vet_state = 'complate'
                VetCheckRequest.objects.create(
                    kill_house_vet=kill_house_vet,
                    kill_house_request=kill_house_request,
                    state='complete'
                )
                VetCheckAllocations.objects.create(
                    vet=kill_house_vet.vet,
                    kill_house_request=kill_house_request
                )
                kill_house_request.save()
                send_sms = threading.Thread(target=send_discharge_bar, args=(t.text, m.text))
                send_sms.start()


def condition_of_sms(request):
    query = UserMessageSend.objects.filter(trash=False).select_related('user')
    list1 = []
    for q in query:
        if len(q.receive_code) > 3:
            req = send_sms_request(
                url=f"http://webservice.sahandsms.com/newsmswebservice.asmx/GetQueueMessageStatus?username={USERNAME_SMS}&password={PASSWORD_SMS}&MessageIds={q.receive_code}"
            )
            root = ET.fromstring(req.content)
            int_value = int(root.find('.//{http://tempuri.org/}int').text)
        else:
            int_value = None
        dict1 = {
            "role": q.user.role.name,
            "user": q.user.fullname,
            "mobile": q.user.mobile,
            "message": q.message,
            "create_date": q.create_date,
            'receive_code': int_value,
        }
        list1.append(dict1)
    return HttpResponse(list1)


def send_gate_way_sms():
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False).select_related('kill_house_operator__user') \
        .only('name', 'killer', 'kill_house_operator__user__user_gate_way_id', 'kill_house_operator__user__mobile')
    for kill_house in kill_houses:
        total_paid_wage = 0
        total_unpaid_wage = get_finance_info(kill_house)['total_price']
        # province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
        #                                                             state__in=('pending', 'accepted'),
        #                                                             trash=False,
        #                                                             return_to_province=False,
        #                                                             first_car_allocated_quantity=0,
        #                                                             archive_wage=False,
        #                                                             ).exclude(union_share=0, company_share=0,
        #                                                                       guilds_share=0).only(
        #     'total_killed_weight', 'union_share', 'company_share',
        #     'guilds_share', 'total_wage_amount', 'total_killed_quantity')
        # freezing_province_kill_requests = province_kill_requests.filter(
        #     province_request__poultry_request__freezing=True).only('total_killed_weight', 'union_share',
        #                                                            'company_share',
        #                                                            'guilds_share', 'total_wage_amount',
        #                                                            'total_killed_quantity')
        #
        # kill_house_requests = KillHouseRequest.objects.filter(
        #     Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q(
        #         Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q(
        #         Q(killer__isnull=True) | Q(killer=kill_house)),
        #     archive_wage=False,
        #     trash=False
        # ).select_related('province_kill_request').only('accepted_real_weight',
        #                                                'province_kill_request__union_share_percent',
        #                                                'province_kill_request__wage', 'accepted_real_weight',
        #                                                'province_kill_request__guilds_share_percent',
        #                                                'province_kill_request__company_share_percent',
        #                                                'accepted_real_quantity', 'accepted_real_quantity')
        # kill_house_requests = kill_house_requests.filter(
        #     Q(killer=kill_house) | Q(killhouse_user=kill_house)).select_related(
        #     'province_kill_request').only(
        #     'accepted_real_weight', 'province_kill_request__union_share_percent',
        #     'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent',
        #     'province_kill_request__company_share_percent', 'accepted_real_quantity')
        #
        # freezing_kill_house_requests = kill_house_requests.filter(
        #     province_kill_request__province_request__poultry_request__freezing=True).select_related(
        #     'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent',
        #                                   'province_kill_request__wage', 'accepted_real_weight',
        #                                   'province_kill_request__guilds_share_percent',
        #                                   'province_kill_request__company_share_percent', 'accepted_real_quantity')
        #
        # free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, archive_wage=False,
        #                                                        trash=False).only('live_weight', 'union_share',
        #                                                                          'weight_of_carcasses',
        #                                                                          'company_share',
        #                                                                          'guilds_share',
        #                                                                          'total_wage_amount')
        # free_bars_live = free_bars.filter(buy_type='live', trash=False).only('live_weight', 'union_share',
        #                                                                      'weight_of_carcasses',
        #                                                                      'company_share',
        #                                                                      'guilds_share',
        #                                                                      'total_wage_amount')
        # free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False).only('live_weight', 'union_share',
        #                                                                             'weight_of_carcasses',
        #                                                                             'company_share',
        #                                                                             'guilds_share',
        #                                                                             'total_wage_amount'
        #                                                                             )
        #
        #
        # province_kill_requests_total_wage = \
        #     province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate(
        #         total=Sum('total_wage_amount'))[
        #         'total'] or 0
        # if wage_percent > 0:
        #     province_kill_requests_total_wage -= province_kill_requests_total_wage * wage_percent
        # freezing_province_kill_request_total_wage = \
        #     freezing_province_kill_requests.aggregate(total=Sum('total_wage_amount'))['total'] or 0
        #
        # kill_house_reqest_total_wage = \
        #     kill_house_requests.filter(
        #         province_kill_request__province_request__poultry_request__freezing=False).aggregate(
        #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
        #         'total'] or 0
        # if wage_percent > 0:
        #     kill_house_reqest_total_wage -= kill_house_reqest_total_wage * wage_percent
        # freezing_kill_house_reqest_total_wage = \
        #     freezing_kill_house_requests.aggregate(
        #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
        #         'total'] or 0
        #
        # free_bars_live_total_wage = free_bars_live.aggregate(total=Sum('total_wage_amount'))[
        #                                 'total'] or 0
        #
        # free_bars_carcases_total_wage = free_bars_carcases.aggregate(total=Sum('total_wage_amount'))[
        #                                     'total'] or 0
        # total_unpaid_wage = free_bars_carcases_total_wage + kill_house_reqest_total_wage + \
        #                     freezing_kill_house_reqest_total_wage + province_kill_requests_total_wage + \
        #                     freezing_province_kill_request_total_wage + free_bars_live_total_wage
        slaughter_transactions = InternalTransaction.objects.filter(
            Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed',
            trash=False).only('union_share', 'company_share', 'guilds_share', 'amount')
        total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[
                              'total'] or 0

        if kill_house.killer == False:
            killer = 'کشتارگاه'
        else:
            killer = 'کشتارکن'
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()

        total_wage = total_unpaid_wage - (total_paid_wage + kill_house.off)
        unpaid = "{:,}".format(int(total_wage))
        user_token = 'k' + kill_house.kill_house_operator.user.user_gate_way_id
        message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                  '\n' \
                  'باسلام' \
                  '\n' \
                  f'مبلغ بدهی تعرفه شما {unpaid} ریال می باشدبا توجه به سقف مجاز  بدهی تعیین شده، در اسرع وقت اقدام به پرداخت تعرفه خود کنید.' \
                  '\n' \
                  f'https://rasadyar.net/pay/{base_pos_id}/{user_token}' \
                  f'\n' \
                  f'(سامانه رصدیار)'

        if kill_house_purchase and kill_house_purchase.limitation_number <= total_wage and \
                kill_house_purchase.limitation == True:
            continue
        else:
            if int(total_wage) > 0:
                # if kill_house_purchase.limitation_number > total_wage:
                #     debt=int(kill_house_purchase.limitation_number*0.5)
                # if int(total_wage >= debt):
                check_mobile = check_mobile_number(kill_house.kill_house_operator.user.mobile)
                if check_mobile:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={kill_house.kill_house_operator.user.mobile}&message={message}")
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={COMPANY_NUMBER}&message={message}")
                if UNION_THIRD_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")

                if UNION_FOURTH_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={UNION_FOURTH_NUMBER}&message={message}")


# OUT_SMS_PASS
def send_gate_way_sms_manual(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False).select_related('kill_house_operator__user') \
        .only('name', 'killer', 'kill_house_operator__user__user_gate_way_id', 'kill_house_operator__user__mobile')
    for kill_house in kill_houses:
        total_paid_wage = 0
        total_unpaid_wage = get_finance_info(kill_house)['total_price']
        # province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
        #                                                             state__in=('pending', 'accepted'),
        #                                                             trash=False,
        #                                                             return_to_province=False,
        #                                                             first_car_allocated_quantity=0,
        #                                                             archive_wage=False,
        #                                                             ).exclude(union_share=0, company_share=0,
        #                                                                       guilds_share=0).only(
        #     'total_killed_weight', 'union_share', 'company_share',
        #     'guilds_share', 'total_wage_amount', 'total_killed_quantity')
        # freezing_province_kill_requests = province_kill_requests.filter(
        #     province_request__poultry_request__freezing=True).only('total_killed_weight', 'union_share',
        #                                                            'company_share',
        #                                                            'guilds_share', 'total_wage_amount',
        #                                                            'total_killed_quantity')
        #
        # kill_house_requests = KillHouseRequest.objects.filter(
        #     Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q(
        #         Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q(
        #         Q(killer__isnull=True) | Q(killer=kill_house)),
        #     archive_wage=False,
        #     trash=False
        # ).select_related('province_kill_request').only('accepted_real_weight',
        #                                                'province_kill_request__union_share_percent',
        #                                                'province_kill_request__wage', 'accepted_real_weight',
        #                                                'province_kill_request__guilds_share_percent',
        #                                                'province_kill_request__company_share_percent',
        #                                                'accepted_real_quantity', 'accepted_real_quantity')
        # kill_house_requests = kill_house_requests.filter(
        #     Q(killer=kill_house) | Q(killhouse_user=kill_house)).select_related(
        #     'province_kill_request').only(
        #     'accepted_real_weight', 'province_kill_request__union_share_percent',
        #     'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent',
        #     'province_kill_request__company_share_percent', 'accepted_real_quantity')
        #
        # freezing_kill_house_requests = kill_house_requests.filter(
        #     province_kill_request__province_request__poultry_request__freezing=True).select_related(
        #     'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent',
        #                                   'province_kill_request__wage', 'accepted_real_weight',
        #                                   'province_kill_request__guilds_share_percent',
        #                                   'province_kill_request__company_share_percent', 'accepted_real_quantity')
        #
        # free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, archive_wage=False,
        #                                                        trash=False).only('live_weight', 'union_share',
        #                                                                          'weight_of_carcasses',
        #                                                                          'company_share',
        #                                                                          'guilds_share',
        #                                                                          'total_wage_amount')
        # free_bars_live = free_bars.filter(buy_type='live', trash=False).only('live_weight', 'union_share',
        #                                                                      'weight_of_carcasses',
        #                                                                      'company_share',
        #                                                                      'guilds_share',
        #                                                                      'total_wage_amount')
        # free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False).only('live_weight', 'union_share',
        #                                                                             'weight_of_carcasses',
        #                                                                             'company_share',
        #                                                                             'guilds_share',
        #                                                                             'total_wage_amount'
        #                                                                             )
        #
        #
        # province_kill_requests_total_wage = \
        #     province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate(
        #         total=Sum('total_wage_amount'))[
        #         'total'] or 0
        # if wage_percent > 0:
        #     province_kill_requests_total_wage -= province_kill_requests_total_wage * wage_percent
        # freezing_province_kill_request_total_wage = \
        #     freezing_province_kill_requests.aggregate(total=Sum('total_wage_amount'))['total'] or 0
        #
        # kill_house_reqest_total_wage = \
        #     kill_house_requests.filter(
        #         province_kill_request__province_request__poultry_request__freezing=False).aggregate(
        #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
        #         'total'] or 0
        # if wage_percent > 0:
        #     kill_house_reqest_total_wage -= kill_house_reqest_total_wage * wage_percent
        # freezing_kill_house_reqest_total_wage = \
        #     freezing_kill_house_requests.aggregate(
        #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
        #         'total'] or 0
        #
        # free_bars_live_total_wage = free_bars_live.aggregate(total=Sum('total_wage_amount'))[
        #                                 'total'] or 0
        #
        # free_bars_carcases_total_wage = free_bars_carcases.aggregate(total=Sum('total_wage_amount'))[
        #                                     'total'] or 0
        # total_unpaid_wage = free_bars_carcases_total_wage + kill_house_reqest_total_wage + \
        #                     freezing_kill_house_reqest_total_wage + province_kill_requests_total_wage + \
        #                     freezing_province_kill_request_total_wage + free_bars_live_total_wage
        slaughter_transactions = InternalTransaction.objects.filter(
            Q(kill_house=kill_house) | Q(parent_kill_house=kill_house), status='completed',
            trash=False).only('union_share', 'company_share', 'guilds_share', 'amount')
        total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[
                              'total'] or 0

        if kill_house.killer == False:
            killer = 'کشتارگاه'
        else:
            killer = 'کشتارکن'
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(kill_house=kill_house).first()

        total_wage = total_unpaid_wage - (total_paid_wage + kill_house.off)
        unpaid = "{:,}".format(int(total_wage))
        user_token = 'k' + kill_house.kill_house_operator.user.user_gate_way_id
        message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                  '\n' \
                  'باسلام' \
                  '\n' \
                  f'مبلغ بدهی تعرفه شما {unpaid} ریال می باشدبا توجه به سقف مجاز  بدهی تعیین شده، در اسرع وقت اقدام به پرداخت تعرفه خود کنید.' \
                  '\n' \
                  f'https://rasadyar.net/pay/{base_pos_id}/{user_token}' \
                  f'\n' \
                  f'(سامانه رصدیار)'

        if kill_house_purchase and kill_house_purchase.limitation_number <= total_wage and \
                kill_house_purchase.limitation == True:
            continue
        else:
            if int(total_wage) > 0:
                # if kill_house_purchase.limitation_number > total_wage:
                #     debt=int(kill_house_purchase.limitation_number*0.5)
                # if int(total_wage >= debt):
                check_mobile = check_mobile_number(kill_house.kill_house_operator.user.mobile)
                if check_mobile:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={kill_house.kill_house_operator.user.mobile}&message={message}")
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={COMPANY_NUMBER}&message={message}")
                if UNION_THIRD_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")

                if UNION_FOURTH_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={gate_way_username}&password={gate_way_password}&from=30002501&to={UNION_FOURTH_NUMBER}&message={message}")
    return HttpResponse('ok')


def send_province_request_pdf_sms():
    mobile = [UNION_NUMBER]
    date = datetime.now().date()
    province_kill_requests = ProvinceKillRequest.objects.filter(kill_request__recive_date__date=date, trash=False,
                                                                state__in=('pending', 'accepted'),
                                                                return_to_province=False)
    poultry = Poultry.objects.filter(
        key__in=province_kill_requests.values_list('province_request__poultry_request__poultry__key', flat=True))
    vat_farm = VetFarm.objects.filter(trash=False, poultry__in=poultry).values_list('vet__user__mobile',
                                                                                    flat=True).distinct()
    mobile.extend(vat_farm)
    message = 'کاربرگرامی' \
              '\n' \
              'جهت دریافت گزارش روزانه تخصیص مرغ استان بر روی لینک کلیک کنید:' \
              '\n' \
              f'https://{base_url_sms}.rasadyaar.ir/reports/ds'
    for m in mobile:
        check_mobile = check_mobile_number(m)
        if check_mobile:
            req = send_sms_request(
                f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={m}&message={message}")


def send_deactivate_panel_debt_sms():
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(limitation=True, kill_house=kill_house).first()
        if kill_house_purchase:
            total_unpaid_wage = get_finance_info(kill_house)['total_price']
            total_paid_wage = 0
            # province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
            #                                                             state__in=('pending', 'accepted'),
            #                                                             trash=False,
            #                                                             return_to_province=False,
            #                                                             first_car_allocated_quantity=0,
            #                                                             archive_wage=False,
            #                                                             ).exclude(union_share=0, company_share=0,
            #                                                                       guilds_share=0).only(
            #     'total_killed_weight', 'union_share', 'company_share',
            #     'guilds_share', 'total_wage_amount', 'total_killed_quantity')
            # freezing_province_kill_requests = province_kill_requests.filter(
            #     province_request__poultry_request__freezing=True).only('total_killed_weight', 'union_share',
            #                                                            'company_share',
            #                                                            'guilds_share', 'total_wage_amount',
            #                                                            'total_killed_quantity')
            #
            # kill_house_requests = KillHouseRequest.objects.filter(
            #     Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q(
            #         Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q(
            #         Q(killer__isnull=True) | Q(killer=kill_house)),
            #     archive_wage=False,
            #     trash=False
            # ).select_related('province_kill_request').only('accepted_real_weight',
            #                                                'province_kill_request__union_share_percent',
            #                                                'province_kill_request__wage', 'accepted_real_weight',
            #                                                'province_kill_request__guilds_share_percent',
            #                                                'province_kill_request__company_share_percent',
            #                                                'accepted_real_quantity', 'accepted_real_quantity')
            # kill_house_requests = kill_house_requests.filter(Q(killer=kill_house) | Q(killhouse_user=kill_house)).select_related(
            #     'province_kill_request').only(
            #     'accepted_real_weight', 'province_kill_request__union_share_percent',
            #     'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent',
            #     'province_kill_request__company_share_percent', 'accepted_real_quantity')
            #
            # freezing_kill_house_requests = kill_house_requests.filter(
            #     province_kill_request__province_request__poultry_request__freezing=True).select_related(
            #     'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent',
            #                                   'province_kill_request__wage', 'accepted_real_weight',
            #                                   'province_kill_request__guilds_share_percent',
            #                                   'province_kill_request__company_share_percent', 'accepted_real_quantity')
            #
            # free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, archive_wage=False,
            #                                                        trash=False).only('live_weight', 'union_share',
            #                                                                          'weight_of_carcasses',
            #                                                                          'company_share',
            #                                                                          'guilds_share',
            #                                                                          'total_wage_amount')
            # free_bars_live = free_bars.filter(buy_type='live', trash=False).only('live_weight', 'union_share',
            #                                                                      'weight_of_carcasses',
            #                                                                      'company_share',
            #                                                                      'guilds_share',
            #                                                                      'total_wage_amount')
            # free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False).only('live_weight', 'union_share',
            #                                                                             'weight_of_carcasses',
            #                                                                             'company_share',
            #                                                                             'guilds_share',
            #                                                                             'total_wage_amount'
            #                                                                             )
            slaughter_transactions = InternalTransaction.objects.filter(
                Q(kill_house=kill_house) | Q(parent_kill_house=kill_house),
                status='completed',
                trash=False).only('union_share', 'company_share', 'guilds_share', 'amount')

            # province_kill_requests_total_wage = \
            #     province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate(
            #         total=Sum('total_wage_amount'))[
            #         'total'] or 0
            # if wage_percent > 0:
            #     province_kill_requests_total_wage -= province_kill_requests_total_wage * wage_percent
            # freezing_province_kill_request_total_wage = \
            #     freezing_province_kill_requests.aggregate(total=Sum('total_wage_amount'))['total'] or 0
            #
            # kill_house_reqest_total_wage = \
            #     kill_house_requests.filter(
            #         province_kill_request__province_request__poultry_request__freezing=False).aggregate(
            #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
            #         'total'] or 0
            # if wage_percent > 0:
            #     kill_house_reqest_total_wage -= kill_house_reqest_total_wage * wage_percent
            # freezing_kill_house_reqest_total_wage = \
            #     freezing_kill_house_requests.aggregate(
            #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
            #         'total'] or 0
            #
            # free_bars_live_total_wage = free_bars_live.aggregate(total=Sum('total_wage_amount'))[
            #                                 'total'] or 0
            #
            # free_bars_carcases_total_wage = free_bars_carcases.aggregate(total=Sum('total_wage_amount'))[
            #                                     'total'] or 0
            # total_unpaid_wage = free_bars_carcases_total_wage + kill_house_reqest_total_wage + \
            #              freezing_kill_house_reqest_total_wage + province_kill_requests_total_wage + \
            #              freezing_province_kill_request_total_wage + free_bars_live_total_wage

            total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[
                                  'total'] or 0
            total_wage = total_unpaid_wage - (total_paid_wage + kill_house.off)
            if kill_house_purchase.limitation_number <= total_wage:
                unpaid = "{:,}".format(int(total_wage))
                if kill_house.killer == False:
                    killer = 'کشتارگاه'
                else:
                    killer = 'کشتارکن'
                amount = "{:,}".format(int(kill_house_purchase.limitation_number))
                user_token = 'k' + kill_house.kill_house_operator.user.user_gate_way_id
                message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                          f'\n' \
                          f'باسلام واحترام ' \
                          f'\n' \
                          f'باتوجه به عدم پرداخت  بدهی تعرفه سامانه به مبلغ{unpaid} امکان ثبت کشتار برای شما وجود ندارد.جهت فعال سازی پنل، بدهی شما باید کمتر از {amount} ریال باشد.' \
                          f'\n' \
                          f'لازم به توضیح است که کشتار خارج از سامانه به عنوان کشتار و عرضه خارج از شبکه محسوب میگردد.' \
                          f'\n' \
                          f'لینک مشاهده و پرداخت بدهی:' \
                          f'\n' \
                          f'https://rasadyar.net/pay/{base_pos_id}/{user_token} \n' \
                          f'\n' \
                          f'(سامانه رصدیار)'
                check_mobile = check_mobile_number(kill_house.kill_house_operator.user.mobile)
                if check_mobile:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={kill_house.kill_house_operator.user.mobile}&message={message}")
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={COMPANY_NUMBER}&message={message}")
                if UNION_SECOND_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_SECOND_NUMBER}&message={message}")
                if UNION_THIRD_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")
                if UNION_FIFTH_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_FIFTH_NUMBER}&message={message}")
                if UNION_SIXTH_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_SIXTH_NUMBER}&message={message}")


# OUT_SMS_PASS
def send_deactivate_panel_debt_sms_manual(request):
    kill_houses = KillHouse.objects.filter(trash=False, out_province=False)
    for kill_house in kill_houses:
        kill_house_purchase = KillHousePurchaseRequest.objects.filter(limitation=True, kill_house=kill_house).first()
        if kill_house_purchase:
            total_unpaid_wage = get_finance_info(kill_house)['total_price']
            total_paid_wage = 0
            # province_kill_requests = ProvinceKillRequest.objects.filter(killhouse_user=kill_house,
            #                                                             state__in=('pending', 'accepted'),
            #                                                             trash=False,
            #                                                             return_to_province=False,
            #                                                             first_car_allocated_quantity=0,
            #                                                             archive_wage=False,
            #                                                             ).exclude(union_share=0, company_share=0,
            #                                                                       guilds_share=0).only(
            #     'total_killed_weight', 'union_share', 'company_share',
            #     'guilds_share', 'total_wage_amount', 'total_killed_quantity')
            # freezing_province_kill_requests = province_kill_requests.filter(
            #     province_request__poultry_request__freezing=True).only('total_killed_weight', 'union_share',
            #                                                            'company_share',
            #                                                            'guilds_share', 'total_wage_amount',
            #                                                            'total_killed_quantity')
            #
            # kill_house_requests = KillHouseRequest.objects.filter(
            #     Q(Q(killer=kill_house) & Q(killhouse_user=kill_house)) | Q(
            #         Q(killer__isnull=True) & Q(killhouse_user=kill_house)) | Q(
            #         Q(killer__isnull=True) | Q(killer=kill_house)),
            #     archive_wage=False,
            #     trash=False
            # ).select_related('province_kill_request').only('accepted_real_weight',
            #                                                'province_kill_request__union_share_percent',
            #                                                'province_kill_request__wage', 'accepted_real_weight',
            #                                                'province_kill_request__guilds_share_percent',
            #                                                'province_kill_request__company_share_percent',
            #                                                'accepted_real_quantity', 'accepted_real_quantity')
            # kill_house_requests = kill_house_requests.filter(Q(killer=kill_house) | Q(killhouse_user=kill_house)).select_related(
            #     'province_kill_request').only(
            #     'accepted_real_weight', 'province_kill_request__union_share_percent',
            #     'province_kill_request__wage', 'accepted_real_weight', 'province_kill_request__guilds_share_percent',
            #     'province_kill_request__company_share_percent', 'accepted_real_quantity')
            #
            # freezing_kill_house_requests = kill_house_requests.filter(
            #     province_kill_request__province_request__poultry_request__freezing=True).select_related(
            #     'province_kill_request').only('accepted_real_weight', 'province_kill_request__union_share_percent',
            #                                   'province_kill_request__wage', 'accepted_real_weight',
            #                                   'province_kill_request__guilds_share_percent',
            #                                   'province_kill_request__company_share_percent', 'accepted_real_quantity')
            #
            # free_bars = KillHouseFreeBarInformation.objects.filter(kill_house=kill_house, archive_wage=False,
            #                                                        trash=False).only('live_weight', 'union_share',
            #                                                                          'weight_of_carcasses',
            #                                                                          'company_share',
            #                                                                          'guilds_share',
            #                                                                          'total_wage_amount')
            # free_bars_live = free_bars.filter(buy_type='live', trash=False).only('live_weight', 'union_share',
            #                                                                      'weight_of_carcasses',
            #                                                                      'company_share',
            #                                                                      'guilds_share',
            #                                                                      'total_wage_amount')
            # free_bars_carcases = free_bars.filter(buy_type='carcass', trash=False).only('live_weight', 'union_share',
            #                                                                             'weight_of_carcasses',
            #                                                                             'company_share',
            #                                                                             'guilds_share',
            #                                                                             'total_wage_amount'
            #                                                                             )
            slaughter_transactions = InternalTransaction.objects.filter(
                Q(kill_house=kill_house) | Q(parent_kill_house=kill_house),
                status='completed',
                trash=False).only('union_share', 'company_share', 'guilds_share', 'amount')

            # province_kill_requests_total_wage = \
            #     province_kill_requests.filter(province_request__poultry_request__freezing=False).aggregate(
            #         total=Sum('total_wage_amount'))[
            #         'total'] or 0
            # if wage_percent > 0:
            #     province_kill_requests_total_wage -= province_kill_requests_total_wage * wage_percent
            # freezing_province_kill_request_total_wage = \
            #     freezing_province_kill_requests.aggregate(total=Sum('total_wage_amount'))['total'] or 0
            #
            # kill_house_reqest_total_wage = \
            #     kill_house_requests.filter(
            #         province_kill_request__province_request__poultry_request__freezing=False).aggregate(
            #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
            #         'total'] or 0
            # if wage_percent > 0:
            #     kill_house_reqest_total_wage -= kill_house_reqest_total_wage * wage_percent
            # freezing_kill_house_reqest_total_wage = \
            #     freezing_kill_house_requests.aggregate(
            #         total=Sum(F('accepted_real_weight') * F('province_kill_request__wage')))[
            #         'total'] or 0
            #
            # free_bars_live_total_wage = free_bars_live.aggregate(total=Sum('total_wage_amount'))[
            #                                 'total'] or 0
            #
            # free_bars_carcases_total_wage = free_bars_carcases.aggregate(total=Sum('total_wage_amount'))[
            #                                     'total'] or 0
            # total_unpaid_wage = free_bars_carcases_total_wage + kill_house_reqest_total_wage + \
            #              freezing_kill_house_reqest_total_wage + province_kill_requests_total_wage + \
            #              freezing_province_kill_request_total_wage + free_bars_live_total_wage

            total_paid_wage = slaughter_transactions.aggregate(total=Sum('amount'))[
                                  'total'] or 0
            total_wage = total_unpaid_wage - (total_paid_wage + kill_house.off)
            if kill_house_purchase.limitation_number <= total_wage:
                unpaid = "{:,}".format(int(total_wage))
                if kill_house.killer == False:
                    killer = 'کشتارگاه'
                else:
                    killer = 'کشتارکن'
                amount = "{:,}".format(int(kill_house_purchase.limitation_number))
                user_token = 'k' + kill_house.kill_house_operator.user.user_gate_way_id
                message = f'کاربر گرامی {killer + "(" + kill_house.name + ")"}' \
                          f'\n' \
                          f'باسلام واحترام ' \
                          f'\n' \
                          f'باتوجه به عدم پرداخت  بدهی تعرفه سامانه به مبلغ{unpaid} امکان ثبت کشتار برای شما وجود ندارد.جهت فعال سازی پنل، بدهی شما باید کمتر از {amount} ریال باشد.' \
                          f'\n' \
                          f'لازم به توضیح است که کشتار خارج از سامانه به عنوان کشتار و عرضه خارج از شبکه محسوب میگردد.' \
                          f'\n' \
                          f'لینک مشاهده و پرداخت بدهی:' \
                          f'\n' \
                          f'https://rasadyar.net/pay/{base_pos_id}/{user_token} \n' \
                          f'\n' \
                          f'(سامانه رصدیار)'
                check_mobile = check_mobile_number(kill_house.kill_house_operator.user.mobile)
                if check_mobile:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={kill_house.kill_house_operator.user.mobile}&message={message}")
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={COMPANY_NUMBER}&message={message}")
                if UNION_SECOND_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_SECOND_NUMBER}&message={message}")
                if UNION_THIRD_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_THIRD_NUMBER}&message={message}")
                if UNION_FIFTH_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_FIFTH_NUMBER}&message={message}")
                if UNION_SIXTH_NUMBER is not None:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={send_deactivate_username}&password={send_deactivate_password}&from=30002501&to={UNION_SIXTH_NUMBER}&message={message}")
    return HttpResponse('ok')


# USERNAME_SMS_FINANCIAL
def province_out_request_transaction_sms(province, buyer, poultry_name, quantity, index_weight, wage, mobile,
                                         order_code, date, amount, sale_type):
    date1 = datetime.strptime(str(date),
                              '%Y-%m-%d').date()
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    date = separate.join(reversed_date)
    all_wage = "{:,}".format(int(wage))
    amount = "{:,}".format(int(amount))
    sale_type_free = 'آزاد' if sale_type == False else 'دولتی'
    message = f'سفارش فروش مرغ زنده استان {province}' \
              '\n' \
              f'تاریخ: {date}' \
              f'\n' \
              f'خریدار: {buyer}' \
              '\n' \
              f'مرغدار: {poultry_name}' \
              '\n' \
              f'نوع فروش:{sale_type_free}' \
              '\n' \
              f'تعداد: {quantity}' \
              '\n' \
              f'وزن تقریبی سفارش: {index_weight}' \
              f'\n' \
              f'وزن تقریبی کل سفارش: {int(index_weight * quantity)}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'مبلغ کل تعرفه:{all_wage} ریال ' \
              f'\n' \
              f'لینک مشاهده و پرداخت تعرفه:' \
              f'\n' \
              f'https://rasadyar.net/pay/{base_pos_id}/{order_code}' \
              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={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={mobile}&message={message}")
    req = send_sms_request(
        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={COMPANY_NUMBER}&message={message}")


# def daily_report_excel_and_pdf_send_from_sms():
#     message = f'سفارش فروش مرغ زنده استان {province}' \
#               '\n' \
#               f'تاریخ: {date}' \
#               f'\n' \
#               f'خریدار: {buyer}' \
#               '\n' \
#               f'مرغدار: {poultry_name}' \
#               '\n' \
#               f'تعداد: {quantity}' \
#               '\n' \
#               f'وزن تقریبی سفارش: {index_weight}' \
#               f'\n' \
#               f'مبلغ کل تعرفه:{all_wage} ریال ' \
#               f'\n' \
#               f'لینک مشاهده و پرداخت تعرفه:' \
#               f'\n' \
#               f'https://{base_url_sms}.rasadyar.net/pay/{order_code}' \
#               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={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={mobile}&message={message}")

# USERNAME_SMS_FINANCIAL

def send_sms_for_final_approval_out_province_threading(buyer_list, poultry_request_list):
    # users = SystemUserProfile.objects.filter(id__in=poultry_list).select_related('province').only('mobile', 'user_gate_way_id','province__name','fullname')
    if base_url_sms == 'ha':
        province_name = 'همدان'
    elif base_url_sms == 'ku':
        province_name = 'کردستان'
    elif base_url_sms == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'
    base_url = f'rasadyar.net/pay/{base_pos_id}'
    if poultry_request_list is not None:
        poultry_requests = PoultryRequest.objects.filter(trash=False, id__in=poultry_request_list)
        for poultry_request in poultry_requests:
            if poultry_request.interface_number is not None:
                mobile = poultry_request.interface_number
            else:
                mobile = poultry_request.poultry.user.mobile
            token_user = 'p' + poultry_request.poultry.user.user_gate_way_id

            message = f' مرغدار محترم {poultry_request.poultry.user.fullname} ' \
                      f'\n' \
                      f'سفارش خرید مرغ زنده(فروش خارج از استان) با کد سفارش {poultry_request.order_code} برای شما در سامانه رصدیار استان  {province_name} ثبت گردید جهت پرداخت تعرفه از طریق لینک زیر اقدام نمایید.' \
                      f'\n' \
                      f'**لازم به ذکر است: در صورت عدم پرداخت تعرفه تا پایان وقت  امروز(16 بعد از ظهر) سفارشات شما لغو میگردد!' \
                      f'\n' \
                      f'لینک مشاهده و پرداخت تعرفه :' \
                      f'\n' \
                      f'https://{base_url}/{token_user}{poultry_request.order_code}' \
                      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={poultry_link_out_sale_username}&password={poultry_link_out_sale_password}&from=30002501&to={mobile}&message={message}")

    users = SystemUserProfile.objects.filter(id__in=buyer_list).select_related('province').only('mobile',
                                                                                                'user_gate_way_id',
                                                                                                'province__name',
                                                                                                'fullname')
    for user in users:
        mobile = user.mobile
        token_user = 'b' + user.user_gate_way_id

        message = f'  خریدار محترم {user.fullname} ' \
                  f'\n' \
                  f'سفارش خرید مرغ زنده(فروش خارج از استان) برای شما در سامانه رصدیار استان  {province_name} ثبت گردید جهت پرداخت تعرفه از طریق لینک زیر اقدام نمایید.' \
                  f'\n' \
                  f'**لازم به ذکر است: در صورت عدم پرداخت تعرفه تا پایان وقت  امروز(16 بعد از ظهر) سفارشات شما لغو میگردد!' \
                  f'\n' \
                  f'لینک مشاهده و پرداخت تعرفه :' \
                  f'\n' \
                  f'https://{base_url}/{token_user}' \
                  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={poultry_link_out_sale_username}&password={poultry_link_out_sale_password}&from=30002501&to={mobile}&message={message}")


def send_sms_for_final_approval_out_province_buyer_threading(buyer_list):
    users = SystemUserProfile.objects.filter(id__in=buyer_list).select_related('province').only('mobile',
                                                                                                'user_gate_way_id',
                                                                                                'province__name',
                                                                                                'fullname')
    for user in users:
        mobile = user.mobile
        token_user = 'b' + user.user_gate_way_id
        message = f'  خریدار محترم {user.fullname} ' \
                  f'\n' \
                  f'سفارش خرید مرغ زنده برای شما در سامانه رصدیار استان {user.province.name} ثبت گردید جهت پرداخت تعرفه از طریق لینک زیر اقدام نمایید.' \
                  f'\n' \
                  f'لازم به ذکر است در صورت عدم پرداخت تعرفه تا پایان وقت  امروز(۱۲ شب) سفارشات شما لغو میگردد!' \
                  f'\n' \
                  f'لینک مشاهده و پرداخت تعرفه :' \
                  f'\n' \
                  f'https://rasadyar.net/pay/{base_pos_id}/{token_user}' \
                  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={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={mobile}&message={message}")
            print({"status": req.status_code, "mobile": user.mobile})


def sms_allocation_for_vet_farm(poultry_name, poultry_mobile, quantity, Index_weight, kill_house_name, kill_house_mobile
                                , city, send_date, mobile):
    quantity_1 = "{:,}".format(int(quantity))
    message = f'تخصیص مرغ زنده (کشتار داخل استان)' \
              f'\n' \
              f'مرغدار:{poultry_name}' \
              f'\n' \
              f'تلفن:{poultry_mobile}' \
              f'\n' \
              f'تعداد:{quantity_1}' \
              f'\n' \
              f'میانگین وزن: {Index_weight}' \
              f'\n' \
              f'خریدار:{kill_house_name}' \
              f'\n' \
              f'تلفن:{kill_house_mobile}' \
              f'\n' \
              f'ادرس:{city}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'توضیحات: قبل از صدور مجوز حمل با مرغدار هماهنگی های لازم انجام دهید و کد قرنطینه در سامانه رصدیار ثبت گردد.(اتحادیه مرغداران گوشتی استان همدان)' \
              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={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")


def sms_chain_company_for_ver_farm(poultry_name, poultry_mobile, quantity, Index_weight, kill_house_name,
                                   kill_house_mobile
                                   , city, send_date, mobile, province):
    quantity_1 = "{:,}".format(int(quantity))
    message = f'تخصیص مرغ زنده (کشتار زنجیره ها)' \
              f'\n' \
              f'مرغدار:{poultry_name}' \
              f'\n' \
              f'تلفن:{poultry_mobile}' \
              f'\n' \
              f'تعداد:{quantity_1}' \
              f'\n' \
              f'میانگین وزن: {Index_weight}' \
              f'\n' \
              f'خریدار:{kill_house_name}' \
              f'\n' \
              f'تلفن:{kill_house_mobile}' \
              f'\n' \
              f'ادرس:{city}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'اتحادیه مرغداران گوشتی استان {province}' \
              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={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={mobile}&message={message}")


def sms_ticket(province, fullname):
    message = f'یک تیکت جدید از استان {province} دارید .' \
              '\n' \
              f'کاربر: {fullname}'
    req = send_sms_request(
        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={SUPPORTER_NUMBER}&message={message}")


def document_discrepancy_sms(killer, name, bar_code, doc, mobile, date):
    killer_user = 'کشتارکن' if killer == True else 'کشتارگاه'
    date1 = datetime.strptime(str(date),
                              '%Y-%m-%d').date()
    from_date = jdatetime.date.fromgregorian(
        year=date1.year,
        month=date1.month,
        day=date1.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    date = separate.join(reversed_date)
    message = f' کاربر گرامی {killer_user} {name}' \
              '\n' \
              f'بار به شماره {bar_code} در تاریخ({date}) به علت وضعیت ({doc}) نیازمند ویرایش میباشد.' \
              f'\n' \
              f'جهت ویرایش اطلاعات به پنل کاربری خود مراجعه فرمایید.' \
              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={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
    req = send_sms_request(
        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={COMPANY_NUMBER}&message={message}")


def confirmation_of_the_need_for_slaughterhouse_sms_threading(name):
    city_operator = CityOperator.objects.filter(trash=False).select_related('user').only('user__mobile')
    mobiles = city_operator.values_list('user__mobile', flat=True).distinct()
    message = f' کاربر گرامی {name}' \
              '\n' \
              'باسلام' \
              '\n' \
              'صرفا جهت اطلاع' \
              '\n' \
              f'درخواست نیاز شما مورد تایید قرار گرفت و امکان ثبت درخواست کشتار را دارید.' \
              f'\n' \
              f'(سامانه رصدیار)'
    for mobile in mobiles:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            req = send_sms_request(
                f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")


# USERNAME_SMS
def province_kill_request_accept_sms(kill_house_name
                                     ):
    city_operator = CityOperator.objects.filter(trash=False).select_related('user').only('user__mobile')
    mobiles = city_operator.values_list('user__mobile', flat=True).distinct()
    message = f' کاربر گرامی {kill_house_name}' \
              '\n' \
              'باسلام' \
              '\n' \
              'صرفا جهت اطلاع' \
              '\n' \
              f'درخواست نیاز شما مورد تایید قرار گرفت و امکان ثبت درخواست کشتار را دارید.' \
              f'\n' \
              f'(سامانه رصدیار)'
    for mobile in mobiles:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            req = send_sms_request(
                f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")


def reporting_sms():
    now = datetime.now().date()
    from_date = jdatetime.date.fromgregorian(
        year=now.year,
        month=now.month,
        day=now.day
    ).strftime('%Y-%m-%d')
    reversed_date = reversed(from_date.split("-"))
    separate = "-"
    date = separate.join(reversed_date)
    reporst = ReportsUsers.objects.filter(active=True)
    for r in reporst:
        user_reporst = UserReports.objects.filter(active=True, user=r).order_by('id')

        message = f'کاربرگرامی {r.fullname}' \
                  '\n' \
                  'با سلام' \
                  '\n' \
                  f'احتراماً لیست گزارشات کشتار و توزیع مرغ گوشتی استان مورخ {date}  جهت اطلاع بحضورتان ارسال میگردد.' \
                  '\n'
        l = 1
        if user_reporst:
            for user in user_reporst:
                message = message + '\n' \
                                    f'{l}_{user.report.title}' \
                                    '\n' \
                                    f'https://{base_url_for_sms_report}backend.rasadyaar.ir/{user.report.end_point}/?key={r.user_token}' \
                                    '\n'
                l += 1
            else:
                message = message + '\n' \
                                    '(سامانه رصدیار)'
                check_mobile = check_mobile_number(r.mobile)
                if check_mobile:
                    req = send_sms_request(
                        f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={r.mobile}&message={message}")


def car_allocation_vet_farm_sms(date, poultry, age, quantity, car, code, pelak, kill_house, mobile, amount,
                                free_sale_in_province):
    date1 = datetime.strptime(str(date),
                              '%Y-%m-%d').date()
    date = shamsi_date(date1)
    quantity = "{:,}".format(int(quantity))
    amount = "{:,}".format(int(amount))
    sale_type = 'آزاد' if free_sale_in_province == False else 'دولتی'
    message = f'اطلاعات بار' \
              f'\n' \
              f'تاریخ کشتار: {date}' \
              f'\n' \
              f'نوع کشتار:{sale_type}' \
              f'\n' \
              f'مرغدار: {poultry}' \
              f'\n' \
              f'سن: {age}' \
              f'\n' \
              f'قطعه: {quantity}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'ماشین: {car}' \
              f'\n' \
              f'کد حمل: {code}' \
              f'\n' \
              f'پلاک: {pelak}' \
              f'\n' \
              f'کشتارگاه: {kill_house}' \
              '\n' \
              '(سامانه رصدیار)'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")


def delete_car_allocation_vet_farm_sms(date, poultry, age, quantity, car, code, pelak, kill_house, mobile, amount,
                                       free_sale_in_province):
    date1 = datetime.strptime(str(date),
                              '%Y-%m-%d').date()
    date = shamsi_date(date1)
    quantity = "{:,}".format(int(quantity))
    amount = "{:,}".format(int(amount))
    sale_type = 'آزاد' if free_sale_in_province == False else 'دولتی'
    message = f'اطلاعات بار حذف شده' \
              f'\n' \
              f'تاریخ کشتار: {date}' \
              f'\n' \
              f'نوع کشتار:{sale_type}' \
              f'\n' \
              f'مرغدار: {poultry}' \
              f'\n' \
              f'سن: {age}' \
              f'\n' \
              f'قطعه: {quantity}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'ماشین: {car}' \
              f'\n' \
              f'کد حمل: {code}' \
              f'\n' \
              f'پلاک: {pelak}' \
              f'\n' \
              f'کشتارگاه: {kill_house}' \
              '\n' \
              '(سامانه رصدیار)'
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")


def cron_for_update_sms():
    update_date = LastUpdate.objects.first().update_date.date()
    num_list = [SUPPORTER_NUMBER, COMPANY_NUMBER, '09201917727']
    if base_url_for_sms_report == 'ha':
        base = 'همدان'
    elif base_url_for_sms_report == 'ma':
        base = 'مرکزی'
    else:
        base = 'بوشهر'
    if not update_date == datetime.now().date():
        message = f'جوجه ریزی آپدیت نشده است. استان {base}'
        for num in num_list:
            send_sms_request(
                f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS_FINANCIAL}"
                f"&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={num}&message={message}")


def ticket_answered(mobile):
    message = 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={mobile}&message={message}")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def send_again_sms_for_final_approval_out_province(request):
    key = request.GET['key']
    poultry_request = PoultryRequest.objects.get(trash=False, key=key)
    if base_url_sms == 'ha':
        province_name = 'همدان'
    elif base_url_sms == 'ku':
        province_name = 'کردستان'
    elif base_url_sms == 'ma':
        province_name = 'مرکزی'
    else:

        province_name = 'تست'
    base_url = f'rasadyar.net/pay/{base_pos_id}'
    if poultry_request.payer_type == 'poultry':
        if poultry_request.interface_number is not None:
            mobile = poultry_request.interface_number
        else:
            mobile = poultry_request.poultry.user.mobile
        token_user = 'p' + poultry_request.poultry.user.user_gate_way_id

        message = f' مرغدار محترم {poultry_request.poultry.user.fullname} ' \
                  f'\n' \
                  f'سفارش خرید مرغ زنده(فروش خارج از استان) با کد سفارش {poultry_request.order_code} برای شما در سامانه رصدیار استان  {province_name} ثبت گردید جهت پرداخت تعرفه از طریق لینک زیر اقدام نمایید.' \
                  f'\n' \
                  f'**لازم به ذکر است: در صورت عدم پرداخت تعرفه تا پایان وقت  امروز(16 بعد از ظهر) سفارشات شما لغو میگردد!' \
                  f'\n' \
                  f'لینک مشاهده و پرداخت تعرفه :' \
                  f'\n' \
                  f'https://{base_url}/{token_user}{poultry_request.order_code}' \
                  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={poultry_link_out_sale_username}&password={poultry_link_out_sale_password}&from=30002501&to={mobile}&message={message}")
    else:
        mobile = poultry_request.buyer_mobile
        user = SystemUserProfile.objects.filter(mobile=mobile).first()
        token_user = 'b' + user.user_gate_way_id

        message = f'  خریدار محترم {user.fullname} ' \
                  f'\n' \
                  f'سفارش خرید مرغ زنده(فروش خارج از استان) برای شما در سامانه رصدیار استان  {province_name} ثبت گردید جهت پرداخت تعرفه از طریق لینک زیر اقدام نمایید.' \
                  f'\n' \
                  f'**لازم به ذکر است: در صورت عدم پرداخت تعرفه تا پایان وقت  امروز(16 بعد از ظهر) سفارشات شما لغو میگردد!' \
                  f'\n' \
                  f'لینک مشاهده و پرداخت تعرفه :' \
                  f'\n' \
                  f'https://{base_url}/{token_user}' \
                  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={poultry_link_out_sale_username}&password={poultry_link_out_sale_password}&from=30002501&to={mobile}&message={message}")
    return HttpResponse('ok', status=status.HTTP_200_OK)


def vet_farm_out_poultry_request_sms(mobile, poultry_fullname, quantity, chicken_breed,
                                     order_code, send_date, sale_in_province, amount):
    sale_type = 'آزاد' if sale_in_province == True else 'دولتی'
    amount = "{:,}".format(int(amount))
    quantity = "{:,}".format(int(quantity))
    message = 'درخواست فروش به خارج از استان' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'نژاد:{chicken_breed}' \
              f'\n' \
              f'تاریخ کشتار:{send_date}' \
              f'\n' \
              f'نوع فروش:{sale_type}' \
              f'\n' \
              f'مرغدار:{poultry_fullname}' \
              f'\n' \
              f'کدسفارش:{order_code}' \
              f'\n' \
              f'قیمت مرغدار:{amount}' \
              f'\n' \
              f'(سامانه رصدیار)'

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)


def send_sms_for_kill_house_not_add_to_inventory(mobile, quantity):
    quantity = "{:,}".format(int(quantity))
    message = 'درخواست فروش به خارج از استان' \
              f'\n' \
              f'تعداد:{quantity}' \
              f'\n' \
              f'\n' \
              f'(سامانه رصدیار)'

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
            USERNAME_SMS, PASSWORD_SMS,
            mobile, message)


def send_sms_for_bar_difference_request(mobile, quantity, poultry):
    message = 'با سلام و احترام' \
              '\n' \
              f'کاربر گرامی برای شما  حجم {quantity} قطعه اختلاف کشتار از مرغدار {poultry} ثبت گردیده لطفا جهت تعیین تکلیف به بخش مدیریت بار قسمت اختلاف کشتار مراجعه نمایید.باتشکر سامانه رصدیار '
    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        req = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS_FINANCIAL}&password={PASSWORD_SMS_FINANCIAL}&from=30002501&to={mobile}&message={message}")


class ManagementSendSmsViewSet(viewsets.ModelViewSet):
    queryset = ManagementSendSms.objects.all().order_by('id')
    serializer_class = ManagementSendSmsSerializer
    permission_classes = [TokenHasReadWriteScope]


def send_sms_fro_kill_request_market(kill_req):
    poultry_name = kill_req.poultry.unit_name
    mobile = kill_req.poultry.user.mobile
    kill_house_name = kill_req.kill_house.name
    kill_house_mobile = kill_req.kill_house.kill_house_operator.user.mobile
    message = f' مرغدار محترم {poultry_name} ' \
              f'\n' \
              f'سفارش مرغ زنده در پنل بورسی برای شما ثبت شد:' \
              f'\n' \
              f'خریدار:{kill_house_name}({kill_house_mobile})' \
              f'\n' \
              f'حجم:{to_locale_str(kill_req.kill_capacity)}(قطعه)' \
              f'\n' \
              f'وزن:{to_locale_str(int(kill_req.kill_capacity * kill_req.Index_weight))}(کیلوگرم)' \
              f'\n' \
              f'مبلغ هر کیلو:{to_locale_str(kill_req.amount)}(ریال)' \
              f'\n' \
              f'حداکثر مهلت تسویه:{shamsi_date(kill_req.payment_deadline_date)}' \
              f'\n' \
              f'کد احراز:{kill_req.market_code}' \
              f'\n' \
              f'مهلت وارد کردن کد احراز 30 دقیقه میباشد و پس از آن درخواست لغو خواهد شد و گزارش برای دستگاه نظارتی ارسال میگردد.' \
              f'\n' \
              'سامانه رصدیار'

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={kill_req_market_username}"
            f"&password={kill_req_market_password}&from=30002501&to={mobile}&message={message}")


def send_sms_for_poultry_market(poultry_req):
    poultry_name = poultry_req.poultry.unit_name
    mobile = poultry_req.poultry.user.mobile
    quantity = to_locale_str(poultry_req.quantity)
    amount = to_locale_str(poultry_req.amount)
    send_date = shamsi_date(poultry_req.send_date)
    message = 'مرغدار محترم {0}' \
              '\n' \
              'تعداد {1} قطعه مرغ گوشتی سهمیه کشتار در تاریخ {3} با قیمت مصوب {2} (ریال) برای شما در پنل بورسی سامانه رصدیار ثبت شده است.' \
              '\n' \
              'درصورت عدم موجوی و یا عدم امکان تحویل تعداد مذکور با تعاونی شهرستان خود یا کاربر سامانه در اتحادیه استان تماس حاصل فرمایید.' \
              '\n' \
              'سامانه رصدیار'.format(poultry_name, quantity, amount, send_date)

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={poultry_req_market_username}"
            f"&password={poultry_req_market_password}&from=30002501&to={mobile}&message={message}")


def send_sms_for_guild(guilds):
    mobile = guilds.user.mobile
    type_role = 'مباشر' if guilds.steward == True else 'صنف'
    message = 'کاربر گرامی\n' \
              'برای شما کاربری {5} توسط {6}({7}) در سامانه رصدیار ثبت شده است.\n' \
              'نام و نام خانوادگی: {0}\n' \
              'نام واحد صنفی: {1}\n' \
              'شهر: {2}\n' \
              'آدرس: {3}\n' \
              'درصورتی که اطلاعات مورد تایید شما میباشد کد احراز را به ثبت کننده تحویل دهید.\n' \
              'کد احراز: {4}\n' \
              'سامانه رصدیار'.format(guilds.user.fullname, guilds.guilds_name, guilds.address.city.name,
                                     guilds.address.address, guilds.register_code, type_role,
                                     guilds.registerar_fullname,
                                     guilds.registerar_mobile)

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={guild_register_username}"
            f"&password={guild_register_password}&from=30002501&to={mobile}&message={message}")


def send_sms_for_guild_for_register(guilds):
    mobile = guilds.user.mobile
    type_role = 'مباشر' if guilds.steward == True else 'صنف'
    message = 'کاربر گرامی\n' \
              'برای شما کاربری {5} در سامانه رصدیار ثبت شده است.\n' \
              'نام و نام خانوادگی: {0}\n' \
              'نام واحد صنفی: {1}\n' \
              'شهر: {2}\n' \
              'آدرس: {3}\n' \
              'درصورتی که اطلاعات مورد تایید شما میباشد برای احراز شما در سامانه لطفا کد رو تحویل ثبت کننده دهید.\n' \
              'کد احراز: {4}\n' \
              'سامانه رصدیار'.format(guilds.user.fullname, guilds.guilds_name, guilds.address.city.name,
                                     guilds.address.address, guilds.register_code, type_role,
                                     guilds.registerar_fullname if guilds.registerar_fullname else '-',
                                     guilds.registerar_mobile if guilds.registerar_mobile else '-')

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={guild_register_username}"
            f"&password={guild_register_password}&from=30002501&to={mobile}&message={message}")


def send_sms_for_sale_bar(bar):
    mobile = bar.buyer_mobile
    date = shamsi_date(bar.date)
    seller = bar.kill_house.name
    weight = bar.weight_of_carcasses
    number = bar.registration_code
    buyer = bar.buyer_name
    quanarntine_code = bar.clearance_code
    provicne = bar.province
    city = bar.city

    message = 'اطلاعات توزیع لاشه به خارج استان\n' \
              'فروشنده: {0} \n' \
              'تاریخ فروش: {1}\n' \
              'خریدار: {2}\n' \
              'استان: {6}\n' \
              'شهر: {7}\n' \
              'وزن لاشه: {3} (کیلوگرم)\n' \
              'کد قرنطینه: {4} \n' \
              'کد احراز: {5}\n' \
              'سامانه رصدیار'.format(seller, date, buyer, to_locale_str(weight), quanarntine_code, number, provicne,
                                     city)

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={steward_allocation_username}"
            f"&password={steward_allocation_password}&from=30002501&to={mobile}&message={message}")


def send_sms_for_sale_bar_for_steward(bar):
    mobile = bar.buyer_mobile
    date = shamsi_date(bar.date)
    seller = bar.steward.guilds_name
    weight = bar.weight_of_carcasses
    number = bar.registration_code
    buyer = bar.buyer_name
    quanarntine_code = bar.clearance_code
    provicne = bar.province
    city = bar.city

    message = 'اطلاعات توزیع لاشه به خارج استان\n' \
              'فروشنده: {0} \n' \
              'تاریخ فروش: {1}\n' \
              'خریدار: {2}\n' \
              'استان: {6}\n' \
              'شهر: {7}\n' \
              'وزن لاشه: {3} (کیلوگرم)\n' \
              'کد قرنطینه: {4} \n' \
              'کد احراز: {5}\n' \
              'سامانه رصدیار'.format(seller, date, buyer, to_locale_str(weight), quanarntine_code, number, provicne,
                                     city)

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        u = send_sms_request(
            f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={steward_allocation_username}"
            f"&password={steward_allocation_password}&from=30002501&to={mobile}&message={message}")


def send_daily_slaughter_statistics_sms():
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]

    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)

    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ku':
        province_name = 'کردستان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'

    province_kill_requests = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).aggregate(
        total_orders=Sum('id'),
        total_quantity=Sum('total_killed_quantity'),
        total_live_weight=Sum('total_killed_weight'),
    )

    orders_count = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).count()

    total_quantity = province_kill_requests['total_quantity'] or 0
    total_live_weight = province_kill_requests['total_live_weight'] or 0
    total_carcass_weight = int(total_live_weight * 0.75)
    average_weight = round(total_live_weight / total_quantity, 1) if total_quantity > 0 else 0

    kill_house_requests = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).aggregate(
        total_quantity=Sum('accepted_real_quantity'),
        total_weight=Sum('accepted_real_weight')
    )

    loads_count = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).count()

    loads_quantity = kill_house_requests['total_quantity'] or 0
    loads_weight = kill_house_requests['total_weight'] or 0

    formatted_quantity = to_locale_str(int(total_quantity))
    formatted_live_weight = to_locale_str(int(total_live_weight))
    formatted_carcass_weight = to_locale_str(int(total_carcass_weight))
    formatted_loads_quantity = to_locale_str(int(loads_quantity))
    formatted_loads_weight = to_locale_str(int(loads_weight))

    message = f'اطلاعات کشتار مرغ گوشتی مورخ {date_shamsi} استان {province_name}\n' \
              f'تعداد سفارشات: {orders_count}\n' \
              f'حجم سفارش کشتار: {formatted_quantity} قطعه\n' \
              f'وزن تقریبی زنده: {formatted_live_weight} کیلوگرم\n' \
              f'وزن تقریبی لاشه: {formatted_carcass_weight} کیلوگرم\n' \
              f'میانگین وزن زنده: {average_weight} کیلوگرم\n' \
              f'اطلاعات بارایجاد شده:\n' \
              f'تعداد بار: {loads_count}\n' \
              f'حجم بارها: {formatted_loads_quantity} قطعه\n' \
              f'وزن بارها(زنده): {formatted_loads_weight} کیلوگرم\n' \
              f'سامانه رصدیار'

    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={sms_recipient_username}"
                    f"&password={sms_recipient_password}&from=30002501&to={mobile}&message={message}")
            except Exception as e:
                print(f"Error sending SMS to {mobile}: {str(e)}")


def send_daily_distribution_report_sms():
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]

    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)

    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ku':
        province_name = 'کردستان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'

    kill_houses = KillHouse.objects.filter(out_province=False, active=True, trash=False).order_by('name')

    distribution_data = []
    total_distribution_weight = 0

    for kill_house in kill_houses:
        kill_house_allocations = StewardAllocation.objects.filter(
            kill_house=kill_house,
            trash=False,
            receiver_state__in=('pending', 'accepted'),
            to_cold_house__isnull=True,
            date__date=target_date,
            warehouse=True
        ).aggregate(
            total_weight=Sum('real_weight_of_carcasses')
        )

        allocation_weight = kill_house_allocations['total_weight']

        if allocation_weight and allocation_weight > 0:
            distribution_data.append({
                'name': kill_house.name,
                'weight': allocation_weight
            })
            total_distribution_weight += allocation_weight

    if not distribution_data:
        return HttpResponse('هیچ توزیعی برای امروز ثبت نشده است', status=status.HTTP_200_OK)

    message_lines = [f'گزارش توزیع گوشت مرغ داخل استان']
    message_lines.append(f'مورخ {date_shamsi} استان {province_name}')

    for item in distribution_data:
        formatted_weight = to_locale_str(int(item['weight']))
        message_lines.append("kg {1}: {0}".format(item['name'], formatted_weight))

    message_lines.append('-------------------------')
    formatted_total = to_locale_str(int(total_distribution_weight))
    message_lines.append(' مجموع کل توزیع: {} kg'.format(formatted_total))
    message_lines.append('سامانه رصدیار')

    message = '\n'.join(message_lines)

    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={sms_recipient_username}"
                    f"&password={sms_recipient_password}&from=30002501&to={mobile}&message={message}")
            except Exception as e:
                print(f"Error sending SMS to {mobile}: {str(e)}")


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def send_daily_distribution_report_sms_manual(request):
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]

    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)

    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ku':
        province_name = 'کردستان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'

    kill_houses = KillHouse.objects.filter(out_province=False, active=True, trash=False).order_by('name')

    distribution_data = []
    total_distribution_weight = 0

    for kill_house in kill_houses:
        kill_house_allocations = StewardAllocation.objects.filter(
            kill_house=kill_house,
            trash=False,
            receiver_state__in=('pending', 'accepted'),
            to_cold_house__isnull=True,
            date__date=target_date,
            warehouse=True
        ).aggregate(
            total_weight=Sum('real_weight_of_carcasses')
        )

        allocation_weight = kill_house_allocations['total_weight']

        if allocation_weight and allocation_weight > 0:
            distribution_data.append({
                'name': kill_house.name,
                'weight': allocation_weight
            })
            total_distribution_weight += allocation_weight

    if not distribution_data:
        return HttpResponse('هیچ توزیعی برای امروز ثبت نشده است', status=status.HTTP_200_OK)

    message_lines = [f'گزارش توزیع گوشت مرغ داخل استان']
    message_lines.append(f'مورخ {date_shamsi} استان {province_name}')

    for item in distribution_data:
        formatted_weight = to_locale_str(int(item['weight']))
        message_lines.append("kg {1}: {0}".format(item['name'], formatted_weight))

    message_lines.append('-------------------------')
    formatted_total = to_locale_str(int(total_distribution_weight))
    message_lines.append(' مجموع کل توزیع: {} kg'.format(formatted_total))
    message_lines.append('سامانه رصدیار')

    message = '\n'.join(message_lines)

    success_count = 0
    failed_numbers = []

    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={sms_recipient_username}"
                    f"&password={sms_recipient_password}&from=30002501&to={mobile}&message={message}")
                success_count += 1
            except Exception as e:
                failed_numbers.append(mobile)
                print(f"Error sending SMS to {mobile}: {str(e)}")
        else:
            failed_numbers.append(mobile)

    return HttpResponse(
        f'گزارش توزیع با موفقیت برای {success_count} شماره ارسال شد. تعداد کشتارگاه: {len(distribution_data)}. شماره های ناموفق: {failed_numbers if failed_numbers else "ندارد"}',
        status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def send_daily_slaughter_statistics_sms_manual(request):
    mobile_objects = SmsRecipient.objects.filter(is_active=True)
    mobile_numbers = [obj.phone_number for obj in mobile_objects]
    # mobile_numbers = [
    #     '09188176737',
    #     '09011110919',
    #     '09181112717',
    #     '09185914818',
    #     '09187040838',
    #     '09393946626',
    #     '09127687317',
    #     '09033073493',
    # ]

    target_date = datetime.now().date()
    date_shamsi = shamsi_date(target_date)

    if base_url_for_sms_report == 'ha':
        province_name = 'همدان'
    elif base_url_for_sms_report == 'ku':
        province_name = 'کردستان'
    elif base_url_for_sms_report == 'ma':
        province_name = 'مرکزی'
    else:
        province_name = 'تست'

    province_kill_requests = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).aggregate(
        total_orders=Sum('id'),
        total_quantity=Sum('total_killed_quantity'),
        total_live_weight=Sum('total_killed_weight'),
    )

    orders_count = ProvinceKillRequest.objects.filter(
        trash=False,
        return_to_province=False,
        archive_wage=False,
        state__in=('pending', 'accepted'),
        kill_request__recive_date__date=target_date
    ).count()

    total_quantity = province_kill_requests['total_quantity'] or 0
    total_live_weight = province_kill_requests['total_live_weight'] or 0
    total_carcass_weight = int(total_live_weight * 0.75)
    average_weight = round(total_live_weight / total_quantity, 1) if total_quantity > 0 else 0

    kill_house_requests = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).aggregate(
        total_quantity=Sum('accepted_real_quantity'),
        total_weight=Sum('accepted_real_weight')
    )

    loads_count = KillHouseRequest.objects.filter(
        kill_request__recive_date__date=target_date,
        trash=False
    ).count()

    loads_quantity = kill_house_requests['total_quantity'] or 0
    loads_weight = kill_house_requests['total_weight'] or 0

    formatted_quantity = to_locale_str(int(total_quantity))
    formatted_live_weight = to_locale_str(int(total_live_weight))
    formatted_carcass_weight = to_locale_str(int(total_carcass_weight))
    formatted_loads_quantity = to_locale_str(int(loads_quantity))
    formatted_loads_weight = to_locale_str(int(loads_weight))

    message = f'اطلاعات کشتار مرغ گوشتی مورخ {date_shamsi} استان {province_name}\n' \
              f'تعداد سفارشات: {orders_count}\n' \
              f'حجم سفارش کشتار: {formatted_quantity} قطعه\n' \
              f'وزن تقریبی زنده: {formatted_live_weight} کیلوگرم\n' \
              f'وزن تقریبی لاشه: {formatted_carcass_weight} کیلوگرم\n' \
              f'میانگین وزن زنده: {average_weight} کیلوگرم\n' \
              f'اطلاعات بارایجاد شده:\n' \
              f'تعداد بار: {loads_count}\n' \
              f'حجم بارها: {formatted_loads_quantity} قطعه\n' \
              f'وزن بارها(زنده): {formatted_loads_weight} کیلوگرم\n' \
              f'سامانه رصدیار'

    success_count = 0
    failed_numbers = []

    for mobile in mobile_numbers:
        check_mobile = check_mobile_number(mobile)
        if check_mobile:
            try:
                req = send_sms_request(
                    f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={sms_recipient_username}"
                    f"&password={sms_recipient_password}&from=30002501&to={mobile}&message={message}")
                success_count += 1
            except Exception as e:
                failed_numbers.append(mobile)
                print(f"Error sending SMS to {mobile}: {str(e)}")
        else:
            failed_numbers.append(mobile)

    return HttpResponse(
        f'پیامک با موفقیت برای {success_count} شماره ارسال شد. شماره های ناموفق: {failed_numbers if failed_numbers else "ندارد"}',
        status=status.HTTP_200_OK)


def test_sms_simple():
    """
    تابع ساده برای تست ارسال پیامک
    """
    mobile = '09165597588'
    message = 'تست ارسال پیامک از سامانه رصدیار'

    check_mobile = check_mobile_number(mobile)
    if check_mobile:
        try:
            req = send_sms_request(
                f"http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={USERNAME_SMS}&password={PASSWORD_SMS}&from=30002501&to={mobile}&message={message}")
            print(f"SMS sent successfully. Status: {req.status_code}")
            return f"پیامک با موفقیت ارسال شد. Status: {req.status_code}"
        except Exception as e:
            print(f"Error sending SMS: {str(e)}")
            return f"خطا در ارسال پیامک: {str(e)}"
    else:
        return "شماره موبایل معتبر نیست"


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def test_sms_endpoint(request):
    print('so')
    """
    Endpoint برای تست ارسال پیامک
    """
    result = test_sms_simple()
    return HttpResponse(result, status=status.HTTP_200_OK)