from django.db import models
from django.db.models import Sum, Count, Q
from django.db.models.functions import Coalesce

from apps.authentication.models import Organization
from apps.authentication.services.service import get_all_org_child
from apps.core.services.filter.search import DynamicSearchService
from apps.product.models import OrganizationQuotaStats, QuotaDistribution, Quota


class QuotaDashboardService:
    """
    dashboard of quota information
    """

    @staticmethod
    def get_dashboard(self, org: Organization, start_date: str = None, end_date: str = None,
                      search_fields: list[str] = None, quota_is_closed: bool = False, query_string: str = None,
                      product_id: int = None,
                      ):

        distribution_number = 0
        base_filter = {}  # filter queries

        # child organizations
        org_child = get_all_org_child(org)
        org_child.append(org)

        if product_id:
            base_filter['quota__product_id'] = product_id

        base_filter['quota__is_closed'] = quota_is_closed

        if org.type.key == 'ADM':
            org_quota_stats = OrganizationQuotaStats.objects.filter(
                stat_type='quota',
                **base_filter
            )
            dist_org_quota_stats = OrganizationQuotaStats.objects.filter(
                stat_type='distribution',
                **base_filter
            )
        else:
            org_quota_stats = OrganizationQuotaStats.objects.filter(
                organization=org,
                **base_filter
            )
            dist_org_quota_stats = OrganizationQuotaStats.objects.filter(
                quota__in=Quota.objects.filter(
                    Q(registerer_organization=org) |
                    Q(assigned_organizations=org)
                ).distinct('id'),
                organization__in=org_child,
                stat_type='distribution',
                **base_filter
            )

        # filter queryset (transactions & items) by date
        if (start_date and end_date) or query_string:
            org_quota_stats = DynamicSearchService(
                queryset=org_quota_stats,
                start=start_date,
                end=end_date,
                date_field="create_date",
                search_fields=search_fields,
                query_string=query_string
            ).apply()

        quota_ids = org_quota_stats.values_list("quota_id", flat=True)
        if org.type.key == 'ADM':
            distribution_number += QuotaDistribution.objects.select_related('quota').filter(
                quota_id__in=quota_ids,
                quota__is_closed=False
            ).count()
        else:
            distribution_number += QuotaDistribution.objects.filter(
                Q(assigner_organization=org),
                quota_id__in=quota_ids,
                quota__is_closed=False
            ).count()

        org_quota_stats = org_quota_stats.aggregate(
            total_quotas=Count("quota", distinct=True),
            total_distributed=Coalesce(Sum("total_distributed", ), 0),
            remaining_amount=Coalesce(Sum("remaining_amount", ), 0),
            inventory_received=Coalesce(Sum("inventory_received", ), 0),
            sold_amount=Coalesce(Sum("sold_amount", ), 0),
            total_amount=Coalesce(Sum("total_amount", ), 0),
            inventory_entry_balance=Coalesce(Sum("inventory_entry_balance", ), 0),
        )

        org_quota_stats.update(
            distribution_number=distribution_number,
            dist_remaining_amount=dist_org_quota_stats.aggregate(
                remaining_amount=Coalesce(Sum("remaining_amount"), 0), )['remaining_amount'] or 0,
        )

        return {
            "quotas_summary": org_quota_stats,
        }

    @staticmethod
    def get_dashboard_by_product(
            self,
            organization: Organization,
            products: dict,
            start_date: str = None, end_date: str = None,
            search_fields: list[str] = None, quota_is_closed: bool = False,
            query_string: str = None
    ):

        stat_by_prod = []
        for prod_name, prod_id in products.items():
            if organization.type.key == 'ADM':
                org_quota_stat = OrganizationQuotaStats.objects.filter(
                    quota__product_id=prod_id,
                    stat_type='quota',
                )
            else:
                org_quota_stat = OrganizationQuotaStats.objects.filter(
                    organization=organization,
                    quota__product_id=prod_id
                )

            # filter queryset (transactions & items) by
            if (start_date and end_date) or query_string:
                org_quota_stats = DynamicSearchService(
                    queryset=org_quota_stat,
                    start=start_date,
                    end=end_date,
                    date_field="create_date",
                    search_fields=search_fields,
                    query_string=query_string
                ).apply()

            product_stat_data = org_quota_stat.aggregate(
                quotas_count=Count('id'),
                total_quotas_weight=Coalesce(models.Sum('total_amount'), 0),
                active_quotas_weight=Coalesce(models.Sum(
                    'total_amount', filter=Q(quota__is_closed=False)
                ), 0),
                closed_quotas_weight=Coalesce(models.Sum(
                    'total_amount', filter=Q(quota__is_closed=True)
                ), 0),
                total_remaining_quotas_weight=Coalesce(models.Sum('remaining_amount'), 0),
                total_distributed=Coalesce(models.Sum('total_distributed'), 0),
                total_warehouse_entry=Coalesce(models.Sum('inventory_received'), 0),
                total_sold=Coalesce(models.Sum('sold_amount'), 0),
            )
            received_distribution_weight = QuotaDistribution.objects.select_related(
                'quota', 'assigned_organization'
            ).filter(
                quota__product_id=prod_id,
                quota__is_closed=False,
                assigned_organization=organization,
            ) if not organization.type.key == 'ADM' else QuotaDistribution.objects.select_related(
                'quota', 'assigned_organization'
            ).filter(
                quota__product_id=prod_id,
                quota__is_closed=False,
            )

            # product total distributed weight from quota
            given_distribution_weight = QuotaDistribution.objects.select_related(
                'quota', 'assigner_organization'
            ).filter(
                quota__product_id=prod_id,
                quota__is_closed=False,
                assigner_organization=organization,
            ) if not organization.type.key == 'ADM' else QuotaDistribution.objects.select_related(
                'quota', 'assigner_organization'
            ).filter(
                quota__product_id=prod_id,
                quota__is_closed=False,
            )

            product_stat_data.update(
                product_name=prod_name,
                product_id=prod_id,
                received_distribution_number=received_distribution_weight.count(),
                received_distribution_weight=received_distribution_weight.aggregate(
                    total_weight=models.Sum('weight')
                )['total_weight'] or 0,

                given_distribution_number=given_distribution_weight.count(),
                given_distribution_weight=given_distribution_weight.aggregate(
                    total_weight=models.Sum('weight')
                )['total_weight'] or 0,
            )

            stat_by_prod.append(product_stat_data)

        return stat_by_prod
