from datetime import datetime

from django.db import transaction
from django.db.models import Q
from rest_framework import status
from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.response import Response

from apps.authentication.services.service import get_all_org_child
from apps.core.api import BaseViewSet
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.core.mixins.soft_delete_mixin import SoftDeleteMixin
from apps.core.pagination import CustomPageNumberPagination
from apps.product import models as product_models
from apps.product.exceptions import QuotaExpiredTimeException
from apps.product.models import OrganizationQuotaStats
from apps.product.services.quota_dashboard_service import QuotaDashboardService
from apps.product.web.api.v1.serializers import quota_distribution_serializers
from apps.product.web.api.v1.serializers import quota_serializers
from apps.product.web.api.v1.viewsets import product_api
from common.helpers import get_organization_by_user
from common.tools import CustomOperations


def trash(queryset, pk):  # noqa
    """ sent object to trash """
    obj = queryset.get(id=pk)
    obj.trash = True
    obj.save()


def delete(queryset, pk):
    """ full delete object """
    obj = queryset.get(id=pk)
    obj.delete()


class QuotaViewSet(BaseViewSet, SoftDeleteMixin, QuotaDashboardService, viewsets.ModelViewSet,
                   DynamicSearchMixin, ):  # noqa
    """ apis for product quota """

    queryset = product_models.Quota.objects.all()
    serializer_class = quota_serializers.QuotaSerializer
    filter_backends = [filters.SearchFilter]
    CustomPageNumberPagination.page_size = 5
    search_fields = [
        "registerer_organization__name",
        "quota_id",
        "product__name",
        "sale_type",
        "sale_unit__unit",
        "group",
        "creator_info",
    ]

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        """ custom create quota """

        # get user relations data like organization
        user_relation = request.user.user_relation.all().first()

        # add user relation to data
        if user_relation.organization:
            request.data['registerer_organization'] = user_relation.organization.id
        else:
            raise APIException("برای این کاربر سازمانی تعریف نشده است")  # noqa

        # create quota
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            quota = serializer.save()
            quota.remaining_weight = quota.quota_weight

            # create incentive plan
            plans_list = []
            if 'incentive_plan_data' in request.data.keys():
                for plan in request.data['incentive_plan_data']:
                    plan.update({'quota': quota.id})
                    incentive_plan = CustomOperations().custom_create(
                        request=request,
                        view=QuotaIncentiveAssignmentViewSet(),
                        data_key='incentive_plan_data',
                        data=plan
                    )
                    plans_list.append(incentive_plan)

            # create product price attributes for quota
            attributes_value_list = []
            if 'price_attributes_data' in request.data.keys():
                for attr in request.data['price_attributes_data']:
                    attr.update({'quota': quota.id})
                    attributes = CustomOperations().custom_create(
                        request=request,
                        view=product_api.AttributeValueViewSet(),
                        data=attr
                    )
                    attributes_value_list.append(attributes)

            # create product broker values for quota
            broker_data_list = []
            if 'broker_data' in request.data.keys():
                for broker in request.data['broker_data']:
                    broker.update({'quota': quota.id})
                    broker_value = CustomOperations().custom_create(
                        request=request,
                        view=QuotaBrokerValueViewSet(),
                        data=broker
                    )
                    broker_data_list.append(broker_value)

            # create livestock allocations to quota
            allocations_list = []
            if 'livestock_allocation_data' in request.data.keys():
                for ls_alloc in request.data['livestock_allocation_data']:
                    ls_alloc.update({'quota': quota.id})
                    allocations = CustomOperations().custom_create(
                        request=request,
                        view=QuotaLiveStockAllocationViewSet(),
                        data=ls_alloc
                    )
                    allocations_list.append(allocations)

            # create livestock age limits for quota
            livestock_age_limits = []
            if 'livestock_age_limitations' in request.data.keys():
                for age_limit in request.data['livestock_age_limitations']:
                    age_limit.update({'quota': quota.id})
                    age_limit_creation_object = CustomOperations().custom_create(
                        request=request,
                        view=QuotaLiveStockAgeLimitation(),
                        data=age_limit
                    )
                    livestock_age_limits.append(age_limit_creation_object)

            # create quota price calculation items for final price types
            price_calculation_items = []
            if 'price_calculation_items' in request.data.keys():
                for price_item in request.data['price_calculation_items']:
                    price_item.update({'quota': quota.id})
                    price_item_creation_object = CustomOperations().custom_create(
                        request=request,
                        view=QuotaPriceCalculationItemsViewSet(),
                        data=price_item
                    )
                    price_calculation_items.append(price_item_creation_object)

            data = {
                'quota': serializer.data,
                'incentive_plan': plans_list,  # noqa
                'attribute_values': attributes_value_list,
                'broker_values': broker_data_list,
                'live_stock_allocations': allocations_list,
                'livestock_age_limitations': livestock_age_limits,
                'price_calculation_items': price_calculation_items
            }

            # call save method to generate id & calculate quota final price
            quota.save(calculate_final_price=True)
            return Response(data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

    @transaction.atomic
    def update(self, request, pk=None, *args, **kwargs):
        # get user relations data like organization
        user_relation = request.user.user_relation.all().first()

        # add user relation to data
        request.data['registerer_organization'] = user_relation.organization.id

        # create quota
        serializer = self.serializer_class(data=request.data, instance=self.get_object(), partial=True)
        if serializer.is_valid():
            quota = serializer.save()

            # create incentive plan
            plans_list = []
            if 'incentive_plan_data' in request.data.keys():

                # remove all incentive assignment relations
                quota.incentive_assignments.all().delete()

                for plan in request.data['incentive_plan_data']:
                    # create new relations
                    plan.update({'quota': quota.id})
                    incentive_plan = CustomOperations().custom_create(
                        request=request,
                        view=QuotaIncentiveAssignmentViewSet(),
                        data_key='incentive_plan_data',
                        data=plan
                    )
                    plans_list.append(incentive_plan)

            # create product price attributes for quota
            attributes_value_list = []  # noqa
            if 'price_attributes_data' in request.data.keys():

                # remove all price attribute relations
                quota.attribute_values.all().delete()

                for attr in request.data['price_attributes_data']:
                    for stat in quota.org_quota_stats.all():
                        # create new relations
                        attr.update({
                            'quota': quota.id,
                            'org_quota_stat': stat.id if stat.stat_type != 'quota' else None
                        })
                        attributes = CustomOperations().custom_create(
                            request=request,
                            view=product_api.AttributeValueViewSet(),
                            data=attr
                        )
                        attributes_value_list.append(attributes)

            # create product broker values for quota
            broker_data_list = []  # noqa
            if 'broker_data' in request.data.keys():

                # remove broker values relations
                quota.broker_values.all().delete()

                for broker in request.data['broker_data']:
                    for stat in quota.org_quota_stats.all():
                        # create new relations
                        broker.update({
                            'quota': quota.id,
                            'org_quota_stat': stat.id if stat.stat_type != 'quota' else None
                        })
                        broker_value = CustomOperations().custom_create(
                            request=request,
                            view=QuotaBrokerValueViewSet(),
                            data=broker
                        )
                        broker_data_list.append(broker_value)

            # create livestock allocations to quota
            allocations_list = []
            if 'livestock_allocation_data' in request.data.keys():

                # remove livestock allocations data relations
                quota.livestock_allocations.all().delete()

                for ls_alloc in request.data['livestock_allocation_data']:
                    # create new relations
                    ls_alloc.update({'quota': quota.id})
                    allocations = CustomOperations().custom_create(
                        request=request,
                        view=QuotaLiveStockAllocationViewSet(),
                        data=ls_alloc
                    )
                    allocations_list.append(allocations)

            # create livestock age limits for quota
            livestock_age_limits = []
            if 'livestock_age_limitations' in request.data.keys():

                # remove live stock age limit relations
                quota.livestock_age_limitations.all().delete()

                for age_limit in request.data['livestock_age_limitations']:
                    # create new relations
                    age_limit.update({'quota': quota.id})
                    age_limit_creation_object = CustomOperations().custom_create(
                        request=request,
                        view=QuotaLiveStockAgeLimitation(),
                        data=age_limit
                    )
                    livestock_age_limits.append(age_limit_creation_object)

            # create quota price calculation items for final price types
            price_calculation_items = []
            if 'price_calculation_items' in request.data.keys():

                # remove live stock age limit relations
                quota.pricing_items.all().delete()

                for price_item in request.data['price_calculation_items']:
                    price_item.update({'quota': quota.id})
                    price_item_creation_object = CustomOperations().custom_create(
                        request=request,
                        view=QuotaPriceCalculationItemsViewSet(),
                        data=price_item
                    )
                    price_calculation_items.append(price_item_creation_object)

            data = {
                'quota': serializer.data,
                'incentive_plan': plans_list,  # noqa
                'attribute_values': attributes_value_list,
                'broker_values': broker_data_list,
                'live_stock_allocations': allocations_list,
                'livestock_age_limitations': livestock_age_limits,
                'price_calculation_items': price_calculation_items
            }

            # call save method to generate id & calculate quota final price
            quota.save(calculate_final_price=True)
            return Response(data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, context={
            "org": get_organization_by_user(request.user)
        })
        return Response(serializer.data)

    @action(
        methods=['patch'],
        detail=True,
        url_path='close',
        url_name='close',
        name='close'
    )
    @transaction.atomic
    def close(self, request, pk=None):
        """ to close quota """
        quota = self.get_object()

        # check quota expired time
        if not quota.is_in_sale_licence_time():
            raise QuotaExpiredTimeException()

        if quota.is_closed:
            raise APIException("این سهمیه قبلا بسته شده است", status.HTTP_400_BAD_REQUEST)  # noqa

        quota.is_closed = True
        quota.closed_at = datetime.now()
        quota.save()

        return Response(status.HTTP_200_OK)

    @action(
        methods=['patch'],
        detail=True,
        url_path='activate',
        url_name='activate',
        name='activate'
    )
    def activate(self, request, pk=None):
        """ to activate quota """

        quota = self.get_object()

        # check quota expired time
        if not quota.is_in_sale_licence_time():
            raise QuotaExpiredTimeException()

        if not quota.is_closed:
            raise APIException("این سهمیه از قبل فعال است", status.HTTP_400_BAD_REQUEST)  # noqa

        quota.is_closed = False
        quota.save()
        return Response(status=status.HTTP_200_OK)

    @action(
        methods=['get'],
        detail=False,
        url_path='quotas_dashboard',
        url_name='quotas_dashboard',
        name='quotas_dashboard'
    )
    def quotas_dashboard(self, request):
        """
        dashboard of all quotas & their information
        """

        search_fields = [
            "quota__registerer_organization__name",
            "quota__quota_id",
            "quota__product__name",
            "quota__sale_type",
            "quota__sale_unit__unit",
            "quota__group",
            "quota__creator_info",
        ]
        query_param = self.request.query_params  # noqa

        # filter by date
        start_date = query_param.get('start') if 'start' in query_param.keys() else None
        end_date = query_param.get('end') if 'end' in query_param.keys() else None
        query_string = query_param.get('search') if 'search' in query_param.keys() else None

        # filter by quota is close or open
        is_closed = True if 'is_closed' in query_param.keys() else False

        quota_dashboard = self.get_dashboard(
            self,
            org=get_organization_by_user(request.user),
            start_date=start_date,
            end_date=end_date,
            search_fields=search_fields,
            quota_is_closed=is_closed,
            query_string=query_string
        )

        return Response(quota_dashboard)

    @action(
        methods=['get'],
        detail=False,
        url_path='quotas_dashboard_by_product',
        url_name='quotas_dashboard_by_product',
        name='quotas_dashboard_by_product'
    )
    def quotas_dashboard_by_product(self, request):
        """
        dashboard of all quotas & their information
        """

        search_fields = [
            "quota__registerer_organization__name",
            "quota__quota_id",
            "quota__product__name",
            "quota__sale_type",
            "quota__sale_unit__unit",
            "quota__group",
            "quota__creator_info",
        ]

        org = get_organization_by_user(request.user)
        query_param = self.request.query_params  # noqa

        # filter by date
        start_date = query_param.get('start') if 'start' in query_param.keys() else None
        end_date = query_param.get('end') if 'end' in query_param.keys() else None
        query_string = query_param.get('search') if 'search' in query_param.keys() else None

        # filter by quota is close or open
        is_closed = True if 'is_closed' in query_param.keys() else False

        # get organization quota stats and get product ids
        org_quota_stat = OrganizationQuotaStats.objects.select_related('organization', 'quota').filter(
            organization=org,
            quota__is_closed=is_closed
        ) if not org.type.key == 'ADM' else OrganizationQuotaStats.objects.select_related('organization', 'quota').all()

        products = {f'{stat.quota.product.name}': stat.quota.product.id for stat in org_quota_stat}

        dashboard_data_by_product = self.get_dashboard_by_product(
            self,
            org,
            products,
            start_date=start_date,
            end_date=end_date,
            search_fields=search_fields,
            quota_is_closed=is_closed,
            query_string=query_string
        )

        return Response(dashboard_data_by_product)

    @action(
        methods=['get'],
        detail=True,
        url_path='org_quota_stats_by_product',
        url_name='org_quota_stats_by_product',
        name='org_quota_stats_by_product'
    )
    def org_quota_stats_by_product(self, request, pk=None):
        """
        list of quotas by product
        """
        org = get_organization_by_user(request.user)
        query_param = self.request.query_params  # noqa

        # filter by date
        start_date = query_param.get('start') if 'start' in query_param.keys() else None
        end_date = query_param.get('end') if 'end' in query_param.keys() else None

        queryset = self.filter_query(
            self.get_queryset(visibility_by_org_scope=True).filter(
                is_closed=False)
        )  # return by search param or all objects

        # paginate queryset
        page = self.paginate_queryset(
            queryset.filter(product_id=pk).order_by('-modify_date')
        )
        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True, context={'org': org})
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=False,
        url_path='active_quotas',
        url_name='active_quotas',
        name='active_quotas'
    )
    @transaction.atomic
    def active_quotas(self, request):
        """ list of organization active quotas """

        org = get_organization_by_user(request.user)

        queryset = self.filter_query(
            self.get_queryset(visibility_by_org_scope=True).filter(
                is_closed=False))  # return by search param or all objects

        # paginate queryset
        page = self.paginate_queryset(
            queryset.filter(
                # Q(assigned_organizations=org) |
                # Q(registerer_organization=org)
            ).order_by('-modify_date').distinct()
        )
        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True, context={'org': org})
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=False,
        url_path='inventory_entered_quotas',
        url_name='inventory_entered_quotas',
        name='inventory_entered_quotas'
    )
    @transaction.atomic
    def active_quotas_by_inventory_entry(self, request):
        """ list of organization active quotas that have inventory entries """

        org = get_organization_by_user(request.user)
        query_param = self.request.query_params  # noqa
        base_query = {}

        # filter by product
        product_id = query_param.get('product_id') if 'product_id' in query_param.keys() else None
        if product_id:
            base_query['product_id'] = product_id

        queryset = self.filter_query(
            self.get_queryset(
                visibility_by_org_scope=True).filter(
                is_closed=False
            ))  # return by search param or all objects

        # paginate queryset
        page = self.paginate_queryset(
            queryset.filter(
                org_quota_stats__inventory_received__gt=0,
                **base_query
            ).order_by('-modify_date').distinct()
        )
        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True, context={'org': org})
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=False,
        url_path='closed_quotas',
        url_name='closed_quotas',
        name='closed_quotas'
    )
    @transaction.atomic
    def closed_quotas(self, request):
        """ list of organization closed quotas """

        queryset = self.filter_query(
            self.get_queryset(visibility_by_org_scope=True).filter(
                is_closed=True))  # return by search param or all objects

        # paginate queryset
        page = self.paginate_queryset(
            queryset.order_by('-modify_date').distinct()
        )
        if page is not None:  # noqa
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

    @action(
        methods=['get'],
        detail=True,
        url_path='distributions_by_quota',
        url_name='distributions_by_quota',
        name='distributions_by_quota'
    )
    def get_distributions_by_quota(self, request, pk=None):
        """ list of distributions by quota """

        my_org = get_organization_by_user(request.user)
        my_org_child_list = get_all_org_child(my_org)
        try:
            quota = self.get_object()
            queryset = self.filter_query(
                quota.distributions_assigned.select_related(
                    "quota",
                    "assigned_organization",
                    "assigner_organization",
                    "parent_distribution",
                ).prefetch_related(
                    "quota__attribute_values",
                    "quota__broker_values",
                    "quota__distributions_assigned",
                ).filter(
                    Q(assigner_organization=my_org) |
                    Q(assigned_organization__in=my_org_child_list)
                ).order_by('-modify_date')
            )  # return by search param or all objects

            # paginate queryset
            page = self.paginate_queryset(
                queryset
            )
            if page is not None:
                serializer = quota_distribution_serializers.QuotaDistributionSerializer(
                    page, many=True, context={'org': my_org}
                )
                return self.get_paginated_response(serializer.data)
        except Exception as e:
            raise APIException("none object", code=403)

    @action(
        methods=['get'],
        detail=True,
        url_path='quotas_information',
        url_name='quotas_information',
        name='quotas_information'
    )
    @transaction.atomic
    def quotas_information_by_product(self, request, pk=None):
        """ get quotas information of a product """

        quotas = self.queryset.select_related('product').filter(
            product_id=pk, is_closed=False
        )

        try:
            quota_serializer = self.serializer_class(quotas, many=True).data
            return Response(quota_serializer, status=status.HTTP_200_OK)
        except APIException as e:
            raise APIException(detail="data error", code=400)

    @action(
        methods=['get'],
        detail=False,
        url_path='quotas_info_by_org',
        url_name='quotas_info_by_org',
        name='quotas_info_by_org'
    )
    def quotas_information_by_organization(self, request):
        """ get quotas information of an organization """

        quotas = self.queryset.filter(
            Q(assigned_organizations=get_organization_by_user(request.user)) |
            Q(registerer_organization=get_organization_by_user(request.user))
        )

        serializer = self.serializer_class(quotas, many=True).data
        return Response(serializer, status=status.HTTP_200_OK)

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaIncentiveAssignmentViewSet(SoftDeleteMixin, viewsets.ModelViewSet):  # noqa
    """ apis for incentive assignment """

    queryset = product_models.QuotaIncentiveAssignment.objects.all()
    serializer_class = quota_serializers.QuotaIncentiveAssignmentSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota incentive assignment to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota incentive assignment object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaBrokerValueViewSet(SoftDeleteMixin, viewsets.ModelViewSet):  # noqa
    """ apis for quota broker value """

    queryset = product_models.QuotaBrokerValue.objects.all()
    serializer_class = quota_serializers.QuotaBrokerValueSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota broker value to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota broker value object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaLiveStockAllocationViewSet(SoftDeleteMixin, viewsets.ModelViewSet):
    """ apis for quota livestock allocation """

    queryset = product_models.QuotaLivestockAllocation.objects.all()
    serializer_class = quota_serializers.QuotaLiveStockAllocationSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota livestock allocation to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota livestock allocation object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaLiveStockAgeLimitation(SoftDeleteMixin, viewsets.ModelViewSet):
    queryset = product_models.QuotaLiveStockAgeLimitation.objects.all()  # noqa
    serializer_class = quota_serializers.QuotaLiveStockAgeLimitationSerializer

    @action(
        methods=['put'],
        detail=True,
        url_path='trash',
        url_name='trash',
        name='trash',
    )
    @transaction.atomic
    def trash(self, request, pk=None):
        """ Sent quota livestock age limitation to trash """
        try:
            trash(self.queryset, pk)
        except APIException as e:
            return Response(e, status.HTTP_204_NO_CONTENT)

    @action(
        methods=['post'],
        detail=True,
        url_name='delete',
        url_path='delete',
        name='delete'
    )
    @transaction.atomic
    def delete(self, request, pk=None):
        """ Full delete of quota livestock age limitation object """
        try:
            delete(self.queryset, pk)
            return Response(status=status.HTTP_200_OK)
        except APIException as e:
            return Response(e, status=status.HTTP_204_NO_CONTENT)


class QuotaPriceCalculationItemsViewSet(viewsets.ModelViewSet):
    queryset = product_models.QuotaPriceCalculationItems.objects.all().select_related('quota', 'pricing_type')
    serializer_class = quota_serializers.QuotaPriceCalculationPriceItemsSerializer


class QuotaFinalPriceTypeViewSet(viewsets.ModelViewSet):
    queryset = product_models.QuotaFinalPriceTypes.objects.all()
    serializer_class = quota_serializers.QuotaFinalPriceTypeSerializer
