import datetime
import json
from django.db import transaction
import random
import requests
import environ
from rest_framework.views import APIView
from rest_framework.response import Response
import threading
from django.db.models import Sum
from urllib.parse import urlencode


from distributors.models import (
    Commission,
    SuperDistributors,
    WalletTransaction,
    DistributorWallet,
)
from helper import getCumulativeAmount
from retailers.models import Recharge, RechargeErrors, Retailer, Transaction, Wallet
from settings.models import ManualRecharge, Operator, MRobotics, State, TransferRecharge
from api.recharge.serializers import RechargeSerializer
from django.db.models import Q
from django.db import transaction

env = environ.Env()


def distributeCommission(cmsn, amt):
    amt = float(amt)
    distributor = cmsn.distributor

    if distributor:
        operator = cmsn.operator
        # percentage = float(cmsn.receive_commission) - float(cmsn.forward_commission)
        percentage = float(cmsn.receive_commission)

        Sdist = SuperDistributors.objects.get(id=distributor.super_distributor.id)

        if Sdist:
            sd_cmsn = Commission.objects.get(super_distributor=Sdist, operator=operator)

            # sd_percentage = float(sd_cmsn.receive_commission) - float(
            #     sd_cmsn.forward_commission
            # )
            sd_percentage = float(sd_cmsn.receive_commission)
            percentage = percentage / 100
            dAmt = amt * percentage

            sd_percentage = sd_percentage / 100
            sdAmt = amt * sd_percentage

            dWallet = DistributorWallet.objects.get(distributor=distributor)
            if dWallet:
                __wltAmt = float(dWallet.amount)
                WalletTransaction.objects.create(
                    wallet=dWallet, amount=dAmt, type=1, cumulative=(__wltAmt + dAmt)
                )
                dWallet.amount = __wltAmt + dAmt
                dWallet.save()

            __wltAmt = 0
            sdWallet = DistributorWallet.objects.get(super_distributor=Sdist)
            if sdWallet:
                __wltAmt = float(sdWallet.amount)
                WalletTransaction.objects.create(
                    wallet=sdWallet, amount=sdAmt, type=1, cumulative=(__wltAmt + sdAmt)
                )
                sdWallet.amount = __wltAmt + sdAmt
                sdWallet.save()


