from rest_framework import serializers
from snow_flake.models import *
from django.db.models import *
import math

languageKey = "languageId"


# Start Parameters in request URL
def getLanguage(self):
    if self.context.__contains__("request"):
        languageId = self.context["request"].query_params.get(languageKey, None)
    elif self.context.__contains__(languageKey):
        languageId = self.context[languageKey]
    else:
        languageId = None

    if languageId is not None:
        selectedLanguage = Language.objects.get(id=languageId)
        if selectedLanguage.isEnabled:
            return languageId

    return None


def getIsDashboard(self):
    if self.context.__contains__("request"):
        isDashboard = self.context["request"].query_params.get("isDashboard", None)
    elif self.context.__contains__("isDashboard"):
        isDashboard = self.context["isDashboard"]
    else:
        isDashboard = None
    return isDashboard


def getClientId(self):
    clientId = None
    if self.context.__contains__("request"):
        clientId = self.context["request"].query_params.get("clientId", None)
    elif self.context.__contains__("clientId"):
        clientId = self.context["clientId"]
    return clientId


def getIsShowFeatureBullet(self):
    if self.context.__contains__("request"):
        isShowFeatureBullet = self.context["request"].query_params.get(
            "isShowFeatureBullet", None
        )
    elif self.context.__contains__("isShowFeatureBullet"):
        isShowFeatureBullet = self.context["isShowFeatureBullet"]
    else:
        isShowFeatureBullet = None
    return isShowFeatureBullet


def getIsMultipleSKU(self):
    if self.context.__contains__("request"):
        isMultipleSKU = self.context["request"].query_params.get("isMultipleSKU", None)
    elif self.context.__contains__("isMultipleSKU"):
        isMultipleSKU = self.context["isMultipleSKU"]
    else:
        isMultipleSKU = None
    return isMultipleSKU


def getIsShowItem(self):
    if self.context.__contains__("request"):
        isSKUDetail = self.context["request"].query_params.get("isShowItem", None)
    elif self.context.__contains__("isShowItem"):
        isSKUDetail = self.context["isShowItem"]
    else:
        isSKUDetail = None
    return isSKUDetail


def getIsShowRequestReturnDetail(self):
    if self.context.__contains__("request"):
        isShowRequestReturnDetail = self.context["request"].query_params.get(
            "isShowRequestReturnDetail", None
        )
    elif self.context.__contains__("isShowRequestReturnDetail"):
        isShowRequestReturnDetail = self.context["isShowRequestReturnDetail"]
    else:
        isShowRequestReturnDetail = None
    return isShowRequestReturnDetail


def getIsShowShippingItemDetail(self):
    if self.context.__contains__("request"):
        isShowShippingItemDetail = self.context["request"].query_params.get(
            "isShowShippingItemDetail", None
        )
    elif self.context.__contains__("isShowShippingItemDetail"):
        isShowShippingItemDetail = self.context["isShowShippingItemDetail"]
    else:
        isShowShippingItemDetail = None
    return isShowShippingItemDetail


def getIsFavoriteWithCurrentClient(self, instance):
    clientId = getClientId(self)
    val = 0
    if clientId is not None:
        val = (
            Favorite.objects.filter(itemId=str(instance.id))
            .filter(clientId=str(clientId))
            .count()
        )
    if val > 0:
        return True
    return False


def getIsShowCountry(self):
    if self.context.__contains__("request"):
        isShowCountry = self.context["request"].query_params.get("isShowCountry", None)
    elif self.context.__contains__("isShowCountry"):
        isShowCountry = self.context["isShowCountry"]
    else:
        isShowCountry = None
    return isShowCountry


def getIsShowShippingMethod(self):
    if self.context.__contains__("request"):
        isShowShippingMethod = self.context["request"].query_params.get(
            "isShowShippingMethod", None
        )
    elif self.context.__contains__("isShowShippingMethod"):
        isShowShippingMethod = self.context["isShowShippingMethod"]
    else:
        isShowShippingMethod = None
    return isShowShippingMethod


def getIsShowDeliveryMan(self):
    if self.context.__contains__("request"):
        isShowDeliveryMan = self.context["request"].query_params.get(
            "isShowDeliveryMan", None
        )
    elif self.context.__contains__("isShowDeliveryMan"):
        isShowDeliveryMan = self.context["isShowDeliveryMan"]
    else:
        isShowDeliveryMan = None
    return isShowDeliveryMan

def calculatePrice(price,skuCost):
    if skuCost is not None:
        serviceCost = (price * skuCost.serviceCost) / 100
        handlingCost = (price * skuCost.handlingCost) / 100
        packingCost = (price * skuCost.packingCost) / 100
        taxCost = ((serviceCost + handlingCost + packingCost + price) * skuCost.taxCost)/100
        total = serviceCost + handlingCost + packingCost + taxCost + skuCost.transactionFixedCost + price
        transactionFeeCost = (total * skuCost.transactionFeeCost ) / 100
        overall = total + transactionFeeCost
        return overall,skuCost.id


# End Parameters in request URL


def getCountry(self, instance):
    languageId = getLanguage(self)
    country = Country.objects.get(id=str(instance.countryId.id))
    return CountrySerializer(country, context={languageKey: languageId}).data

def getState(self, instance):
    languageId = getLanguage(self)
    if instance.stateId is not None:
        state = State.objects.get(id=str(instance.stateId.id))
        return StateSerializer(
            state, context={languageKey: languageId}
        ).data

def getCity(self, instance):
    languageId = getLanguage(self)
    if instance.cityId is not None:
        state = City.objects.get(id=str(instance.cityId.id))
        return CitySerializer(
            state, context={languageKey: languageId}
        ).data

def getShippingMethod(self, instance):
    shippingMethod = ShippingMethod.objects.get(id=str(instance.shippingMethodId.id))
    return ShippingMethodSerializer(shippingMethod).data

def getDeliveryMan(self, instance):
    deliveryMan = DeliveryMan.objects.get(id=str(instance.deliveryManId.id))
    return DeliveryManSerializer(deliveryMan).data

def getDepartment(self, instance):
    languageId = getLanguage(self)
    department = Department.objects.get(id=str(instance.departmentId.id))
    return DepartmentSerializer(
        department, context={languageKey: languageId}
    ).data


def getTransactionType(self, instance):
    languageId = getLanguage(self)
    transactionType = TransactionType.objects.get(id=str(instance.transactionTypeId.id))
    return TransactionTypeSerializer(
        transactionType, context={languageKey: languageId}
    ).data


# def getTaxes(self, instance):
#     languageId = getLanguage(self)
#     taxes = Taxes.objects.get(id=str(instance.taxesId.id))
#     return TaxesSerializer(taxes, context={languageKey: languageId}).data


def getPaymentMethod(self, instance):
    languageId = getLanguage(self)
    paymentMethod = PaymentMethod.objects.get(id=str(instance.paymentMethodId.id))
    return PaymentMethodSerializer(
        paymentMethod, context={languageKey: languageId}
    ).data


def getSubscriptionStatus(self, instance):
    languageId = getLanguage(self)
    subscriptionStatus = SubscriptionStatus.objects.get(
        id=str(instance.subscriptionStatusId.id)
    )
    return SubscriptionStatusSerializer(
        subscriptionStatus, context={languageKey: languageId}
    ).data


def getSubscriptionType(self, instance):
    languageId = getLanguage(self)
    subscriptionType = SubscriptionType.objects.get(
        id=str(instance.subscriptionTypeId.id)
    )
    return SubscriptionTypeSerializer(
        subscriptionType, context={languageKey: languageId}
    ).data


# def getReturnCost(self, instance):
#     languageId = getLanguage(self)
#     returnCost = ReturnCost.objects.get(id=str(instance.returnCostId.id))
#     return ReturnCostSerializer(returnCost, context={languageKey: languageId}).data


def getReturnStatus(self, instance):
    languageId = getLanguage(self)
    returnStatus = ReturnStatus.objects.get(id=str(instance.returnStatusId.id))
    return ReturnStatusSerializer(returnStatus, context={languageKey: languageId}).data


def getSKU(self, instance):
    clientId = getClientId(self)
    languageId = getLanguage(self)
    isDashboard = getIsDashboard(self)
    isShowItem = getIsShowItem(self)
    sku = SKU.objects.get(id=instance.skuId.id)
    return SKUSerializer(
        sku,
        context={
            "clientId": clientId,
            languageKey: languageId,
            "isDashboard": isDashboard,
            "isShowItem": isShowItem,
        },
    ).data


def getClient(self, instance):
    languageId = getLanguage(self)
    client = Client.objects.get(id=str(instance.clientId.id))
    return ClientDisplaySerializer(client, context={languageKey: languageId}).data


def getSupplierInfo(self, instance):
    supplier = Supplier.objects.get(id=str(instance.supplierId.id))
    return SupplierDisplaySerializer(supplier).data


class DashboardDataSerializer(serializers.Serializer):
    countItems = serializers.IntegerField()
    sumPaymentTotal = serializers.FloatField()
    sumPaymentPaid = serializers.FloatField()
    sumPaymentChange = serializers.FloatField()
    countTransactionIn = serializers.IntegerField()
    sumTransactionInTotal = serializers.FloatField()
    sumTransactionInPaid = serializers.FloatField()
    countTransactionOut = serializers.IntegerField()
    sumTransactionOutTotal = serializers.FloatField()
    sumTransactionOutPaid = serializers.FloatField()
    currentBalanceTotal = serializers.FloatField()
    currentBalancePaid = serializers.FloatField()
    currentSumTaxes = serializers.FloatField()

# Settings


class SettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Settings
        fields = [
            "id",
            "isMaintenanceClient",
            "isMaintenanceSupplier",
            "isEnableFreeSubscriptionForSupplier",
            "itemSKULimit",
            "itemSKUOptionLimit",
            "itemFeatureBulletLimit",
            "maxCartQuantity",
            "isEnableStoreBankCards",
            #"isDiscountOnMultipleProducts",
            "isShowBrands",
            "isInitialSettingsDone",
            "createdDate",
            "updatedDate",
        ]


