import threading
from datetime import datetime

from django.db.models import Sum, Q
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from LiveStock.Jahad.filterset import LiveStockAllocationsFilterSet, CooperativeProductsShareFilterSet
from LiveStock.Jahad.helpers import jahad_warehousing, union_warehousing, cooperative_warehousing
from LiveStock.Jahad.serializers import LiveStockProvinceJahadSerializer, LiveStockRolseProductSerializer, \
    LiveStockAllocationsSerializer, LiveStockProductSerializer, CooperativeProductsShareSerializer
from LiveStock.Rancher.helpers import update_quota_rancher_threading
from LiveStock.Rancher.serializers import RancherSerializer
from LiveStock.Union.serializers import UnionSerializer
from LiveStock.helpers import CustomPagination, build_query
from LiveStock.models import LiveStockProvinceJahad, LiveStockRolseProduct, LiveStockAllocations, Union, Cooperative, \
    Rancher, LiveStockProduct, CooperativeProductsShare
from authentication.models import SystemUserProfile


class LiveStockProvinceJahadViewSet(viewsets.ModelViewSet):
    queryset = LiveStockProvinceJahad.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = LiveStockProvinceJahadSerializer

    def retrieve(self, request, pk=None, *args, **kwargs):
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)

            jahad = user.jahad_user.all()

            serializer = self.serializer_class(jahad[0])
            return Response(serializer.data, status=status.HTTP_200_OK)


class LiveStockRolseProductViewset(viewsets.ModelViewSet):
    queryset = LiveStockRolseProduct.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = LiveStockRolseProductSerializer

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        products = {
            "bran":"سبوس",
            "barley":"جو",
            "soy":"سویا",
            "corn":"ذرت",
            "sheep_concentrate":"کنسانتره گوسفندی",
            "high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
            "medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
            "fattening_calf_concentrate":"کنسانتره گوساله پرواری",
        }
        name =products[request.GET.get('name')]

        product = LiveStockProduct.objects.filter(trash=False, name=name).first()
        if request.GET['role'] == 'LiveStockProvinceJahad':
            products = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
                                                            , parent_product=product).first()
        elif request.GET['role'] == 'Union':
            products = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
                                                            parent_product=product).first()

        else:
            products = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
                                                            parent_product=product).first()
        serializer = self.serializer_class(products)
        return Response(serializer.data, status=status.HTTP_200_OK)