class GetTotalBalance(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = Wallet.objects.filter(is_active=True).aggregate(Sum("amount"))
            if data["amount__sum"] != None:
                __rslt["data"] = data["amount__sum"]
            else:
                __rslt["data"] = 0

            __rslt["ok"] = 1

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


# def thirdPartyRecharge(self, userData, wlt, __rslt, distributor):

#     api = "2c57de69ef0749409e3e44a669b258c4"
#     order_id = "".join(random.choices("0123456789", k=10))
#     operator = Operator.objects.filter(operator_id=userData["operator"])
#     operator_code = ""
#     if len(operator) > 0:
#         operator_code = operator[0].operator_code

#     circle = State.objects.filter(id=userData["circle"])
#     if len(circle) > 0:
#         circle = circle[0].operator_code

#     myData = {
#         "token": api,
#         "number": userData["mobile"],
#         "operator": operator_code,
#         "circle": circle,
#         "amount": userData["amount"],
#         "agentid": order_id,
#         # "agentid": "AP648876",
#     }
#     query_string = urlencode(myData)
#     response = requests.get(
#         f"https://www.emantor.com/ApiServices/Recharge/Payment.aspx?{query_string}"
#         + "&format={{json}}"
#     )

#     response = response.json()

#     __rslt["qry"] = query_string
#     __rslt["data"] = response
#     if response["StatusCode"] != "ERR":
#         sts = 2  # for pending
#         if response["StatusCode"] == "TXN":
#             sts = 1
#         elif response["StatusCode"] == "TUP":
#             sts = 2

#         if "Data" in response:
#             res_data = response["Data"]
#             rech = Recharge.objects.create(
#                 order_id=order_id,
#                 recharge_id=res_data["APITransID"],
#                 mobile=res_data["Number"],
#                 status=sts,
#                 source=2,
#                 retailer_id=int(userData["retailer"]),
#                 operator=operator[0],
#                 operator_no=res_data["Number"],
#                 amount=userData["amount"],
#                 # date=res_data["DateTime"],
#             )

#             trans = Transaction.objects.create(
#                 order_id=order_id,
#                 tnx_id=res_data["APITransID"],
#                 source=2,
#                 retailer_id=int(userData["retailer"]),
#                 operator=operator[0],
#                 amount=userData["amount"],
#                 # date=res_data["DateTime"],
#                 transaction_type=2,
#                 status=sts,
#                 remark=res_data["APIMessage"],
#                 recharge=rech,
#             )

#             # if sts == 1:

#             cmsn = Commission.objects.get(
#                 distributor=distributor, operator=operator[0]
#             )

#             rch_amount = float(userData["amount"])

#             one_per_amt = rch_amount / 100

#             cm_amt = float(cmsn.forward_commission) * one_per_amt

#             # cm_amt = float(operator[0].commission) * one_per_amt

#             rch_amount = rch_amount - cm_amt
#             trans.deduction_amount = rch_amount
#             rech.deduction_amount = rch_amount
#             trans.commission_amount = cm_amt
#             rech.commission_amount = cm_amt
#             rech.save()
#             trans.save()
#             wlt.amount = float(wlt.amount) - rch_amount
#             wlt.save()

#             __rslt["ok"] = 1
#             __rslt["data"] = response
#         else:
#             __rslt["ok"] = 0
#             __rslt["error"] = response["Message"]
#     else:
#         __rslt["ok"] = 0
#         if "Message" in response:
#             __rslt["error"] = response["Message"]
#         else:
#             __rslt["error"] = response["data"]

#     return __rslt


class RechargeAPI(APIView):
    authentication_classes = []
    permission_classes = []
    lock = threading.Lock()

    def get(self, request, id=0, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            retailer = []

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)

    def post(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:

            with self.lock:  # Thread-level lock
                with transaction.atomic():  # Database-level atomicity
                    userData = request.data
                    # Lock mechanism to prevent concurrent requests
                    rtr = Retailer.objects.select_for_update().get(
                        id=userData["retailer"]
                    )

                    if rtr.transaction_in_progress:
                        raise Exception(
                            "Another transaction is in progress. Please wait."
                        )

                    # Mark the transaction as in progress
                    rtr.transaction_in_progress = True
                    rtr.save()
                    __amt = int(float(str(userData["amount"])))
                    # Wallet and deduction logic
                    wlt = (
                        Wallet.objects.select_for_update()
                        .filter(
                            retailer__id=userData["retailer"],
                            amount__gte=__amt,
                        )
                        .first()
                    )

                    if not wlt:
                        raise Exception("Low Wallet Balance!")

                    __amt = int(float(str(userData["amount"])))
                    if __amt == 99:
                        raise Exception("Invalid Recharge!")

                    if not rtr.distributor:
                        raise Exception("You don't have distributor!")

                    # Deduct amount from wallet instantly
                    deducted_amount = float(userData["amount"])
                    wlt.amount = float(wlt.amount) - deducted_amount
                    wlt.save()

                    try:

                        __mrobotics = MRobotics.objects.filter(
                            operator__operator_id=userData["operator"],
                            balance__gte=float(userData["amount"]),
                        ).first()

                        if not __mrobotics:
                            raise Exception("Low Balance in API Admin")

                        oprtr = Operator.objects.get(operator_id=userData["operator"])

                        trans = TransferRecharge.objects.filter(
                            operator_from=oprtr, amount=float(userData["amount"])
                        ).last()

                        if trans:
                            if trans.operator_to:
                                oprtr = trans.operator_to
                                userData["operator"] = trans.operator_to.operator_id

                        rech = Recharge.objects.create(
                            mobile=userData["mobile"],
                            status=2,
                            source=1,
                            retailer_id=int(userData["retailer"]),
                            operator=oprtr,
                            amount=userData["amount"],
                        )

                        trans = Transaction.objects.create(
                            source=2,
                            retailer_id=int(userData["retailer"]),
                            operator=oprtr,
                            amount=userData["amount"],
                            transaction_type=2,
                            status=2,
                            recharge=rech,
                        )

                        sts = 2  # Pending
                        oprator_skip = ManualRecharge.objects.filter(
                            operator=oprtr, is_active=True
                        ).exists()
                        if not oprator_skip:

                            # Perform the transaction logic
                            api = env("Mr_TOKEN")
                            order_id = "".join(random.choices("0123456789", k=10))
                            myData = {
                                "api_token": api,
                                "mobile_no": userData["mobile"],
                                "amount": userData["amount"],
                                "company_id": userData["operator"],
                                "order_id": order_id,
                                "is_stv": "false",
                            }

                            mroboData = requests.post(
                                "https://mrobotics.in/api/recharge/",
                                data=myData,
                                # timeout=15,
                            )

                            mroboData = mroboData.json()

                            if mroboData["status"] == "failure":
                                raise Exception(
                                    mroboData.get("response", json.dumps(mroboData))
                                )

                            if mroboData["status"] == "success":
                                sts = 1
                            elif mroboData["status"] == "failure":
                                sts = 3
                        else:
                            mroboData = {
                                "id": "Manual",
                                "order_id": "Manual",
                                "user_id": "Manual",
                                "lapu_id": 0,
                                "mobile_no": userData["mobile"],
                                "recharge_date": datetime.datetime.now(),
                                "tnx_id": "Manual",
                                "response": "Manual",
                                "status": 2,
                            }

                        rech.order_id = mroboData["order_id"]
                        rech.recharge_id = mroboData["id"]
                        rech.user_id = mroboData["user_id"]
                        rech.lapu_id = mroboData["lapu_id"]
                        rech.operator_no = mroboData["mobile_no"]
                        rech.date = mroboData["recharge_date"]
                        rech.status = sts
                        rech.save()

                        trans.order_id = mroboData["order_id"]
                        trans.tnx_id = mroboData["tnx_id"]
                        trans.remark = mroboData["response"]
                        trans.date = mroboData["recharge_date"]
                        trans.status = sts
                        trans.save()

                        if not oprator_skip:
                            mrobotics = MRobotics.objects.filter(
                                operator__operator_id=mroboData["company_id"],
                                lapu_id=mroboData["lapu_id"],
                            ).first()
                            if mrobotics:
                                mrobotics.balance = mroboData["balance"]
                                mrobotics.save()
                        if oprator_skip:
                            sts = 1

                        if sts == 1:
                            cmsn = Commission.objects.get(
                                distributor=rtr.distributor, operator=oprtr
                            )
                            rch_amount = float(userData["amount"])
                            one_per_amt = rch_amount / 100
                            cm_amt = float(cmsn.forward_commission) * one_per_amt
                            rch_amount -= cm_amt

                            trans.deduction_amount = rch_amount
                            rech.deduction_amount = rch_amount
                            trans.commission_amount = cm_amt
                            rech.commission_amount = cm_amt
                            trans.cumulative_amount = getCumulativeAmount(
                                rtr, 0, rch_amount, trans.id
                            )
                            trans.status = sts
                            trans.save()
                            rech.save()
                            try:
                                wlt.amount = float(wlt.amount) + deducted_amount
                                wlt.amount = float(wlt.amount) - float(rch_amount)
                                wlt.save()
                            except Exception as ex:
                                RechargeErrors.objects.create(
                                    recharge=rech,
                                    retailer=rtr,
                                    error=f"We will revert the charge Failed to save wallet: {str(ex)}",
                                )
                                raise Exception(f"Failed to save wallet: {str(ex)}")

                            distributeCommission(cmsn, rch_amount)

                            __rslt["ok"] = 1
                            __rslt["data"] = mroboData
                        else:
                            __rslt["ok"] = 0
                            __rslt["error"] = "Transaction Failed Check Lapu"

                    except Exception as ex:
                        RechargeErrors.objects.create(error=ex)
                        # Rollback the deducted amount in case of failure
                        wlt.amount = float(wlt.amount) + deducted_amount
                        wlt.save()
                        raise ex  # Re-raise the exception after rollback

                    finally:
                        # Ensure the transaction flag is cleared in all cases
                        rtr.transaction_in_progress = False
                        rtr.save()

        except Exception as ex:
            RechargeErrors.objects.create(error=ex)
            __rslt["error"] = str(ex)
            # Handle exception and log errors

        return Response(__rslt)

    # def post(self, request, format=None):
    #     __rslt = {"ok": 0, "message": "", "error": "", "data": None}
    #     try:
    #         userData = request.data

    #         with transaction.atomic():
    #             # Lock mechanism to prevent concurrent requests
    #             rtr = Retailer.objects.select_for_update().get(id=userData["retailer"])

    #             if rtr.transaction_in_progress:
    #                 raise Exception("Another transaction is in progress. Please wait.")

    #             # Mark the transaction as in progress
    #             rtr.transaction_in_progress = True
    #             rtr.save()

    #             try:
    #                 # Your business logic here
    #                 __amt = int(str(userData["amount"]))
    #                 if __amt == 99:
    #                     raise Exception("Invalid Recharge!")

    #                 if not rtr.distributor:
    #                     raise Exception("You don't have distributor!")

    #                 wlt = Wallet.objects.filter(
    #                     retailer__id=userData["retailer"], amount__gte=userData["amount"]
    #                 ).first()

    #                 if not wlt:
    #                     raise Exception("Low Wallet Balance!")

    #                 # Perform the transaction logic
    #                 # Example: Call external API with timeout
    #                 api = env("Mr_TOKEN")
    #                 order_id = "".join(random.choices("0123456789", k=10))
    #                 myData = {
    #                     "api_token": api,
    #                     "mobile_no": userData["mobile"],
    #                     "amount": userData["amount"],
    #                     "company_id": userData["operator"],
    #                     "order_id": order_id,
    #                     "is_stv": "false",
    #                 }

    #                 mroboData = requests.post(
    #                     "https://mrobotics.in/api/recharge/", data=myData, timeout=10
    #                 ).json()

    #                 if mroboData["status"] == "failure":
    #                     raise Exception(mroboData.get("errorMessage", "Unknown Error"))

    #                 # Update balance, transaction, and other related objects
    #                 wlt.amount -= float(userData["amount"])
    #                 wlt.save()

    #                 # Further logic...

    #                 __rslt["ok"] = 1
    #                 __rslt["data"] = mroboData

    #             finally:
    #                 # Ensure the transaction flag is cleared in all cases
    #                 rtr.transaction_in_progress = False
    #                 rtr.save()

    #     except Exception as ex:
    #         __rslt["error"] = str(ex)
    #         # Handle exception and log errors

    #     return Response(__rslt)


class RechargeTransactionsAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, retailerID=0, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:

            data = request.GET
            search = data.get("text", None)
            from_date = data.get("from_date", None)
            to_date = data.get("to_date", None)

            if from_date and from_date != "null":
                from_date = str(from_date).split(" ")[0]
            else:
                from_date = None
            if to_date and to_date != "null":
                to_date = str(to_date).split(" ")[0]
            else:
                to_date = None

            transactions = Recharge.objects.filter(retailer__id=retailerID)

            if search:
                transactions = transactions.filter(
                    Q(mobile__icontains=search)
                    | Q(order_id__icontains=search)
                    | Q(recharge_id__icontains=search),
                )

            if from_date and to_date:
                from_date = datetime.datetime.strptime(from_date, "%Y-%m-%d").date()
                to_date = datetime.datetime.strptime(to_date, "%Y-%m-%d").date()
                transactions = transactions.filter(date__range=(from_date, to_date))

            if len(transactions) > 0:
                transactions = transactions.order_by("-pk")
                __rslt["data"] = RechargeSerializer(transactions, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "Transactions not found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class ThirdPartyRechargeAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, id=0, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            retailer = []

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)

    def post(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            userData = request.data
            rtr = Retailer.objects.get(id=userData["retailer"])

            if rtr.distributor:

                wlt = Wallet.objects.filter(
                    retailer__id=userData["retailer"], amount__gte=userData["amount"]
                )

                if len(wlt) > 0:
                    wlt = wlt[0]

                    api = "2c57de69ef0749409e3e44a669b258c4"
                    order_id = "".join(random.choices("0123456789", k=10))

                    myData = {
                        "token": api,
                        "number": userData["account"],
                        "operator": userData["operator"],
                        "circle": userData["circle"],
                        "amount": userData["amount"],
                        "agentid": order_id,
                        # "agentid": "AP648876",
                    }
                    query_string = urlencode(myData)
                    response = requests.get(
                        f"https://www.emantor.com/ApiServices/Recharge/Payment.aspx?{query_string}"
                        + "&format={{json}}"
                    )

                    response = response.json()

                    __rslt["qry"] = query_string
                    __rslt["data"] = response
                    if response["StatusCode"] != "ERR":
                        sts = 2  # for pending
                        if response["StatusCode"] == "TXN":
                            sts = 1
                        elif response["StatusCode"] == "TUP":
                            sts = 2

                        if "Data" in response:
                            oprtr = Operator.objects.get(
                                operator_code=userData["operator"]
                            )
                            res_data = response["Data"]
                            rech = Recharge.objects.create(
                                order_id=order_id,
                                recharge_id=res_data["APITransID"],
                                mobile=res_data["Number"],
                                status=sts,
                                source=2,
                                retailer_id=int(userData["retailer"]),
                                operator=oprtr,
                                operator_no=res_data["Number"],
                                amount=userData["amount"],
                                # date=res_data["DateTime"],
                            )

                            trans = Transaction.objects.create(
                                order_id=order_id,
                                tnx_id=res_data["APITransID"],
                                source=2,
                                retailer_id=int(userData["retailer"]),
                                operator=oprtr,
                                amount=userData["amount"],
                                # date=res_data["DateTime"],
                                transaction_type=2,
                                status=sts,
                                remark=res_data["APIMessage"],
                                recharge=rech,
                            )

                            # mrobotics = MRobotics.objects.filter(
                            #     operator__operator_id=response["company_id"],
                            #     lapu_id=response["lapu_id"],
                            # )
                            # if len(mrobotics) > 0:
                            #     opr = mrobotics[0]
                            #     opr.balance = response["balance"]
                            #     opr.save()
                            if sts == 1:
                                cmsn = Commission.objects.get(
                                    distributor=rtr.distributor, operator=oprtr
                                )

                                rch_amount = float(userData["amount"])

                                one_per_amt = rch_amount / 100

                                cm_amt = float(cmsn.forward_commission) * one_per_amt

                                # cm_amt = float(oprtr.commission) * one_per_amt

                                rch_amount = rch_amount - cm_amt
                                trans.deduction_amount = rch_amount
                                rech.deduction_amount = rch_amount
                                trans.commission_amount = cm_amt
                                rech.commission_amount = cm_amt
                                rech.save()
                                trans.save()
                                wlt.amount = float(wlt.amount) - rch_amount
                                wlt.save()

                            __rslt["ok"] = 1
                            __rslt["data"] = response
                        else:
                            __rslt["ok"] = 0
                            __rslt["error"] = response["Message"]

                    else:
                        __rslt["ok"] = 0
                        if "Message" in response:
                            __rslt["error"] = response["Message"]
                        else:
                            __rslt["error"] = response["data"]
                else:
                    __rslt["error"] = "Insufficient Wallet Balance!"
            else:
                __rslt["error"] = "You don't have distributor!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class StatusThirdPartyRecharge(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, id, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            rech = Recharge.objects.filter(id=id)
            if len(rech) > 0:
                order_id = rech[0].order_id
                api = "2c57de69ef0749409e3e44a669b258c4"

                myData = {
                    "token": api,
                    "agentid": order_id,
                }
                query_string = urlencode(myData)
                response = requests.get(
                    f"https://www.emantor.com/ApiServices/Recharge/Status.aspx?{query_string}"
                    + "&format={{json}}"
                )

                response = response.json()

                # __rslt["qry"] = query_string
                __rslt["data"] = response
                if response["StatusCode"] != "ERR":
                    sts = 2  # for pending
                    if response["StatusCode"] == "TXN":
                        sts = 1
                    elif response["StatusCode"] == "TUP":
                        sts = 2

                    if "Data" in response:
                        rech = rech[0]
                        # oprtr = rech.operator
                        # wlt = Wallet.objects.get(retailer=rech.retailer)
                        trans = Transaction.objects.get(order_id=order_id)

                        if sts == 1:
                            # rch_amount = float(rech.amount)
                            # one_per_amt = rch_amount / 100
                            # cm_amt = float(oprtr.commission) * one_per_amt

                            trans.status = 1
                            rech.status = 1

                            # rch_amount = rch_amount - cm_amt
                            # trans.deduction_amount = rch_amount
                            # rech.deduction_amount = rch_amount
                            # trans.commission_amount = cm_amt
                            # rech.commission_amount = cm_amt

                            rech.save()
                            trans.save()

                            # wlt.amount = float(wlt.amount) - rch_amount
                            # wlt.save()

                            # rtr = rech.retailer
                            # oprtr = rech.operator
                            oprtr = Operator.objects.get(id=rech.operator.id)
                            rtr = Retailer.objects.get(id=rech.retailer.id)
                            cmsn = Commission.objects.get(
                                distributor=rtr.distributor, operator=oprtr
                            )

                            distributeCommission(cmsn, rech.amount)

                            __rslt["ok"] = 1
                            __rslt["data"] = response
                        else:
                            __rslt["ok"] = 0
                            __rslt["error"] = response["Message"]
                    else:
                        __rslt["ok"] = 0
                        __rslt["error"] = response["Message"]

                else:
                    __rslt["ok"] = 0
                    if "Message" in response:
                        __rslt["error"] = response["Message"]
                    else:
                        __rslt["error"] = response["data"]
            else:
                __rslt["error"] = "Recharge Not found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class FindOperatorsAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, mobile, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:

            url = f"http://planapi.in/api/Mobile/OperatorFetchNew?ApiUserID=6792&ApiPassword=Obaidur@2001&Mobileno={mobile}"
            response = requests.get(url)

            if response.status_code == 200:
                data = response.json()
                if int(data["ERROR"]) > 0:
                    __rslt["error"] = data["Message"]
                    __rslt["ok"] = 0
                else:

                    states = State.objects.filter(api_code=data["CircleCode"])
                    operators = Operator.objects.filter(api_code=data["OpCode"])
                    rs = {"circle": 0, "operator": 0}
                    if len(states) > 0:
                        rs["circle"] = states[0].id
                    else:
                        raise Exception("Circle Not Found!")

                    if len(operators) > 0:
                        rs["operator"] = operators[0].operator_id
                        rs["operator__name"] = operators[0].name
                    else:
                        raise Exception("Operator Not Found!")

                    __rslt["data"] = [rs]
                    __rslt["ok"] = 1

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class FindROffersAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, mobile_no, operatorcode, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            operators = Operator.objects.filter(operator_id=operatorcode)

            if len(operators) > 0:
                operatorcode = operators[0].api_code

                url = f"http://planapi.in/api/Mobile/RofferCheck?apimember_id=6792&api_password=Obaidur@2001&mobile_no={mobile_no}&operator_code={operatorcode}"
                response = requests.get(url)

                if response.status_code == 200:
                    data = response.json()
                    __rslt["data"] = data
                    if int(data["ERROR"]) > 0:
                        __rslt["error"] = data["MESSAGE"]
                        __rslt["ok"] = 0
                    else:
                        __rslt["data"] = data["RDATA"]
                        __rslt["ok"] = 1
                else:
                    __rslt["data"] = response.json()

            else:
                __rslt["error"] = "Operators not found!"
                __rslt["ok"] = 0

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class FindPlanOffersAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, cricle, operatorcode, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            circles = State.objects.filter(id=cricle)
            operators = Operator.objects.filter(operator_id=operatorcode)

            if len(circles) > 0 and len(operators) > 0:
                cricle = circles[0].api_code
                operatorcode = operators[0].api_code

                url = f"http://planapi.in/api/Mobile/Operatorplan?apimember_id=6792&api_password=Obaidur@2001&cricle={cricle}&operatorcode={operatorcode}"
                response = requests.get(url)

                if response.status_code == 200:
                    data = response.json()
                    if int(data["ERROR"]) > 0:
                        __rslt["error"] = data["MESSAGE"]
                        __rslt["ok"] = 0
                    else:
                        __rslt["data"] = data["RDATA"]
                        __rslt["ok"] = 1

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class EmantorFetchBill(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = request.data

            api = "2c57de69ef0749409e3e44a669b258c4"
            # order_id = "".join(random.choices("0123456789", k=10))

            myData = {
                "token": api,
                "number": data["account"],
                "operator": data["operator"],
                # "agentid": "AP648876",
            }

            query_string = urlencode(myData)

            url = (
                f"https://www.emantor.com/ApiServices/Operator/BillFetch.aspx?{query_string}"
                + "&format={{json}}"
            )
            response = requests.get(url)

            if response.status_code == 200:
                data = response.json()
                if data["StatusCode"] == "TXN":
                    __rslt["data"] = data["Data"]
                    __rslt["ok"] = 1
                else:
                    __rslt["data"] = data
                    __rslt["error"] = data["Message"]
                    __rslt["ok"] = 0

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class FetchBill(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, accountno, operatorcode, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            operators = Operator.objects.filter(operator_id=operatorcode)

            if len(operators) > 0:
                operatorcode = operators[0].api_code

                url = f"http://planapi.in/api/Mobile/BillCheck?apimember_id=6792&api_password=Obaidur@2001&Accountno={accountno}&operator_code={operatorcode}"
                response = requests.get(url)
                data = response.json()

                if response.status_code == 200:

                    if data["ERROR"]:
                        if int(data["ERROR"]) > 0:
                            __rslt["error"] = data["MESSAGE"]
                            __rslt["ok"] = 0
                        else:
                            __rslt["data"] = data["BILLDEATILS"]
                            __rslt["ok"] = 1
                    else:
                        __rslt["error"] = data["MESSAGE"]
                        __rslt["ok"] = 0
            else:
                __rslt["error"] = "operators not found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)

    def post(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = request.data

            api = "2c57de69ef0749409e3e44a669b258c4"
            # order_id = "".join(random.choices("0123456789", k=10))

            myData = {
                "token": api,
                "number": data["account"],
                "operator": data["operator"],
                # "agentid": "AP648876",
            }

            query_string = urlencode(myData)

            url = (
                f"https://www.emantor.com/ApiServices/Operator/BillFetch.aspx?{query_string}"
                + "&format={{json}}"
            )
            response = requests.get(url)

            if response.status_code == 200:
                data = response.json()
                if data["StatusCode"] == "TXN":
                    __rslt["data"] = data["Data"]
                    __rslt["ok"] = 1
                else:
                    __rslt["data"] = data
                    __rslt["error"] = data["Message"]
                    __rslt["ok"] = 0

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)