# Language


class LanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Language
        fields = [
            "id",
            "name",
            "countryCode",
            "isEnabled",
            "languageCode",
            "createdDate",
            "updatedDate",
        ]


# Social Link


class SocialLinkSerializer(serializers.ModelSerializer):
    tokenCount = serializers.SerializerMethodField()

    class Meta:
        model = SocialLink
        fields = [
            "id",
            "name",
            "url",
            "createdDate",
            "updatedDate",
            "tokenCount",
        ]

    def get_tokenCount(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                currentList = SocialLinkToken.objects.filter(socialLinkId=instance.id)
                if currentList.__len__() > 0:
                    return 1
                return 0
            return -1
        return -1


class SocialLinkTokenSerializer(serializers.ModelSerializer):
    class Meta:
        model = SocialLinkToken
        fields = [
            "id",
            "socialLinkId",
            "token",
            "longToken",
            "timeInSeconds",
        ]


# Provider


class RegisterTypeSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = RegisterType
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            registerTypeLanguageList = RegisterTypeLanguage.objects.filter(
                registerTypeId=str(instance.id)
            ).filter(languageId=languageId)
            if registerTypeLanguageList.__len__() > 0:
                return registerTypeLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                registerTypeLanguageList = RegisterTypeLanguage.objects.filter(
                    registerTypeId=str(instance.id)
                )
                if registerTypeLanguageList.__len__() > 0:
                    return RegisterTypeLanguageSerializer(
                        registerTypeLanguageList, many=True
                    ).data


class RegisterTypeLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegisterTypeLanguage
        fields = [
            "id",
            "name",
            "registerTypeId",
            languageKey,
        ]

class OrderFromSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = OrderFrom
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        orderFromLanguageList = OrderFromLanguage.objects.filter(
            orderFromId=str(instance.id)
        ).filter(languageId=languageId)
        if orderFromLanguageList.__len__() > 0:
            return orderFromLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                orderFromLanguageList = OrderFromLanguage.objects.filter(
                    orderFromId=str(instance.id)
                )
                if orderFromLanguageList.__len__() > 0:
                    return OrderFromLanguageSerializer(
                        orderFromLanguageList, many=True
                    ).data

class OrderFromLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderFromLanguage
        fields = [
            "id",
            "name",
            "orderFromId",
            languageKey,
        ]


# Return Status


class ReturnStatusSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = ReturnStatus
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        returnStatusLanguageList = ReturnStatusLanguage.objects.filter(
            returnStatusId=str(instance.id)
        ).filter(languageId=languageId)
        if returnStatusLanguageList.__len__() > 0:
            return returnStatusLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                returnStatusLanguageList = ReturnStatusLanguage.objects.filter(
                    returnStatusId=str(instance.id)
                )
                if returnStatusLanguageList.__len__() > 0:
                    return ReturnStatusLanguageSerializer(
                        returnStatusLanguageList, many=True
                    ).data

class ReturnStatusLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ReturnStatusLanguage
        fields = [
            "id",
            "name",
            "returnStatusId",
            languageKey,
        ]


# Track Status


class TrackStatusSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = TrackStatus
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        trackStatusLanguageList = TrackStatusLanguage.objects.filter(
            trackStatusId=str(instance.id)
        ).filter(languageId=languageId)
        if trackStatusLanguageList.__len__() > 0:
            return trackStatusLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                trackStatusLanguageList = TrackStatusLanguage.objects.filter(
                    trackStatusId=str(instance.id)
                )
                if trackStatusLanguageList.__len__() > 0:
                    return TrackStatusLanguageSerializer(
                        trackStatusLanguageList, many=True
                    ).data

class TrackStatusLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = TrackStatusLanguage
        fields = [
            "id",
            "name",
            "trackStatusId",
            languageKey,
        ]



#Add This
class SKUCostSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUCost
        fields = [
            "id",
            "serviceCost",
            "handlingCost",
            "packingCost",
            "taxCost",
            "cancelCost",
            "returnCost",
            "transactionFixedCost",
            "transactionFeeCost",
            "isEnabled",
            "createdDate",
            "updatedDate"
        ]


# Payment Method


class PaymentMethodSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = PaymentMethod
        fields = [
            "id",
            "keyName",
            #"fixedPrice",
            #"price",
            #"isPercentage",
            "isEnabled",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        paymentMethodLanguageList = PaymentMethodLanguage.objects.filter(
            paymentMethodId=str(instance.id)
        ).filter(languageId=languageId)
        if paymentMethodLanguageList.__len__() > 0:
            return paymentMethodLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                paymentMethodLanguageList = PaymentMethodLanguage.objects.filter(
                    paymentMethodId=str(instance.id)
                )
                if paymentMethodLanguageList.__len__() > 0:
                    return PaymentMethodLanguageSerializer(
                        paymentMethodLanguageList, many=True
                    ).data


class PaymentMethodLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PaymentMethodLanguage
        fields = [
            "id",
            "name",
            "paymentMethodId",
            languageKey,
        ]


# EligableType


class EligibleTypeSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = EligibleType
        fields = [
            "id",
            "keyName",
            "keyOption",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        eligibleTypeLanguageList = EligibleTypeLanguage.objects.filter(
            eligibleTypeId=str(instance.id)
        ).filter(languageId=languageId)
        if eligibleTypeLanguageList.__len__() > 0:
            return eligibleTypeLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                eligibleTypeLanguageList = EligibleTypeLanguage.objects.filter(
                    eligibleTypeId=str(instance.id)
                )
                if eligibleTypeLanguageList.__len__() > 0:
                    return EligibleTypeLanguageSerializer(
                        eligibleTypeLanguageList, many=True
                    ).data


class EligibleTypeLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = EligibleTypeLanguage
        fields = [
            "id",
            "name",
            "eligibleTypeId",
            languageKey,
        ]


# Country


class CountrySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = Country
        fields = [
            "id",
            "isActive",
            "isMainBranch",
            "dialCode",
            "currency",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        countryLanguageList = CountryLanguage.objects.filter(
            countryId=str(instance.id)
        ).filter(languageId=languageId)
        if countryLanguageList.__len__() > 0:
            return countryLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                countryLanguageList = CountryLanguage.objects.filter(
                    countryId=str(instance.id)
                )
                if countryLanguageList.__len__() > 0:
                    return CountryLanguageSerializer(
                        countryLanguageList, many=True
                    ).data


class CountryLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = CountryLanguage
        fields = [
            "id",
            "name",
            "countryId",
            languageKey,
        ]


# State


class StateSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = State
        fields = [
            "id",
            "isActive",
            "createdDate",
            "updatedDate",
            "countryId",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        stateLanguageList = StateLanguage.objects.filter(
            stateId=str(instance.id)
        ).filter(languageId=languageId)
        if stateLanguageList.__len__() > 0:
            return stateLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                stateLanguageList = StateLanguage.objects.filter(
                    stateId=str(instance.id)
                )
                if stateLanguageList.__len__() > 0:
                    return StateLanguageSerializer(
                        stateLanguageList, many=True
                    ).data


class StateLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = StateLanguage
        fields = [
            "id",
            "name",
            "stateId",
            languageKey,
        ]

# City

class CitySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = City
        fields = [
            "id",
            "isActive",
            "createdDate",
            "updatedDate",
            "stateId",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        cityLanguageList = CityLanguage.objects.filter(
            cityId=str(instance.id)
        ).filter(languageId=languageId)
        if cityLanguageList.__len__() > 0:
            return cityLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                cityLanguageList = CityLanguage.objects.filter(
                    cityId=str(instance.id)
                )
                if cityLanguageList.__len__() > 0:
                    return CityLanguageSerializer(
                        cityLanguageList, many=True
                    ).data


class CityLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = CityLanguage
        fields = [
            "id",
            "name",
            "cityId",
            languageKey,
        ]


# Shipping Method


class ShippingMethodSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = ShippingMethod
        fields = [
            "id",
            "keyName",
            "isEnabled",
            "createdDate",
            "updatedDate",
            "name",
            "languageList"
        ]
    
    def get_name(self, instance):
        languageId = getLanguage(self)
        shippingMethodLanguageList = ShippingMethodLanguage.objects.filter(
            shippingMethodId=str(instance.id)
        ).filter(languageId=languageId)
        if shippingMethodLanguageList.__len__() > 0:
            return shippingMethodLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                shippingMethodLanguageList = ShippingMethodLanguage.objects.filter(
                    shippingMethodId=str(instance.id)
                )
                if shippingMethodLanguageList.__len__() > 0:
                    return ShippingMethodLanguageSerializer(
                        shippingMethodLanguageList, many=True
                    ).data

class ShippingMethodLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShippingMethodLanguage
        fields = [
            "id",
            "name",
            "shippingMethodId",
            languageKey,
        ]


class ShippingCostSerializer(serializers.ModelSerializer):
    country = serializers.SerializerMethodField()
    shippingMethod = serializers.SerializerMethodField()
    supplier = serializers.SerializerMethodField()

    class Meta:
        model = ShippingCost
        fields = [
            "id",
            "price",
            "additionalPrice",
            "isEnabled",
            "workingDays",
            "DeliveryDays",
            "createdDate",
            "updatedDate",
            "countryId",
            "shippingMethodId",
            "supplierId",
            "country",
            "shippingMethod",
            "supplier",
        ]

    def get_country(self, instance):
        isShowCountry = getIsShowCountry(self)
        if isShowCountry is not None:
            if bool(isShowCountry) == bool("1"):
                return getCountry(self, instance)

    def get_shippingMethod(self, instance):
        isShowShippingMethod = getIsShowShippingMethod(self)
        if isShowShippingMethod is not None:
            if bool(isShowShippingMethod) == bool("1"):
                return getShippingMethod(self, instance)
    
    def get_supplier(self, instance):
        isShowSupplier = getIsShowDeliveryMan(self)
        if isShowSupplier is not None:
            if bool(isShowSupplier) == bool("1"):
                return getSupplierInfo(self, instance)


# Department

class DepartmentSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = [
            "id",
            "keyName",
            "isVisible",
            "totalViews",
            "createdDate",
            "updatedDate",
            "isMainDepartment",
            "departmentId",
            "name",
            "languageList",
        ]
    
    def get_name(self, instance):
        languageId = getLanguage(self)
        departmentLanguageList = DepartmentLanguage.objects.filter(
            departmentId=str(instance.id)
        ).filter(languageId=languageId)
        if departmentLanguageList.__len__() > 0:
            return departmentLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                departmentLanguageList = DepartmentLanguage.objects.filter(
                    departmentId=str(instance.id)
                )
                if departmentLanguageList.__len__() > 0:
                    return DepartmentLanguageSerializer(
                        departmentLanguageList, many=True
                    ).data


class DepartmentLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = DepartmentLanguage
        fields = [
            "id",
            "name",
            "departmentId",
            languageKey,
        ]

# Brand


class BrandSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = Brand
        fields = [
            "id",
            "keyName",
            "isVisible",
            "image",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        brandLanguageList = BrandLanguage.objects.filter(
            brandId=str(instance.id)
        ).filter(languageId=languageId)
        if brandLanguageList.__len__() > 0:
            return brandLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                brandLanguageList = BrandLanguage.objects.filter(
                    brandId=str(instance.id)
                )
                if brandLanguageList.__len__() > 0:
                    return BrandLanguageSerializer(brandLanguageList, many=True).data


class BrandLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = BrandLanguage
        fields = [
            "id",
            "name",
            "brandId",
            languageKey,
        ]


class BrandDisplaySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()

    class Meta:
        model = Brand
        fields = [
            "id",
            "keyName",
            "name",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        brandLanguageList = BrandLanguage.objects.filter(
            brandId=str(instance.id)
        ).filter(languageId=languageId)
        if brandLanguageList.__len__() > 0:
            return brandLanguageList[0].name


# Subscription Status


class SubscriptionStatusSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = SubscriptionStatus
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        subscriptionStatusLanguageList = SubscriptionStatusLanguage.objects.filter(
            subscriptionStatusId=str(instance.id)
        ).filter(languageId=languageId)
        if subscriptionStatusLanguageList.__len__() > 0:
            return subscriptionStatusLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                subscriptionStatusLanguageList = (
                    SubscriptionStatusLanguage.objects.filter(
                        subscriptionStatusId=str(instance.id)
                    )
                )
                if subscriptionStatusLanguageList.__len__() > 0:
                    return SubscriptionStatusLanguageSerializer(
                        subscriptionStatusLanguageList, many=True
                    ).data


class SubscriptionStatusLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubscriptionStatusLanguage
        fields = [
            "id",
            "name",
            "subscriptionStatusId",
            languageKey,
        ]


# Subscription Option


class SubscriptionOptionSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = SubscriptionOption
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        subscriptionOptionLanguageList = SubscriptionOptionLanguage.objects.filter(
            subscriptionOptionId=str(instance.id)
        ).filter(languageId=languageId)
        if subscriptionOptionLanguageList.__len__() > 0:
            return subscriptionOptionLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                subscriptionOptionLanguageList = (
                    SubscriptionOptionLanguage.objects.filter(
                        subscriptionOptionId=str(instance.id)
                    )
                )
                if subscriptionOptionLanguageList.__len__() > 0:
                    return SubscriptionOptionLanguageSerializer(
                        subscriptionOptionLanguageList, many=True
                    ).data


class SubscriptionOptionLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubscriptionOptionLanguage
        fields = [
            "id",
            "name",
            "subscriptionOptionId",
            languageKey,
        ]


# Subscription Type


class SubscriptionTypeSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = SubscriptionType
        fields = [
            "id",
            "costPerMonth",
            "price",
            "discount",
            "serviceCost",
            "durationInMonth",
            "isEnabled",
            "createdDate",
            "updatedDate",
            "subscriptionOptionId",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        subscriptionTypeLanguageList = SubscriptionTypeLanguage.objects.filter(
            subscriptionTypeId=str(instance.id)
        ).filter(languageId=languageId)
        if subscriptionTypeLanguageList.__len__() > 0:
            return subscriptionTypeLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                subscriptionTypeLanguageList = SubscriptionTypeLanguage.objects.filter(
                    subscriptionTypeId=str(instance.id)
                )
                if subscriptionTypeLanguageList.__len__() > 0:
                    return SubscriptionTypeLanguageSerializer(
                        subscriptionTypeLanguageList, many=True
                    ).data


class SubscriptionTypeLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubscriptionTypeLanguage
        fields = [
            "id",
            "name",
            "subscriptionTypeId",
            languageKey,
        ]


# Transaction Type


class TransactionTypeSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = TransactionType
        fields = [
            "id",
            "keyName",
            "createdDate",
            "updatedDate",
            "name",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        transactionTypeLanguageList = TransactionTypeLanguage.objects.filter(
            transactionTypeId=str(instance.id)
        ).filter(languageId=languageId)
        if transactionTypeLanguageList.__len__() > 0:
            return transactionTypeLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                transactionTypeLanguageList = TransactionTypeLanguage.objects.filter(
                    transactionTypeId=str(instance.id)
                )
                if transactionTypeLanguageList.__len__() > 0:
                    return TransactionTypeLanguageSerializer(
                        transactionTypeLanguageList, many=True
                    ).data


class TransactionTypeLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = TransactionTypeLanguage
        fields = [
            "id",
            "name",
            "transactionTypeId",
            languageKey,
        ]


# New Arrival


class NewArrivalSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    description = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = NewArrival
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "name",
            "description",
            "languageList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        newArrivalLanguageList = NewArrivalLanguage.objects.filter(
            newArrivalId=str(instance.id)
        ).filter(languageId=languageId)
        if newArrivalLanguageList.__len__() > 0:
            return newArrivalLanguageList[0].name

    def get_description(self, instance):
        languageId = getLanguage(self)
        newArrivalLanguageList = NewArrivalLanguage.objects.filter(
            newArrivalId=str(instance.id)
        ).filter(languageId=languageId)
        if newArrivalLanguageList.__len__() > 0:
            return newArrivalLanguageList[0].description

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                newArrivalLanguageList = NewArrivalLanguage.objects.filter(
                    newArrivalId=str(instance.id)
                )
                if newArrivalLanguageList.__len__() > 0:
                    return NewArrivalLanguageSerializer(
                        newArrivalLanguageList, many=True
                    ).data


class NewArrivalLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = NewArrivalLanguage
        fields = [
            "id",
            "name",
            "description",
            "newArrivalId",
            languageKey,
        ]


class NewArrivalDisplaySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()

    class Meta:
        model = NewArrival
        fields = [
            "id",
            "name",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        newArrivalLanguageList = NewArrivalLanguage.objects.filter(
            newArrivalId=str(instance.id)
        ).filter(languageId=languageId)
        if newArrivalLanguageList.__len__() > 0:
            return newArrivalLanguageList[0].name


# App Content

class AppContentSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()
    class Meta:
        model = AppContent
        fields = [
            "id",
            "keyName",
            "isImage",
            "image",
            "createdDate",
            "updatedDate",
            "description",
            "languageList",
        ]
    
    def get_description(self, instance):
        languageId = getLanguage(self)
        appContentLanguageList = AppContentLanguage.objects.filter(itemId=str(instance.id)).filter(
            languageId=languageId
        )
        if appContentLanguageList.__len__() > 0:
            return appContentLanguageList[0].description
    
    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                appContentLanguageList = AppContentLanguage.objects.filter(
                    appContentId=str(instance.id)
                )
                if appContentLanguageList.__len__() > 0:
                    return AppContentLanguageSerializer(
                        appContentLanguageList, many=True
                    ).data

class AppContentLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = AppContentLanguage
        fields = [
            "id",
            "description",
            "appContentId",
            languageKey,
        ]

# Copoun


class CouponSerializer(serializers.ModelSerializer):
    class Meta:
        model = Coupon
        fields = [
            "id",
            "code",
            "discount",
            "startDate",
            "endDate",
            "description",
            "createdDate",
            "updatedDate",
        ]


# Client


class ClientSerializer(serializers.ModelSerializer):
    registerType = serializers.SerializerMethodField()
    selectedLanguage = serializers.SerializerMethodField()
    creditCardList = serializers.SerializerMethodField()
    addressBookList = serializers.SerializerMethodField()
    wallet = serializers.SerializerMethodField()

    class Meta:
        model = Client
        fields = [
            "id",
            "firstName",
            "lastName",
            "email",
            "password",
            "phone",
            "createdDate",
            "updatedDate",
            "registerTypeId",
            "selectedLanguageId",
            "registerType",
            "selectedLanguage",
            "creditCardList",
            "addressBookList",
            "wallet",
        ]

    def get_registerType(self, instance):
        languageId = getLanguage(self)
        registerType = RegisterType.objects.get(id=str(instance.registerTypeId.id))
        return RegisterTypeSerializer(
            registerType, context={languageKey: languageId}
        ).data

    def get_creditCardList(self, instance):
        creditCardList = ClientCreditCard.objects.filter(clientId=str(instance.id))
        return ClientCreditCardSerializer(creditCardList, many=True).data

    def get_addressBookList(self, instance):
        languageId = getLanguage(self)
        addressBookList = ClientAddressBook.objects.filter(
                clientId=str(instance.id)
            )
        return ClientAddressBookSerializer(
                addressBookList, many=True, context={languageKey: languageId}
            ).data

    def get_selectedLanguage(self, instance):
        selectedLanguage = Language.objects.get(id=str(instance.selectedLanguageId.id))
        return LanguageSerializer(selectedLanguage).data

    def get_wallet(self, instance):
        if Wallet.objects.filter(clientId=str(instance.id)).exists():
            wallet = Wallet.objects.get(clientId=str(instance.id))
            return WalletSerializer(wallet).data


class ClientDisplaySerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        fields = [
            "id",
            "firstName",
            "lastName",
            "phone",
        ]

# Client Credit Card


class ClientCreditCardSerializer(serializers.ModelSerializer):
    class Meta:
        model = ClientCreditCard
        fields = [
            "id",
            "holder",
            "number",
            "expireYear",
            "expireMonth",
            "createdDate",
            "updatedDate",
            "clientId",
        ]


# Address Book


class ClientAddressBookSerializer(serializers.ModelSerializer):
    country = serializers.SerializerMethodField()
    state = serializers.SerializerMethodField()
    city = serializers.SerializerMethodField()

    class Meta:
        model = ClientAddressBook
        fields = [
            "id",
            "address1",
            "address2",
            "zipCode",
            "createdDate",
            "updatedDate",
            "countryId",
            "stateId",
            "cityId",
            "clientId",
            "country",
            "state",
            "city",
        ]

    def get_country(self, instance):
        return getCountry(self, instance)

    def get_state(self, instance):
        return getState(self, instance)

    def get_city(self, instance):
        return getCity(self, instance)


# Wallet


class WalletSerializer(serializers.ModelSerializer):
    inCount = serializers.SerializerMethodField()
    inSum = serializers.SerializerMethodField()
    outCount = serializers.SerializerMethodField()
    outSum = serializers.SerializerMethodField()
    transCount = serializers.SerializerMethodField()
    transSum = serializers.SerializerMethodField()

    class Meta:
        model = Wallet
        fields = [
            "createdDate",
            "updatedDate",
            "clientId",
            "inCount",
            "inSum",
            "outCount",
            "outSum",
            "transCount",
            "transSum",
        ]

    def get_inCount(self, instance):
        return (
            Transaction.objects.filter(transactionTypeId=1)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .count()
        )

    def get_outCount(self, instance):
        return (
            Transaction.objects.filter(transactionTypeId=2)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .count()
        )

    def get_inSum(self, instance):
        inValDict = (
            Transaction.objects.filter(transactionTypeId=1)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .aggregate(Sum("amount"))
        )
        if inValDict is not None:
            inVal = inValDict["amount__sum"]
            if inVal is not None:
                return inVal
            else:
                return 0

    def get_outSum(self, instance):
        outValDict = (
            Transaction.objects.filter(transactionTypeId=2)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .aggregate(Sum("amount"))
        )
        if outValDict is not None:
            outVal = outValDict["amount__sum"]
            if outVal is not None:
                return outVal
            else:
                return 0

    def get_transCount(self, instance):
        inValDict = (
            Transaction.objects.filter(transactionTypeId=1)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .count()
        )
        outValDict = (
            Transaction.objects.filter(transactionTypeId=2)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .count()
        )
        if inValDict is not None:
            if outValDict is not None:
                inVal = inValDict
                outVal = outValDict
                total = inVal + outVal
                return total

    def get_transSum(self, instance):
        inValDict = (
            Transaction.objects.filter(transactionTypeId=1)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .aggregate(Sum("amount"))
        )
        outValDict = (
            Transaction.objects.filter(transactionTypeId=2)
            .filter(walletId=instance.clientId.id)
            .order_by("-id")
            .aggregate(Sum("amount"))
        )
        if inValDict is not None:
            if outValDict is not None:
                inVal = inValDict["amount__sum"]
                outVal = outValDict["amount__sum"]
                if inVal is not None:
                    if outVal is not None:
                        total = inVal - outVal
                    else:
                        total = 0
                else:
                    total = 0
            else:
                total = 0
        else:
            total = 0
        return total


# Transaction


class TransactionSerializer(serializers.ModelSerializer):
    transactionType = serializers.SerializerMethodField()

    class Meta:
        model = Transaction
        fields = [
            "id",
            "amount",
            "createdDate",
            "updatedDate",
            "transactionTypeId",
            "walletId",
            "transactionType",
        ]

    def get_transactionType(self, instance):
        return getTransactionType(self, instance)


# Shopping Cart


class ShoppingCartSerializer(serializers.ModelSerializer):
    client = serializers.SerializerMethodField()

    class Meta:
        model = ShoppingCart
        fields = [
            "createdDate",
            "updatedDate",
            "clientId",
            "client",
        ]

    def get_client(self, instance):
        if instance.clientId is not None:
            return getClient(self, instance)


# Purchase Order


class PurchaseOrderSerializer(serializers.ModelSerializer):
    paymentMethod = serializers.SerializerMethodField()
    orderFrom = serializers.SerializerMethodField()
    coupon = serializers.SerializerMethodField()
    client = serializers.SerializerMethodField()
    countSalesOrder = serializers.SerializerMethodField()
    orderCost = serializers.SerializerMethodField()

    class Meta:
        model = PurchaseOrder
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "isCanceled",
            "isRefunded",
            "paymentMethodId",
            "orderFromId",
            "couponId",
            "clientId",
            "paymentMethod",
            "orderFrom",
            "coupon",
            "client",
            "countSalesOrder",
            "orderCost",
        ]

    def get_countSalesOrder(self, instance):
        salesOrderList = SalesOrder.objects.filter(
            shippingItemId__purchaseOrderId=str(instance.id)
        )
        return salesOrderList.__len__()

    def get_paymentMethod(self, instance):
        return getPaymentMethod(self, instance)

    def get_orderFrom(self, instance):
        languageId = getLanguage(self)
        orderFrom = OrderFrom.objects.get(id=str(instance.orderFromId.id))
        return OrderFromSerializer(orderFrom, context={languageKey: languageId}).data

    def get_coupon(self, instance):
        if instance.couponId is not None:
            coupon = Coupon.objects.get(id=str(instance.couponId.id))
            return CouponSerializer(coupon).data

    def get_client(self, instance):
        if instance.clientId is not None:
            client = Client.objects.get(id=str(instance.clientId.id))
            return ClientDisplaySerializer(client).data

    def calculate(self, instance):
        
        subTotal = 0
        sumService = 0
        sumTaxes = 0
        sumPaymentMethod = 0
        sumDelivery = 0
        # total = 0

        # shippingItemList = ShippingItem.objects.filter(purchaseOrderId=instance.id)
        # for current in shippingItemList:
        #     purchaseShippingItemList = PurchaseShippingItem.objects.filter(
        #         shippingItemId=current.id
        #     )

        #     for purchaseShippingItem in purchaseShippingItemList:
        #         quantity = purchaseShippingItem.deliveredQuantity
        #         skuPrice = purchaseShippingItem.skuPrice
        #         serviceCost = ((purchaseShippingItem.skuCostId.serviceCost * skuPrice) / 100)
        #         handlingCost = ((purchaseShippingItem.skuCostId.handlingCost * skuPrice) / 100)
        #         packingCost = ((purchaseShippingItem.skuCostId.packingCost * skuPrice) / 100)
        #         taxCost = ((serviceCost + handlingCost + packingCost + skuPrice) * purchaseShippingItem.skuCostId.taxCost) / 100
        #         transactionFixedCost = purchaseShippingItem.skuCostId.transactionFixedCost
        #         itemCost = serviceCost + handlingCost + packingCost + taxCost + transactionFixedCost + skuPrice
        #         transactionFeeCost =(( itemCost + skuPrice + serviceCost + handlingCost + packingCost + taxCost + transactionFixedCost ) * purchaseShippingItem.skuCostId.transactionFeeCost )/ 100
        #         overall = (itemCost + transactionFeeCost) * quantity

        #         sumService = (sumService + serviceCost + handlingCost + packingCost) * quantity
        #         sumTaxes = (sumTaxes + taxCost) * quantity
        #         sumPaymentMethod = (sumPaymentMethod + transactionFeeCost) * quantity

        #         subTotal = subTotal + overall

        #     if current.shippingCostId is not None:
        #         selectedShippingCost = ShippingCost.objects.get(
        #             id=str(current.shippingCostId.id)
        #         )
        #         if selectedShippingCost is not None:
        #             sumDelivery = sumDelivery + selectedShippingCost.price

        # total = total + subTotal + sumDelivery

        # if instance.couponId is not None:
        #     self.total = self.total - instance.couponId.discount
        
        return subTotal,sumService, sumTaxes, sumPaymentMethod, sumDelivery

    def get_orderCost(self, instance):
        subTotal,sumService, sumTaxes, sumPaymentMethod, sumDelivery = self.calculate(instance)
        return {
            "subTotal":subTotal,
            'sumService':sumService,
            'sumTaxes':sumTaxes,
            'sumPaymentMethod':sumPaymentMethod,
            'sumDelivery':sumDelivery,
            }

# Supplier


class SupplierSerializer(serializers.ModelSerializer):
    phoneList = serializers.SerializerMethodField()
    creditCardList = serializers.SerializerMethodField()
    documentList = serializers.SerializerMethodField()
    selectedLanguage = serializers.SerializerMethodField()
    currentSubscription = serializers.SerializerMethodField()

    class Meta:
        model = Supplier
        fields = [
            "id",
            "name",
            "email",
            "password",
            "isVerified",
            "createdDate",
            "updatedDate",
            "selectedLanguageId",
            "isFreeSubscriptionUsed",
            "selectedLanguage",
            "phoneList",
            "creditCardList",
            "documentList",
            "currentSubscription",
        ]

    def get_selectedLanguage(self, instance):
        selectedLanguage = Language.objects.get(id=str(instance.selectedLanguageId.id))
        return LanguageSerializer(selectedLanguage).data

    def get_phoneList(self, instance):
        phoneList = SupplierPhone.objects.filter(supplierId=str(instance.id))
        return SupplierPhoneSerializer(phoneList, many=True).data

    def get_creditCardList(self, instance):
        creditCardList = SupplierCreditCard.objects.filter(supplierId=str(instance.id))
        return SupplierCreditCardSerializer(creditCardList, many=True).data

    def get_documentList(self, instance):
        documentList = SupplierDocument.objects.filter(supplierId=str(instance.id))
        return SupplierDocumentSerializer(documentList, many=True).data

    def get_currentSubscription(self, instance):
        statusList = SubscriptionStatus.objects.filter(keyName="active")
        if statusList.__len__() > 0:
            currentSubscriptionList = Subscription.objects.filter(
                subscriptionStatusId=statusList[0].id
            ).filter(supplierId=instance.id)
            if currentSubscriptionList.__len__() > 0:
                languageId = getLanguage(self)
                isDashboard = getIsDashboard(self)
                return SubscriptionSerializer(
                    currentSubscriptionList[0],
                    context={languageKey: languageId, "isDashboard": isDashboard},
                ).data


class SupplierDisplaySerializer(serializers.ModelSerializer):
    class Meta:
        model = Supplier
        fields = [
            "id",
            "name",
            "isVerified",
        ]


# Supplier Phone


class SupplierPhoneSerializer(serializers.ModelSerializer):
    class Meta:
        model = SupplierPhone
        fields = [
            "id",
            "phone",
            "createdDate",
            "updatedDate",
            "supplierId",
        ]


# Supplier Credit Card


class SupplierCreditCardSerializer(serializers.ModelSerializer):
    class Meta:
        model = SupplierCreditCard
        fields = [
            "id",
            "holder",
            "number",
            "expireYear",
            "expireMonth",
            "createdDate",
            "updatedDate",
            "supplierId",
        ]


# Supplier Document


class SupplierDocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = SupplierDocument
        fields = [
            "id",
            "fileName",
            "contentType",
            "fileDocument",
            "createdDate",
            "updatedDate",
            "supplierId",
        ]


# Subscription


class SubscriptionSerializer(serializers.ModelSerializer):
    subscriptionType = serializers.SerializerMethodField()
    subscriptionStatus = serializers.SerializerMethodField()

    class Meta:
        model = Subscription
        fields = [
            "id",
            "price",
            "discount",
            "serviceCost",
            "startDate",
            "endDate",
            "createdDate",
            "updatedDate",
            "supplierId",
            "subscriptionTypeId",
            "subscriptionStatusId",
            "subscriptionType",
            "subscriptionStatus",
        ]

    def get_subscriptionType(self, instance):
        return getSubscriptionType(self, instance)

    def get_subscriptionStatus(self, instance):
        return getSubscriptionStatus(self, instance)


# Delivery Man


class DeliveryManSerializer(serializers.ModelSerializer):
    selectedLanguage = serializers.SerializerMethodField()
    phoneList = serializers.SerializerMethodField()

    class Meta:
        model = DeliveryMan
        fields = [
            "id",
            "name",
            "email",
            "password",
            "createdDate",
            "updatedDate",
            "selectedLanguageId",
            "selectedLanguage",
            "phoneList",
        ]

    def get_selectedLanguage(self, instance):
        selectedLanguage = Language.objects.get(id=str(instance.selectedLanguageId.id))
        return LanguageSerializer(selectedLanguage).data

    def get_phoneList(self, instance):
        phoneList = DeliveryManPhone.objects.filter(deliveryManId=str(instance.id))
        return DeliveryManPhoneSerializer(phoneList, many=True).data


class DeliveryManDisplaySerializer(serializers.ModelSerializer):
    class Meta:
        model = DeliveryMan
        fields = [
            "id",
            "name",
        ]


# Delivery Man Phone


class DeliveryManPhoneSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeliveryManPhone
        fields = [
            "id",
            "phone",
            "createdDate",
            "updatedDate",
            "deliveryManId",
        ]


# Shipping Item


class ShippingItemSerializer(serializers.ModelSerializer):
    isSalesOrderCreated = serializers.SerializerMethodField()
    isCanceled = serializers.SerializerMethodField()
    shippingCost = serializers.SerializerMethodField()
    shippingAddress = serializers.SerializerMethodField()
    purchaseShippingItemList = serializers.SerializerMethodField()

    class Meta:
        model = ShippingItem
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "shippingCostId",
            "purchaseOrderId",
            "isSalesOrderCreated",
            "isCanceled",
            "isValidAndPaid",
            "shippingCost",
            "shippingAddress",
            "purchaseShippingItemList",
        ]

    def get_isSalesOrderCreated(self, instance):
        if SalesOrder.objects.filter(shippingItemId=str(instance.id)).exists():
            return True
        else:
            return False

    def get_isCanceled(self, instance):
        return instance.purchaseOrderId.isCanceled

    def get_shippingCost(self, instance):
        if instance.shippingCostId is not None:
            if ShippingCost.objects.filter(
                id=str(instance.shippingCostId.id)
            ).exists():
                languageId = getLanguage(self)
                shippingCost = ShippingCost.objects.get(
                    id=str(instance.shippingCostId.id)
                )
                return ShippingCostSerializer(
                    shippingCost, context={languageKey: languageId}
                ).data

    def get_shippingAddress(self, instance):
        if ShippingAddress.objects.filter(shippingItemId=str(instance.id)).exists():
            languageId = getLanguage(self)
            shippingAddress = ShippingAddress.objects.get(
                shippingItemId=str(instance.id)
            )
            return ShippingAddressSerializer(
                shippingAddress,
                context={
                    languageKey: languageId,
                },
            ).data

    def get_purchaseShippingItemList(self, instance):
        isShowShippingItemDetail = getIsShowShippingItemDetail(self)
        if isShowShippingItemDetail is not None:
            if int(isShowShippingItemDetail) == 1:
                clientId = getClientId(self)
                languageId = getLanguage(self)
                isDashboard = getIsDashboard(self)
                isShowItem = getIsShowItem(self)
                isShowRequestReturnDetail = getIsShowRequestReturnDetail(self)
                purchaseShippingItem = PurchaseShippingItem.objects.filter(
                    shippingItemId=instance.id
                )
                return PurchaseShippingItemSerializer(
                    purchaseShippingItem,
                    many=True,
                    context={
                        "clientId": clientId,
                        languageKey: languageId,
                        "isDashboard": isDashboard,
                        "isShowItem": isShowItem,
                        "isShowRequestReturnDetail": isShowRequestReturnDetail,
                    },
                ).data


# Shipping Address

class ShippingAddressSerializer(serializers.ModelSerializer):
    country = serializers.SerializerMethodField()
    state = serializers.SerializerMethodField()
    city = serializers.SerializerMethodField()
    trackList = serializers.SerializerMethodField()

    class Meta:
        model = ShippingAddress
        fields = [
            "shippingItemId",
            "trackNumber",
            "address1",
            "address2",
            "zipCode",
            "createdDate",
            "updatedDate",
            "countryId",
            "stateId",
            "cityId",
            "country",
            "state",
            "city",
            "trackList",
        ]

    def get_country(self, instance):
        return getCountry(self, instance)

    def get_state(self, instance):
        return getState(self, instance)
    
    def get_city(self, instance):
        return getCity(self, instance)

    def get_trackList(self, instance):
        languageId = getLanguage(self)
        trackList = Track.objects.filter(
            shippingAddressId=instance.shippingItemId.id
        ).order_by("-id")
        return TrackSerializer(
            trackList, many=True, context={languageKey: languageId}
        ).data


# Track


class TrackSerializer(serializers.ModelSerializer):
    trackStatus = serializers.SerializerMethodField()

    class Meta:
        model = Track
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "shippingAddressId",
            "trackStatusId",
            "trackStatus",
        ]

    def get_trackStatus(self, instance):
        languageId = getLanguage(self)
        trackStatus = TrackStatus.objects.get(id=str(instance.trackStatusId.id))
        return TrackStatusSerializer(
            trackStatus, context={languageKey: languageId}
        ).data


# Sales Order


class SalesOrderSerializer(serializers.ModelSerializer):
    shippingItem = serializers.SerializerMethodField()
    supplier = serializers.SerializerMethodField()
    salesOrderItemList = serializers.SerializerMethodField()

    class Meta:
        model = SalesOrder
        fields = [
            "shippingItemId",
            "createdDate",
            "updatedDate",
            "isConfirmed",
            "supplierId",
            "shippingItem",
            "supplier",
            "salesOrderItemList",
        ]

    def get_shippingItem(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if int(isDashboard) == 1:
                languageId = getLanguage(self)
                isShowShippingItemDetail = getIsShowShippingItemDetail(self)
                shippingItem = ShippingItem.objects.get(
                    id=str(instance.shippingItemId.id)
                )
                return ShippingItemSerializer(
                    shippingItem,
                    context={
                        languageKey: languageId,
                        "isDashboard": isDashboard,
                        "isShowShippingItemDetail": isShowShippingItemDetail,
                    },
                ).data

    def get_supplier(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if int(isDashboard) == 1:
                return getSupplierInfo(self, instance)

    def get_salesOrderItemList(self, instance):
        isShowItem = getIsShowItem(self)
        languageId = getLanguage(self)
        salesOrderItem = SalesOrderItem.objects.filter(
            salesOrderId=instance.shippingItemId.id
        )
        return SalesOrderItemSerializer(
            salesOrderItem,
            many=True,
            context={languageKey: languageId, "isShowItem": isShowItem},
        ).data


# Item


class ItemKeyNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = [
            "id",
            "keyName",
        ]


class ItemBasicSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()

    class Meta:
        model = Item
        fields = [
            "id",
            "name",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        itemLanguageList = ItemLanguage.objects.filter(itemId=str(instance.id)).filter(
            languageId=languageId
        )
        if itemLanguageList.__len__() > 0:
            return itemLanguageList[0].name


class ItemSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()
    description = serializers.SerializerMethodField()
    department = serializers.SerializerMethodField()
    brand = serializers.SerializerMethodField()
    supplier = serializers.SerializerMethodField()
    newArrival = serializers.SerializerMethodField()
    skuList = serializers.SerializerMethodField()
    featureBulletList = serializers.SerializerMethodField()
    rate = serializers.SerializerMethodField()
    amount = serializers.SerializerMethodField()
    isFavoriteWithClient = serializers.SerializerMethodField()

    class Meta:
        model = Item
        fields = [
            "id",
            "keyName",
            "isApproved",
            "isTop",
            "isFavorite",
            "isMostDiscount",
            "isMostViewed",
            "isNewArrival",
            "isElectronic",
            "totalViews",
            "createdDate",
            "updatedDate",
            "departmentId",
            "brandId",
            "supplierId",
            "newArrivalId",
            "name",
            "languageList",
            "description",
            "department",
            "brand",
            "supplier",
            "newArrival",
            "skuList",
            "featureBulletList",
            "rate",
            "isFavoriteWithClient",
            "amount",
        ]

    def get_isFavoriteWithClient(self, instance):
        return getIsFavoriteWithCurrentClient(self, instance)

    def get_amount(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                count = SKU.objects.filter(itemId=instance.id).aggregate(
                    sum_amount=Sum("amount")
                )
                return count["sum_amount"]
        return 0

    def get_skuList(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        isMultipleSKU = getIsMultipleSKU(self)
        isShowItem = getIsShowItem(self)
        maxPrice = 0
        minPrice = 0
        selectedSKUList = []
        if isMultipleSKU is not None:
            if int(isMultipleSKU) == 1:
                selectedSKUList = SKU.objects.filter(itemId=instance.id).order_by(
                    "-amount"
                )
                return SKUSerializer(
                    selectedSKUList,
                    context={
                        languageKey: languageId,
                        "isDashboard": isDashboard,
                        "isShowItem": isShowItem,
                    },
                    many=True,
                ).data

            else:
                isSelectedRange = False

                if self.context.__contains__("request"):
                    minPrice = self.context["request"].query_params.get(
                        "min_price", None
                    )
                    maxPrice = self.context["request"].query_params.get(
                        "max_price", None
                    )

                if minPrice is not None and maxPrice is not None:
                    if float(minPrice) > 0 and float(maxPrice) > 0:
                        isSelectedRange = True
                        selectedSKUList = (
                            SKU.objects.filter(itemId=instance.id)
                            .filter(price__gte=minPrice)
                            .filter(price__lte=maxPrice)
                        )

                elif minPrice is not None:
                    if float(minPrice) > 0:
                        isSelectedRange = True
                        selectedSKUList = SKU.objects.filter(itemId=instance.id).filter(
                            price__gte=minPrice
                        )

                elif maxPrice is not None:
                    if float(maxPrice) > 0:
                        isSelectedRange = True
                        selectedSKUList = SKU.objects.filter(itemId=instance.id).filter(
                            price__lte=maxPrice
                        )

                else:
                    isSelectedRange = False

                if isSelectedRange == False:
                    selectedSKUList = SKU.objects.filter(itemId=instance.id).order_by(
                        "-amount"
                    )

                if selectedSKUList.__len__() > 0:
                    tempList = []
                    tempList.append(selectedSKUList[0])
                    return SKUSerializer(
                        tempList,
                        context={
                            languageKey: languageId,
                            "isDashboard": isDashboard,
                            "isShowItem": isShowItem,
                        },
                        many=True,
                    ).data
                else:
                    return []
        else:
            return []

    def get_rate(self, instance):
        totalRate = ClientItemRateReview.objects.filter(
            itemId=str(instance.id)
        ).aggregate(Sum("rate"))

        count = ClientItemRateReview.objects.filter(itemId=str(instance.id)).count()
        
        if totalRate["rate__sum"] is not None:
            return totalRate["rate__sum"] / count
        else:
            return 0

    def get_department(self, instance):
        return getDepartment(self, instance)

    def get_brand(self, instance):
        languageId = getLanguage(self)
        brand = Brand.objects.get(id=str(instance.brandId.id))
        return BrandDisplaySerializer(brand, context={languageKey: languageId}).data

    def get_supplier(self, instance):
        return getSupplierInfo(self, instance)

    def get_newArrival(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        newArrival = NewArrival.objects.get(id=str(instance.newArrivalId.id))
        return NewArrivalDisplaySerializer(
            newArrival, context={languageKey: languageId, "isDashboard": isDashboard}
        ).data

    def get_featureBulletList(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        isShowFeatureBullet = getIsShowFeatureBullet(self)
        if isShowFeatureBullet is not None:
            if int(isShowFeatureBullet) == 1:
                featureBulletList = FeatureBullet.objects.filter(
                    itemId=str(instance.id)
                )
                return FeatureBulletSerializer(
                    featureBulletList,
                    context={languageKey: languageId, "isDashboard": isDashboard},
                    many=True,
                ).data
            return []
        return []

    def get_name(self, instance):
        languageId = getLanguage(self)
        itemLanguageList = ItemLanguage.objects.filter(itemId=str(instance.id)).filter(
            languageId=languageId
        )
        if itemLanguageList.__len__() > 0:
            return itemLanguageList[0].name

    def get_description(self, instance):
        languageId = getLanguage(self)
        itemLanguageList = ItemLanguage.objects.filter(itemId=str(instance.id)).filter(
            languageId=languageId
        )
        if itemLanguageList.__len__() > 0:
            return itemLanguageList[0].description

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                itemLanguageList = ItemLanguage.objects.filter(itemId=str(instance.id))
                if itemLanguageList.__len__() > 0:
                    return ItemLanguageSerializer(itemLanguageList, many=True).data


class ItemLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemLanguage
        fields = ["id", "name", "description", "itemId", languageKey,]


# Feature Bullet


class FeatureBulletSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = FeatureBullet
        fields = [
            "id",
            "keyName",
            "description",
            "languageList",
            "createdDate",
            "updatedDate",
            "itemId",
        ]

    def get_description(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            featureBullerLanguageList = FeatureBulletLanguage.objects.filter(
                featureBulletId=str(instance.id)
            ).filter(languageId=languageId)
            if featureBullerLanguageList.__len__() > 0:
                return featureBullerLanguageList[0].description

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                featureBullerLanguageList = FeatureBulletLanguage.objects.filter(
                    featureBulletId=str(instance.id)
                )
                if featureBullerLanguageList.__len__() > 0:
                    return FeatureBulletLanguageSerializer(
                        featureBullerLanguageList, many=True
                    ).data


class FeatureBulletLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = FeatureBulletLanguage
        fields = [
            "id",
            "description",
            "featureBulletId",
            languageKey,
        ]


# Eligible


class EligibleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Eligible
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "itemId",
            "eligibleTypeId",
        ]


# SKU
     
class SKUSerializer(serializers.ModelSerializer):
    skuOptionList = serializers.SerializerMethodField()
    skuDescriptionList = serializers.SerializerMethodField()
    item = serializers.SerializerMethodField()
    imageList = serializers.SerializerMethodField()
    skuOldPrice = serializers.SerializerMethodField()
    skuNewPrice = serializers.SerializerMethodField()

    class Meta:
        model = SKU
        fields = [
            "id",
            "keyName",
            "name",
            "price",
            "discount",
            "amount",
            "isTop",
            "isFavorite",
            "isMostDiscount",
            "isMostViewed",
            "isNewArrival",
            "createdDate",
            "updatedDate",
            "itemId",
            "skuOldPrice",
            "skuNewPrice",
            "skuOptionList",
            "skuDescriptionList",
            "item",
            "imageList",
        ]

    def get_skuOptionList(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        skuOptionList = SKUOption.objects.filter(skuId=instance.id)
        return SKUOptionSerializer(
            skuOptionList,
            context={languageKey: languageId, "isDashboard": isDashboard},
            many=True,
        ).data

    def get_skuDescriptionList(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                skuDescriptionList = SKUDescription.objects.filter(skuId=instance.id)
                return SKUDescriptionSerializer(
                    skuDescriptionList,
                    context={languageKey: languageId, "isDashboard": isDashboard},
                    many=True,
                ).data

    def get_item(self, instance):
        isShowItem = getIsShowItem(self)
        if isShowItem is not None:
            if int(isShowItem) == 1:
                clientId = getClientId(self)
                languageId = getLanguage(self)
                isDashboard = getIsDashboard(self)

                item = Item.objects.get(id=str(instance.itemId.id))
                return ItemDisplaySerializer(
                    item,
                    context={
                        "clientId": clientId,
                        languageKey: languageId,
                        "isDashboard": isDashboard,
                    },
                ).data
    
    def get_imageList(self,instance):
        skuImageList = SKUImage.objects.filter(skuId = instance.id)
        return SKUImageSerializer(skuImageList,many=True).data
        #return []

    def getSKUCost(self):
        skuCostList = SKUCost.objects.filter(isEnabled=True)
        skuCost = None
        if skuCostList.__len__() > 0:
            skuCost = skuCostList[0]
        return skuCost
    
    def get_skuOldPrice(self,instance):
        skuCost = self.getSKUCost()
        if skuCost is not None:
            oldPrice,skuCostId = calculatePrice(instance.price,skuCost)
            if oldPrice is not None and skuCostId is not None:
                oldPrice = oldPrice + ((oldPrice * instance.discount)/100)
                skuOldPrice = {}
                skuOldPrice["price"] = math.ceil(oldPrice)
                skuOldPrice["skuCostId"] = skuCostId
                return skuOldPrice
        return None
         
    def get_skuNewPrice(self,instance):
        skuCost = self.getSKUCost()
        if skuCost is not None:
            newPrice,skuCostId = calculatePrice(instance.price,skuCost)
            if newPrice is not None and skuCostId is not None:
                skuNewPrice = {}
                skuNewPrice["price"] = math.ceil(newPrice)
                skuNewPrice["skuCostId"] = skuCostId
                return skuNewPrice
        return None
        

class SKUImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUImage
        fields = [
            "id",
            "keyName",
            "isDownloaded",
            "fileName",
            "extension",
            "source",
            "image",
            "skuId",
        ]

# SKU Option


class SKUOptionSerializer(serializers.ModelSerializer):
    title = serializers.SerializerMethodField()
    value = serializers.SerializerMethodField()
    colorName = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = SKUOption
        fields = [
            "id",
            "keyName",
            "isColor",
            "title",
            "value",
            "colorName",
            "languageList",
            "createdDate",
            "updatedDate",
            "skuId",
        ]

    def get_title(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            skuOptionLanguageList = SKUOptionLanguage.objects.filter(
                skuOptionId=str(instance.id)
            ).filter(languageId=languageId)
            if skuOptionLanguageList.__len__() > 0:
                return skuOptionLanguageList[0].title

    def get_value(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            skuOptionLanguageList = SKUOptionLanguage.objects.filter(
                skuOptionId=str(instance.id)
            ).filter(languageId=languageId)
            if skuOptionLanguageList.__len__() > 0:
                return skuOptionLanguageList[0].value

    def get_colorName(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            skuOptionLanguageList = SKUOptionLanguage.objects.filter(
                skuOptionId=str(instance.id)
            ).filter(languageId=languageId)
            if skuOptionLanguageList.__len__() > 0:
                return skuOptionLanguageList[0].colorName

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                skuOptionLanguageList = SKUOptionLanguage.objects.filter(
                    skuOptionId=str(instance.id)
                )
                if skuOptionLanguageList.__len__() > 0:
                    return SKUOptionLanguageSerializer(
                        skuOptionLanguageList, many=True
                    ).data


class SKUOptionLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUOptionLanguage
        fields = [
            "id",
            "title",
            "value",
            "colorName",
            "skuOptionId",
            languageKey,
        ]


# SKU Description


class SKUDescriptionSerializer(serializers.ModelSerializer):
    title = serializers.SerializerMethodField()
    value = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = SKUDescription
        fields = [
            "id",
            "keyName",
            "isColor",
            "title",
            "value",
            "languageList",
            "createdDate",
            "updatedDate",
            "skuId",
        ]

    def get_title(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            skuDescriptionLanguageList = SKUDescriptionLanguage.objects.filter(
                skuDescriptionId=str(instance.id)
            ).filter(languageId=languageId)
            if skuDescriptionLanguageList.__len__() > 0:
                return skuDescriptionLanguageList[0].title

    def get_value(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            skuDescriptionLanguageList = SKUDescriptionLanguage.objects.filter(
                skuDescriptionId=str(instance.id)
            ).filter(languageId=languageId)
            if skuDescriptionLanguageList.__len__() > 0:
                return skuDescriptionLanguageList[0].value

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                skuDescriptionLanguageList = SKUDescriptionLanguage.objects.filter(
                    skuDescriptionId=str(instance.id)
                )
                if skuDescriptionLanguageList.__len__() > 0:
                    return SKUDescriptionLanguageSerializer(
                        skuDescriptionLanguageList, many=True
                    ).data


class SKUDescriptionLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUDescriptionLanguage
        fields = [
            "id",
            "title",
            "value",
            "colorName",
            "skuDescriptionId",
            languageKey,
        ]


# Item Subscription


class ItemSubscriptionSerializer(serializers.ModelSerializer):
    subscriptionType = serializers.SerializerMethodField()
    subscriptionStatus = serializers.SerializerMethodField()

    class Meta:
        model = ItemSubscription
        fields = [
            "id",
            "price",
            "discount",
            "serviceCost",
            "startDate",
            "endDate",
            "createdDate",
            "updatedDate",
            "itemId",
            "subscriptionTypeId",
            "subscriptionStatusId",
            "subscriptionType",
            "subscriptionStatus",
        ]

    def get_subscriptionType(self, instance):
        return getSubscriptionType(self, instance)

    def get_subscriptionStatus(self, instance):
        return getSubscriptionStatus(self, instance)


# Shopping Cart Item


class ShoppingCartItemSerializer(serializers.ModelSerializer):
    sku = serializers.SerializerMethodField()

    class Meta:
        model = ShoppingCartItem
        fields = [
            "id",
            "quantity",
            "createdDate",
            "updatedDate",
            "shoppingCartId",
            "skuId",
            "sku",
        ]

    def get_sku(self, instance):
        return getSKU(self, instance)


# Purchase Shipping Item

class PurchaseShippingItemSerializer(serializers.ModelSerializer):
    totalPrice = serializers.SerializerMethodField()
    sku = serializers.SerializerMethodField()
    skuCost = serializers.SerializerMethodField()
    canRequestReturnAgain = serializers.SerializerMethodField()
    requestReturnList = serializers.SerializerMethodField()

    class Meta:
        model = PurchaseShippingItem
        fields = [
            "id",
            "totalPrice",
            "skuPrice",
            "skuDiscount",
            "deliveredQuantity",
            "returnedQuantity",
            "canceledQuantity",
            "createdDate",
            "updatedDate",
            "skuCostId",
            "skuId",
            "shippingItemId",
            "sku",
            "skuCost",
            "canRequestReturnAgain",
            "requestReturnList",
        ]

    def get_sku(self, instance):
        return getSKU(self, instance)

    def get_skuCost(self, instance):
        skuCost = SKUCost.objects.get(id=str(instance.skuCostId.id))
        if skuCost is not None:
            return SKUCostSerializer(skuCost).data
        
    def get_totalPrice(self,instance):
        price,skuCostId = calculatePrice(instance.skuPrice,instance.skuCostId)
        return math.ceil(price) * instance.deliveredQuantity

    def get_requestReturnList(self, instance):
        isShowRequestReturnDetail = getIsShowRequestReturnDetail(self)
        if isShowRequestReturnDetail is not None:
            if int(isShowRequestReturnDetail) == 1:
                languageId = getLanguage(self)
                isDashboard = getIsDashboard(self)
                requestReturn = RequestReturn.objects.filter(
                    purchaseShippingItemId=instance.id
                )
                return RequestReturnSerializer(
                    requestReturn,
                    many=True,
                    context={languageKey: languageId, "isDashboard": isDashboard},
                ).data

    def get_canRequestReturnAgain(self, instance):
        if instance.deliveredQuantity > 0:
            data = RequestReturn.objects.filter(purchaseShippingItemId=instance.id)
            if data.__len__() > 0:
                sum = 0
                for d in data:
                    sum += d.requestedQuantity
                if instance.deliveredQuantity > 0:
                    diff = instance.deliveredQuantity - sum
                    if diff > 0:
                        return True
                    if diff == 0:
                        return False
                    else:
                        return False
                else:
                    return False
            else:
                return True
        else:
            return False


# Request Return


class RequestReturnSerializer(serializers.ModelSerializer):
    #returnCost = serializers.SerializerMethodField()
    returnStatus = serializers.SerializerMethodField()

    class Meta:
        model = RequestReturn
        fields = [
            "id",
            "headLine",
            "requestedQuantity",
            "issue",
            "note",
            "createdDate",
            "updatedDate",
            #"returnCostId",
            "returnStatusId",
            "purchaseShippingItemId",
            "returnStatus",
            #"returnCost",
        ]

    def get_returnCost(self, instance):
        pass
        # return getReturnCost(self, instance)

    def get_returnStatus(self, instance):
        return getReturnStatus(self, instance)


class RequestReturnSerializerDetail(serializers.ModelSerializer):
    #returnCost = serializers.SerializerMethodField()
    returnStatus = serializers.SerializerMethodField()
    purchaseShippingItem = serializers.SerializerMethodField()

    class Meta:
        model = RequestReturn
        fields = [
            "id",
            "headLine",
            "requestedQuantity",
            "issue",
            "note",
            "createdDate",
            "updatedDate",
            "returnCostId",
            "returnStatusId",
            "purchaseShippingItemId",
            "returnStatus",
            #"returnCost",
            "purchaseShippingItem",
        ]

    def get_returnCost(self, instance):
        pass
        #return getReturnCost(self, instance)

    def get_returnStatus(self, instance):
        return getReturnStatus(self, instance)

    def get_purchaseShippingItem(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        isShowItem = getIsShowItem(self)
        purchaseShippingItem = PurchaseShippingItem.objects.get(
            id=str(instance.purchaseShippingItemId.id)
        )
        return PurchaseShippingItemSerializer(
            purchaseShippingItem,
            context={
                languageKey: languageId,
                "isDashboard": isDashboard,
                "isShowItem": isShowItem,
            },
        ).data


# Sales Order Item


class SalesOrderItemSerializer(serializers.ModelSerializer):
    sku = serializers.SerializerMethodField()

    class Meta:
        model = SalesOrderItem
        fields = [
            "id",
            "quantity",
            "price",
            "createdDate",
            "updatedDate",
            "skuId",
            "salesOrderId",
            "sku",
        ]

    def get_sku(self, instance):
        return getSKU(self, instance)


# Favortie


class FavoriteSerializer(serializers.ModelSerializer):
    item = serializers.SerializerMethodField()

    class Meta:
        model = Favorite
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "itemId",
            "clientId",
            "item",
        ]

    def get_item(self, instance):
        clientId = getClientId(self)
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        isMultipleSKU = getIsMultipleSKU(self)
        item = Item.objects.get(id=str(instance.itemId.id))
        return ItemSerializer(
            item,
            context={
                "clientId": clientId,
                languageKey: languageId,
                "isDashboard": isDashboard,
                "isMultipleSKU": isMultipleSKU,
            },
        ).data


# Client Item Rate Review


class ClientItemRateReviewSerializer(serializers.ModelSerializer):
    client = serializers.SerializerMethodField()

    class Meta:
        model = ClientItemRateReview
        fields = [
            "id",
            "headLine",
            "rate",
            "comment",
            "createdDate",
            "updatedDate",
            "itemId",
            "clientId",
            "client",
        ]

    def get_client(self, instance):
        return getClient(self, instance)


# Client Supplier Rate Review


class ClientSupplierRateReviewSerializer(serializers.ModelSerializer):
    client = serializers.SerializerMethodField()

    class Meta:
        model = ClientSupplierRateReview
        fields = [
            "id",
            "headLine",
            "rate",
            "comment",
            "createdDate",
            "updatedDate",
            "supplierId",
            "clientId",
            "client",
        ]

    def get_client(self, instance):
        return getClient(self, instance)


# Feedback


class FeedbackSerializer(serializers.ModelSerializer):
    client = serializers.SerializerMethodField()

    class Meta:
        model = Feedback
        fields = [
            "id",
            "headLine",
            "rate",
            "comment",
            "createdDate",
            "updatedDate",
            "clientId",
            "client",
        ]

    def get_client(self, instance):
        return getClient(self, instance)


# Request


class RequestSerializer(serializers.ModelSerializer):
    client = serializers.SerializerMethodField()

    class Meta:
        model = Request
        fields = [
            "id",
            "headLine",
            "description",
            "response",
            "isDone",
            "createdDate",
            "updatedDate",
            "clientId",
            "client",
        ]

    def get_client(self, instance):
        return getClient(self, instance)


# Policy Type


class PolicyTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = PolicyType
        fields = [
            "id",
            "name",
            "createdDate",
            "updatedDate",
        ]


# Policy Header


class PolicyHeaderSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()
    descriptionList = serializers.SerializerMethodField()

    class Meta:
        model = PolicyHeader
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "policyTypeId",
            "name",
            "languageList",
            "descriptionList",
        ]

    def get_name(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            policyHeaderLanguageList = PolicyHeaderLanguage.objects.filter(
                policyHeaderId=str(instance.id)
            ).filter(languageId=languageId)
            if policyHeaderLanguageList.__len__() > 0:
                return policyHeaderLanguageList[0].name

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                policyHeaderLanguageList = PolicyHeaderLanguage.objects.filter(
                    policyHeaderId=str(instance.id)
                )
                if policyHeaderLanguageList.__len__() > 0:
                    return PolicyHeaderLanguageSerializer(
                        policyHeaderLanguageList, many=True
                    ).data

    def get_descriptionList(self, instance):
        languageId = getLanguage(self)
        isDashboard = getIsDashboard(self)
        descriptionList = PolicyDescription.objects.filter(policyHeaderId=instance.id)
        return PolicyDescriptionSerializer(
            descriptionList,
            context={languageKey: languageId, "isDashboard": isDashboard},
            many=True,
        ).data


class PolicyHeaderLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PolicyHeaderLanguage
        fields = [
            "id",
            "name",
            "policyHeaderId",
            languageKey,
        ]


# Policy Description


class PolicyDescriptionSerializer(serializers.ModelSerializer):
    description = serializers.SerializerMethodField()
    languageList = serializers.SerializerMethodField()

    class Meta:
        model = PolicyDescription
        fields = [
            "id",
            "createdDate",
            "updatedDate",
            "policyHeaderId",
            "description",
            "languageList",
        ]

    def get_description(self, instance):
        languageId = getLanguage(self)
        if languageId is not None:
            policyDescriptionLanguageList = PolicyDescriptionLanguage.objects.filter(
                policyDescriptionId=str(instance.id)
            ).filter(languageId=languageId)
            if policyDescriptionLanguageList.__len__() > 0:
                return policyDescriptionLanguageList[0].description

    def get_languageList(self, instance):
        isDashboard = getIsDashboard(self)
        if isDashboard is not None:
            if bool(isDashboard) == bool("1"):
                policyDescriptionLanguageList = (
                    PolicyDescriptionLanguage.objects.filter(
                        policyDescriptionId=str(instance.id)
                    )
                )
                if policyDescriptionLanguageList.__len__() > 0:
                    return PolicyDescriptionLanguageSerializer(
                        policyDescriptionLanguageList, many=True
                    ).data


class PolicyDescriptionLanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PolicyDescriptionLanguage
        fields = [
            "id",
            "description",
            "policyDescriptionId",
            languageKey,
        ]


# Payment

class RechargeCostSerializer(serializers.ModelSerializer):
    class Meta:
        model = RechargeCost
        fields = [
            "id",
            "serviceCost",
            "taxCost",
            "transactionFixedCost",
            "transactionFeeCost",
            "isEnabled",
            "createdDate",
            "updatedDate",
        ]

class RechargeSerializer(serializers.ModelSerializer):
    #taxes = serializers.SerializerMethodField()
    paymentMethod = serializers.SerializerMethodField()
    isPaid = serializers.SerializerMethodField()

    sumTaxes = 0
    transactionFees = 0
    total = 0

    class Meta:
        model = Recharge
        fields = [
            "id",
            "subTotal",
            "sessionId",
            "paymentIntentId",
            "description",
            "createdDate",
            "updatedDate",
            #"taxesId",
            "rechargeCostId",
            "paymentMethodId",
            #"taxes",
            "paymentMethod",
            "isPaid",
        ]

    def get_taxes(self, instance):
        pass
        #return getTaxes(self, instance)

    def get_paymentMethod(self, instance):
        return getPaymentMethod(self, instance)

    def get_isPaid(self, instance):
        isCheck = False
        # paymentList = Payment.objects.filter(rechargeId=instance.id).filter(
        #     taxesId=instance.taxesId
        # )
        paymentList = []
        if paymentList.__len__() > 0:
            isCheck = True
        return isCheck

    def to_representation(self, instance):
        ret = super().to_representation(instance)

        self.sumTaxes = 0
        self.transactionFees = 0
        self.total = 0

        # if instance.service > 0:
        #     self.total = instance.subTotal + instance.service
        # else:
        #     self.total = instance.subTotal

        # if instance.taxesId is not None:
        #     currentValue = 0
        #     if instance.service > 0:
        #         currentValue = instance.service
        #     else:
        #         currentValue = self.total

        #     self.sumTaxes = self.sumTaxes + (
        #         (currentValue * instance.taxesId.price) / 100
        #     )
        #     self.total = self.total + self.sumTaxes

        # if instance.paymentMethodId is not None:
        #     if instance.paymentMethodId.isPercentage == True:
        #         preTotal = self.total + instance.paymentMethodId.fixedPrice
        #         preTotal = preTotal / (1 - (instance.paymentMethodId.price / 100))
        #         self.transactionFees = preTotal - self.total
        #     else:
        #         self.transactionFees = (
        #             self.transactionFees + instance.paymentMethodId.price
        #         )

        #     self.total = self.total + self.transactionFees

        ret["sumTaxes"] = self.sumTaxes
        ret["transactionFees"] = self.transactionFees
        ret["total"] = self.total
        return ret


# Payment


class PaymentSerializer(serializers.ModelSerializer):
    transactionType = serializers.SerializerMethodField()

    class Meta:
        model = Payment
        fields = [
            "id",
            "paid",
            "change",
            "total",
            "taxCost",
            "salesOrderCost",
            "deliveryCost",
            "returnCost",
            "rechargeCost",
            "description",
            "descriptionDetail",
            "createdDate",
            "updatedDate",
            "transactionTypeId",
            "purchaseOrderId",
            "subscriptionId",
            "rechargeId",
            "transactionType",
        ]

    def get_transactionType(self, instance):
        return getTransactionType(self, instance)


# Accessory


class AccessorySerializer(serializers.ModelSerializer):
    amount = serializers.SerializerMethodField()

    class Meta:
        model = Accessory
        fields = [
            "id",
            "name",
            "price",
            "description",
            "createdDate",
            "updatedDate",
            "amount",
        ]

    def get_amount(self, instance):
        inTrans = TransactionType.objects.filter(keyName__icontains="InTrans")
        outTrans = TransactionType.objects.filter(keyName__icontains="OutTrans")
        amountInData = (
            AccessoryTransaction.objects.filter(accessoryId=instance.id)
            .filter(transactionTypeId=inTrans[0].id)
            .aggregate(Sum("quantity"))
        )
        amountOutData = (
            AccessoryTransaction.objects.filter(accessoryId=instance.id)
            .filter(transactionTypeId=outTrans[0].id)
            .aggregate(Sum("quantity"))
        )

        amountIn = 0
        amountOut = 0

        if amountInData["quantity__sum"] is not None:
            amountIn = amountInData["quantity__sum"]

        if amountOutData["quantity__sum"] is not None:
            amountOut = amountOutData["quantity__sum"]

        amount = amountIn - amountOut
        return amount


# Accessory Transaction


class AccessoryTransactionSerializer(serializers.ModelSerializer):
    total = serializers.SerializerMethodField()
    transactionType = serializers.SerializerMethodField()

    class Meta:
        model = AccessoryTransaction
        fields = [
            "id",
            "quantity",
            "price",
            "createdDate",
            "updatedDate",
            "transactionTypeId",
            "accessoryId",
            "total",
            "transactionType",
        ]

    def get_total(self, instance):
        return instance.quantity * instance.price

    def get_transactionType(self, instance):
        return getTransactionType(self, instance)


# Employee


class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = [
            "id",
            "fullName",
            "email",
            "password",
            "createdDate",
            "updatedDate",
        ]


class SystemTrafficSerializer(serializers.ModelSerializer):
    class Meta:
        model = SystemTraffic
        fields = [
            "id",
            "country",
            "state",
            "city",
            "latitude",
            "longitude",
            "deviceIP",
            "openFrom",
            "createdDate",
            "updatedDate",
        ]


class ItemDisplaySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()
    supplier = serializers.SerializerMethodField()
    isFavoriteWithClient = serializers.SerializerMethodField()

    class Meta:
        model = Item
        fields = [
            "id",
            "name",
            "isApproved",
            "isTop",
            "isFavorite",
            "isElectronic",
            "totalViews",
            "createdDate",
            "updatedDate",
            "departmentId",
            "brandId",
            "supplierId",
            "newArrivalId",
            "isFavoriteWithClient",
            "supplier",
        ]

    def get_isFavoriteWithClient(self, instance):
        return getIsFavoriteWithCurrentClient(self, instance)

    def get_name(self, instance):
        languageId = getLanguage(self)
        itemLanguageList = ItemLanguage.objects.filter(itemId=str(instance.id)).filter(
            languageId=languageId
        )
        if itemLanguageList.__len__() > 0:
            return itemLanguageList[0].name

    def get_supplier(self, instance):
        return getSupplierInfo(self, instance)