class LiveStockAllocationsViewSet(viewsets.ModelViewSet):
    queryset = LiveStockAllocations.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = LiveStockAllocationsSerializer
    pagination_class = CustomPagination
    filterset_class = LiveStockAllocationsFilterSet

    def create(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        product = LiveStockRolseProduct.objects.get(key=request.data['product_key'])

        allocator = request.data['allocator']
        receiver = request.data['receiver']
        request.data.pop('allocator')
        request.data.pop('receiver')
        request.data.pop('product_key')

        if allocator == 'LiveStockProvinceJahad':
            jahad = LiveStockProvinceJahad.objects.get(user=user, trash=False)
            jahad_roles_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False,parent_product__name=product.parent_product.name,trash=False).first()
            if receiver != 'LiveStockProvinceJahad':
                if request.data['weight'] > jahad_roles_product.total_remain_weight:
                    return Response({"result": "مقدار وارد شده بیشتر از باقی مانده انبار است !"},
                                    status=status.HTTP_403_FORBIDDEN)

        elif allocator == 'Cooperative':
            cooperative = Cooperative.objects.get(user=user, trash=False)
            cooperative_roles_product = LiveStockRolseProduct.objects.get(cooperative=cooperative,parent_product__name=product.parent_product.name, trash=False)
            if receiver != 'Cooperative':

                if request.data[
                    'weight'] + cooperative_roles_product.total_remain_weight > cooperative_roles_product.total_receipt_weight:
                    return Response({"result": "مقدار وارد شده بیشتر از سهمیه دریافتی است !"},
                                    status=status.HTTP_403_FORBIDDEN)



        else:
            union = Union.objects.get(user=user, trash=False)
            union_roles_product = LiveStockRolseProduct.objects.filter(union__isnull=False,parent_product__name=product.parent_product.name, trash=False).first()
            if request.data['weight'] > union_roles_product.total_remain_weight:
                return Response({"result": "مقدار وارد شده بیشتر از باقی مانده انبار است !"},
                                status=status.HTTP_403_FORBIDDEN)
        if receiver == 'LiveStockProvinceJahad':
            pass
        elif receiver == 'Union':
            union = Union.objects.get(key=request.data['buyer_key'], trash=False)
            request.data.pop('buyer_key')

        else:
            if allocator == 'Cooperative':
                pass
            else:
                cooperative = Cooperative.objects.get(key=request.data['buyer_key'], trash=False)
                request.data.pop('buyer_key')

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            allocation = serializer.create(validated_data=request.data)
            allocation.product = product
            if allocator == 'LiveStockProvinceJahad':
                allocation.jahad = jahad
                allocation.allocate_from = "LiveStockProvinceJahad"

            elif allocator == 'Cooperative':
                allocation.cooperative = cooperative
                allocation.allocate_from = "Cooperative"

            else:
                allocation.union = union
                allocation.allocate_from = "Union"

            if receiver == 'LiveStockProvinceJahad':
                allocation.allocate_to = "LiveStockProvinceJahad"
                allocation.charge = True
                allocation.state = 'accepted'


            elif receiver == 'Union':
                allocation.union = union
                allocation.allocate_to = "Union"

            else:
                allocation.cooperative = cooperative
                allocation.allocate_to = "Cooperative"
                if allocator == 'Cooperative':
                    allocation.charge = True

            allocation.save()

            if allocator == 'LiveStockProvinceJahad':
                jahad_warehousing(product)

            elif allocator == 'Cooperative':
                pass
            else:
                union_warehousing(product)
            if receiver == 'Union':
                reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product, union=union)

                union_warehousing(reciver_product)
            elif receiver == 'Cooperative':
                reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
                                                                    cooperative=cooperative)
                cooperative_warehousing(reciver_product)

            else:
                pass
            return Response({"result": "با موفقیت ثبت شد!"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, pk=None, *args, **kwargs):
        allocation = LiveStockAllocations.objects.get(key=request.data['allocation_key'], trash=False)
        request.data.pop('allocation_key')
        if allocation.charge == True:
            if allocation.allocate_from == 'LiveStockProvinceJahad':
                if request.data['weight'] < allocation.weight:

                    allocations = LiveStockAllocations.objects.filter(jahad=allocation.jahad,product=allocation.product, trash=False)
                    charge = (allocations.filter(charge=True).exclude(id=allocation.id).aggregate(total=Sum('weight'))[
                                  'total'] or 0) + request.data['weight']
                    jahad_alocations = allocations.filter(charge=False).aggregate(total=Sum('weight'))['total'] or 0

                    if charge < jahad_alocations:
                        return Response(
                            {"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)
            else:
                allocations = LiveStockAllocations.objects.filter(cooperative=allocation.cooperative,product=allocation.product, trash=False)
                charge = (allocations.filter(charge=True).exclude(id=allocation.id).aggregate(total=Sum('weight'))[
                              'total'] or 0) + request.data['weight']

                if request.data['weight'] < allocation.weight:

                    if charge < allocation.product.total_allocated_weight:
                        return Response(
                            {"result": "به علت عدم همخوانی موجودی و فروش امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

                elif request.data['weight'] > allocation.weight:
                    if charge > allocation.product.total_receipt_weight:
                        return Response(
                            {
                                "result": "به علت عدم همخوانی سهمیه دریافتی و موجودی انبار امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

        else:
            if request.data['weight'] > allocation.weight:
                if allocation.allocate_from == 'LiveStockProvinceJahad':
                    jahad_products = allocation.product
                    dif = request.data['weight'] - allocation.weight
                    if dif > jahad_products.total_remain_weight:
                        return Response(
                            {"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)


                else:
                    union_products = allocation.product
                    dif = request.data['weight'] - allocation.weight
                    if dif > union_products.total_remain_weight:
                        return Response(
                            {"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

            elif request.data['weight'] < allocation.weight:
                dif = allocation.weight - request.data['weight']

                if allocation.allocate_to == 'Union':
                    union_role_product = LiveStockRolseProduct.objects.get(union=allocation.union,parent_product=allocation.product.parent_product, trash=False)
                    if dif > union_role_product.total_remain_weight:
                        return Response(
                            {"result": "به علت عدم همخوانی موجودی مقصد امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

                elif allocation.allocate_to == 'Cooperative':
                    cooperative_role_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product,
                                                                                 trash=False)

                    if dif > (cooperative_role_product.total_receipt_weight - cooperative_role_product.total_weight):
                        return Response(
                            {"result": "به علت عدم همخوانی موجودی مقصد امکان ویرایش با این وزن وجود ندارد!"},
                            status=status.HTTP_403_FORBIDDEN)

        serializer = self.serializer_class(allocation)
        serializer.update(instance=allocation, validated_data=request.data)
        product = allocation.product
        if allocation.allocate_from == 'LiveStockProvinceJahad':
            jahad_warehousing(product)

        elif allocation.allocate_from == 'Cooperative':
            pass
        else:
            union_warehousing(product)
        if allocation.allocate_to == 'Union':
            reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
                                                                union=allocation.union)
            union_warehousing(reciver_product)
        elif allocation.allocate_to == 'Cooperative':

            reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
                                                                cooperative=allocation.cooperative)
            cooperative_warehousing(reciver_product)
        else:
            pass
        return Response(serializer.data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        products = {
            "bran":"سبوس",
            "barley":"جو",
            "soy":"سویا",
            "corn":"ذرت",
            "sheep_concentrate":"کنسانتره گوسفندی",
            "high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
            "medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
            "fattening_calf_concentrate":"کنسانتره گوساله پرواری",
        }
        name =products[request.GET.get('name')]
        product = LiveStockProduct.objects.filter(trash=False, name=name).first()
        if request.GET['role'] == 'LiveStockProvinceJahad':
            allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, allocate_from="LiveStockProvinceJahad",
                                                              trash=False, product__parent_product=product).order_by(
                'id').exclude(allocate_to='LiveStockProvinceJahad')
        elif request.GET['role'] == 'Union':
            allocations = LiveStockAllocations.objects.filter(union__isnull=False, trash=False, allocate_from="Union",
                                                              product__parent_product=product).order_by('id')

        else:
            allocations = LiveStockAllocations.objects.filter(cooperative__user=user, charge=False,
                                                              allocate_to="Cooperative",
                                                              trash=False, product__parent_product=product).order_by(
                'id')

        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        if date1 and date2:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)

        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if search != 'undefined' and search.strip():
                allocations = allocations.filter(
                    build_query(self.filterset_class.Meta.fields, value)
                )

        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        page = self.paginate_queryset(allocations)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(allocations, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        allocation = LiveStockAllocations.objects.get(key=request.GET["allocation_key"])
        product = allocation.product

        if allocation.allocate_from == 'LiveStockProvinceJahad':
            if allocation.allocate_to == 'LiveStockProvinceJahad':
                roles_product = allocation.product
            elif allocation.allocate_to == 'Union':
                roles_product = LiveStockRolseProduct.objects.get(union=allocation.union,parent_product=allocation.product.parent_product)
            else:
                roles_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product)

            if allocation.weight > roles_product.total_remain_weight:
                if allocation.allocate_to == 'Cooperative':
                    if roles_product.total_receipt_weight >= allocation.weight:
                        pass
                else:
                    return Response(
                        {"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
                        status=status.HTTP_403_FORBIDDEN)
        elif allocation.allocate_from == 'Union':
            if allocation.allocate_to == 'Union':
                roles_product = allocation.product
            else:
                roles_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product)

            if allocation.weight > roles_product.total_remain_weight:
                if allocation.allocate_to == 'Cooperative':
                    if roles_product.total_receipt_weight >= allocation.weight:
                        pass
                else:
                    return Response(
                        {"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
                        status=status.HTTP_403_FORBIDDEN)



        else:

            cooperative_roles_product = allocation.product
            if allocation.weight > cooperative_roles_product.total_remain_weight:
                return Response(
                    {"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
                    status=status.HTTP_403_FORBIDDEN)

        allocation.trash = True
        allocation.save()
        if allocation.allocate_from == 'LiveStockProvinceJahad':
            jahad_warehousing(product)

        elif allocation.allocate_from == 'Cooperative':
            pass
        else:
            union_warehousing(product)
        if allocation.allocate_to == 'Union':
            reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
                                                                union=allocation.union)
            union_warehousing(reciver_product)
        elif allocation.allocate_to == 'Cooperative':

            reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
                                                                cooperative=allocation.cooperative)
            cooperative_warehousing(reciver_product)
        else:
            pass
        return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)


class CooperativeProductsShareViewSet(viewsets.ModelViewSet):
    queryset = CooperativeProductsShare.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = CooperativeProductsShareSerializer
    pagination_class = CustomPagination
    filterset_class = CooperativeProductsShareFilterSet

    def update(self, request, pk=None, *args, **kwargs):
        share = CooperativeProductsShare.objects.get(key=request.data['share_key'], trash=False)
        request.data.pop('share_key')

        serializer = self.serializer_class(share)
        serializer.update(instance=share, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        shares = CooperativeProductsShare.objects.filter(product__name=request.GET['name'], trash=False).order_by(
            'id')
        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if search != 'undefined' and search.strip():
                shares = shares.filter(
                    build_query(self.filterset_class.Meta.fields, value)
                )

        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        page = self.paginate_queryset(shares)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(shares, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class LiveStockProductViewset(viewsets.ModelViewSet):
    queryset = LiveStockProduct.objects.all()
    permission_classes = [AllowAny]
    serializer_class = LiveStockProductSerializer

    def list(self, request, *args, **kwargs):
        products = {
            "bran":"سبوس",
            "barley":"جو",
            "soy":"سویا",
            "corn":"ذرت",
            "sheep_concentrate":"کنسانتره گوسفندی",
            "high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
            "medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
            "fattening_calf_concentrate":"کنسانتره گوساله پرواری",
        }
        name =products[request.GET.get('name')]

        products = LiveStockProduct.objects.filter(trash=False, name=name).first()
        serializer = self.serializer_class(products)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        products = LiveStockProduct.objects.get(key=request.data['key'])
        request.data.pop('key')
        serializer = self.serializer_class(products)
        serializer.update(instance=products, validated_data=request.data)
        # todo:اگه نیاز شده با ترد بنویس تا همه دامدار ها اپدیت بشن
        # send = threading.Thread(target=update_quota_rancher_threading)
        # send.start()
        return Response(serializer.data, status=status.HTTP_200_OK)


class DashboardLiveStockAllocationsViewSet(viewsets.ModelViewSet):
    queryset = LiveStockAllocations.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = LiveStockAllocationsSerializer
    filterset_class = LiveStockAllocationsFilterSet

    def list(self, request, *args, **kwargs):
        products = {
            "bran":"سبوس",
            "barley":"جو",
            "soy":"سویا",
            "corn":"ذرت",
            "sheep_concentrate":"کنسانتره گوسفندی",
            "high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
            "medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
            "fattening_calf_concentrate":"کنسانتره گوساله پرواری",
        }
        role = request.GET.get('role')
        name =products[request.GET.get('name')]
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        product = LiveStockProduct.objects.filter(trash=False, name=name).first()
        if request.GET['role'] == 'LiveStockProvinceJahad':
            allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, trash=False,
                                                              product__parent_product=product).order_by('id')
            roles_new_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
                                                                     , parent_product=product).first()


        elif request.GET['role'] == 'Union':
            allocations = LiveStockAllocations.objects.filter(union__user=user, trash=False,
                                                              product__parent_product=product).order_by('id')

            roles_new_product = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
                                                                     parent_product=product).first()

        else:
            allocations = LiveStockAllocations.objects.filter(cooperative__user=user, trash=False,
                                                              product__parent_product=product).order_by('id')
            roles_new_product = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
                                                                     parent_product=product).first()

        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        if date1 and date2:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)

        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if search != 'undefined' and search.strip():
                allocations = allocations.filter(
                    build_query(self.filterset_class.Meta.fields, value)
                )
        jahat_to_union = allocations.filter(jahad__isnull=False, allocate_to='Union')
        jahat_to_cooperative = allocations.filter(jahad__isnull=False, allocate_to='Cooperative')
        union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False, trash=False, allocate_to='Cooperative')
        if role == 'Union':
            union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False,trash=False, allocate_to='Cooperative')

        jahat_to_union_weight = jahat_to_union.aggregate(total=Sum('weight'))[
                                    'total'] or 0
        jahat_to_union_real_weight = jahat_to_union.aggregate(total=Sum('real_weight'))[
                                         'total'] or 0
        jahat_to_cooperative_weight = jahat_to_cooperative.aggregate(total=Sum('weight'))[
                                          'total'] or 0
        jahat_to_cooperative_real_weight = jahat_to_cooperative.aggregate(total=Sum('real_weight'))[
                                               'total'] or 0
        union_to_cooperative_weight = union_to_cooperative.aggregate(total=Sum('weight'))[
                                          'total'] or 0
        union_to_cooperative_real_weight = union_to_cooperative.aggregate(total=Sum('real_weight'))[
                                               'total'] or 0

        if role =='Union':
            role_product_union = roles_new_product.total_remain_weight
            role_product_cooperative =  0
            role_product_cooperative_receipt_weight =  0

        elif role == 'Cooperative':
            role_product_union = 0
            role_product_cooperative = roles_new_product.total_remain_weight
            role_product_cooperative_receipt_weight = roles_new_product.total_receipt_weight

        else:
            roles_product = LiveStockRolseProduct.objects.filter(trash=False, parent_product=product)
            union_remain = roles_product.filter(union__isnull=False)
            cooperative_remain = roles_product.filter(cooperative__isnull=False)
            role_product_union = union_remain.aggregate(total=Sum('total_remain_weight'))[
                                     'total'] or 0
            role_product_cooperative = cooperative_remain.aggregate(total=Sum('total_remain_weight'))[
                                           'total'] or 0
            role_product_cooperative_receipt_weight = cooperative_remain.aggregate(total=Sum('total_receipt_weight'))[
                                                          'total'] or 0

        if allocations:
            dict1 = {
                "total_weight": roles_new_product.total_weight,
                "jahad_to_union": jahat_to_union_weight,
                "jahat_to_union_real_weight": jahat_to_union_real_weight,
                "jahat_to_cooperative": jahat_to_cooperative_weight,
                "jahat_to_cooperative_real_weight": jahat_to_cooperative_real_weight,

                "allocation_count": roles_new_product.total_allocated_weight,
                "union_to_cooperative": union_to_cooperative_weight,
                "union_to_cooperative_real_weight": union_to_cooperative_real_weight,
                "total_remain_weight_jahad": roles_new_product.total_remain_weight,
                "total_remain_weight_union": role_product_union,
                "total_remain_weight_cooperative": role_product_cooperative,
                "role_product_cooperative_receipt_weight": role_product_cooperative_receipt_weight,
                "total_remain_weight": roles_new_product.total_remain_weight,
            }
        else:
            dict1 = {
                "total_weight": 0,
                "jahad_to_union": 0,
                "jahat_to_cooperative": 0,

                "allocation_count": 0,
                "union_to_cooperative": 0,
                "total_remain_weight_jahad": 0,
                "total_remain_weight_union": 0,
                "total_remain_weight_cooperative": 0,
                "total_remain_weight": 0,
                "jahat_to_union_real_weight": 0,
                "union_to_cooperative_real_weight": 0,
                "jahat_to_cooperative_real_weight": 0,
                "role_product_cooperative_receipt_weight": role_product_cooperative_receipt_weight,

            }
        return Response(dict1, status=status.HTTP_200_OK)


class LiveStockWarehouseChargeAllocationsViewSet(viewsets.ModelViewSet):
    queryset = LiveStockAllocations.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = LiveStockAllocationsSerializer
    pagination_class = CustomPagination
    filterset_class = LiveStockAllocationsFilterSet

    def list(self, request, *args, **kwargs):
        user = SystemUserProfile.objects.get(user=request.user, trash=False)
        products = {
            "bran":"سبوس",
            "barley":"جو",
            "soy":"سویا",
            "corn":"ذرت",
            "sheep_concentrate":"کنسانتره گوسفندی",
            "high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
            "medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
            "fattening_calf_concentrate":"کنسانتره گوساله پرواری",
        }
        name =products[request.GET.get('name')]
        product = LiveStockProduct.objects.filter(trash=False, name=name).first()
        if request.GET['role'] == 'LiveStockProvinceJahad':
            allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, trash=False,
                                                              product__parent_product=product,
                                                              allocate_to='LiveStockProvinceJahad').order_by('id')

        elif request.GET['role'] == 'Union':
            allocations = LiveStockAllocations.objects.filter(allocate_from='LiveStockProvinceJahad', union__isnull=False,
                                                              trash=False, product__parent_product=product).order_by(
                'id')

        else:
            # allocations = LiveStockAllocations.objects.filter(
            #     allocate_from__in=('LiveStockProvinceJahad', 'Union', 'Cooperative'), cooperative__user=user,
            #     trash=False, product__parent_product=product).order_by('id')
            allocations = LiveStockAllocations.objects.filter(
                charge=True, cooperative__user=user,
                trash=False, product__parent_product=product).order_by('id')

        date1 = request.GET.get('date1')
        date2 = request.GET.get('date2')
        if date1 and date2:
            date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()

            date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
            allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)

        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if search != 'undefined' and search.strip():
                allocations = allocations.filter(
                    build_query(self.filterset_class.Meta.fields, value)
                )

        page_size = request.query_params.get('page_size', None)
        if page_size:
            self.pagination_class.page_size = int(page_size)

        page = self.paginate_queryset(allocations)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(allocations, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def get_user_live_stock(request):
    type = request.GET['type']
    if type == 'Union':
        unions = Union.objects.filter(trash=False).order_by('id')
        serializer = UnionSerializer(unions, many=True)

    else:
        cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
        serializer = RancherSerializer(cooperatives, many=True)

    return Response(serializer.data, status=status.HTTP_200_OK)
