import datetime

from rest_framework import serializers

from authentication.serializer.serializer import SystemUserProfileForGuildSerializer
# سریالایزر مربوط به درخواست بورسی مرغدار
from authentication.serializers import SystemAddressSerializer
from panel.KillHouse.serializers import VetSerializer, VetForBarManagementSerializer
from panel.VetFarm.helpers import get_vet_sub_sector_finance_info, get_vet_sub_sector_finance_info_with_date
from panel.models import VetFarm, VetFarmInspection, PoultryHatching, Poultry, Vet
from panel.poultry.serializers import PoultrySerializer, PoultryHatchingSerializer


class VetFarmSerializer(serializers.ModelSerializer):
    vet = VetSerializer(read_only=True)
    poultry = PoultrySerializer(read_only=True)
    inspection_info = serializers.SerializerMethodField('get_inspections')
    hatching_quantity = serializers.SerializerMethodField('get_hatching_quantity')

    class Meta:
        model = VetFarm
        fields = '__all__'

    def get_inspections(self, instance):
        inspections = len(VetFarmInspection.objects.filter(vet_farm=instance))
        hatching = PoultryHatching.objects.filter(poultry=instance.poultry, hall=int(instance.hall)).only(
            'quantity').last()
        number_of_hatching = 0
        if hatching:
            number_of_hatching = hatching.quantity
        dict1 = {}
        if inspections > 0:
            dict1 = {
                "number_of_inspections": inspections,
                "number_of_hatching": number_of_hatching
            }
        return dict1

    def get_hatching_quantity(self, instance):
        quantity = 0
        poultry = Poultry.objects.get(key=instance.poultry.key)
        poultry_hatching = PoultryHatching.objects.filter(poultry=poultry).only('left_over').last()
        if poultry_hatching:
            quantity = poultry_hatching.left_over

        return quantity


class VetForSubSectorSerializer(serializers.ModelSerializer):
    user = SystemUserProfileForGuildSerializer(read_only=True)
    wage_info = serializers.SerializerMethodField('get_wage_info')

    class Meta:
        model = Vet
        fields = ['key', 'user', 'wage_info']

    def get_wage_info(self, obj):
        if self.context.get('request').GET.get('date1'):
            date1 = datetime.datetime.strptime(str(self.context.get('request').GET['date1']),
                                               '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(self.context.get('request').GET['date2']),
                                               '%Y-%m-%d').date()
        else:
            date1=None
            date2=None
        return get_vet_sub_sector_finance_info(obj,date1,date2)


class VetForSubSectorTransactionSerializer(serializers.ModelSerializer):
    user = SystemUserProfileForGuildSerializer(read_only=True)

    class Meta:
        model = Vet
        fields = ['key', 'user']


class VetFarmInspectionSerializer(serializers.ModelSerializer):
    vet_farm = VetFarmSerializer(read_only=True)
    poultry_hatching = PoultryHatchingSerializer(read_only=True)

    class Meta:
        model = VetFarmInspection
        fields = '__all__'


class ManagementVetFarmSerializer(serializers.ModelSerializer):
    # vet = VetSerializer(read_only=True)
    poultry = PoultrySerializer(read_only=True)
    inspection_info = serializers.SerializerMethodField('get_inspections')
    hatching_quantity = serializers.SerializerMethodField('get_hatching_quantity')

    class Meta:
        model = VetFarm
        fields = '__all__'

    def get_inspections(self, instance):
        inspections = len(VetFarmInspection.objects.filter(vet_farm=instance))
        hatching = PoultryHatching.objects.filter(poultry=instance.poultry, hall=int(instance.hall)).only(
            'quantity').last()
        number_of_hatching = 0
        if hatching:
            number_of_hatching = hatching.quantity
        dict1 = {}
        if inspections > 0:
            dict1 = {
                "number_of_inspections": inspections,
                "number_of_hatching": number_of_hatching
            }
        return dict1

    def get_hatching_quantity(self, instance):
        quantity = 0
        poultry = Poultry.objects.get(key=instance.poultry.key)
        poultry_hatching = PoultryHatching.objects.filter(poultry=poultry).only('left_over').last()
        if poultry_hatching:
            quantity = poultry_hatching.left_over

        return quantity


class PoultryForCityVetSerializer(serializers.ModelSerializer):
    address = SystemAddressSerializer(read_only=True)
    inspection_info = serializers.SerializerMethodField('get_inspections')
    hatching_quantity = serializers.SerializerMethodField('get_hatching_quantity')

    class Meta:
        model = Poultry
        fields = ['key', 'unit_name', 'address', 'number_of_halls', 'breeding_unique_id', 'inspection_info',
                  'hatching_quantity']

    def get_inspections(self, instance):
        inspections = len(VetFarmInspection.objects.filter(vet_farm__poultry=instance))
        hatching = PoultryHatching.objects.filter(poultry=instance, trash=False).only('quantity').last()
        number_of_hatching = 0
        if hatching:
            number_of_hatching = hatching.quantity
        dict1 = {}
        if inspections > 0:
            dict1 = {
                "number_of_inspections": inspections,
                "number_of_hatching": number_of_hatching
            }
        return dict1

    def get_hatching_quantity(self, instance):
        total_quantity = 0
        left_over = 0
        vet_farm_losses = 0
        union_losses = 0
        period = None
        hatching_key = None
        poultry_hatching = PoultryHatching.objects.filter(poultry=instance, allow_hatching='pending', state='pending',
                                                          archive=False, violation=False, trash=False).last()
        if poultry_hatching:
            total_quantity = poultry_hatching.quantity
            left_over = poultry_hatching.left_over
            vet_farm_losses = poultry_hatching.losses
            union_losses = poultry_hatching.direct_losses
            period = poultry_hatching.period
            hatching_key = poultry_hatching.key

        return {
            "total_quantity": total_quantity,
            "left_over": left_over,
            "vet_farm_losses": vet_farm_losses,
            "union_losses": union_losses,
            "period": period,
            "total_losses": union_losses + vet_farm_losses,
            "hatching_key": hatching_key,
        }


class VetForSubSectorSerializerForExcel(serializers.ModelSerializer):
    user = SystemUserProfileForGuildSerializer(read_only=True)
    wage_info = serializers.SerializerMethodField('get_wage_info')

    class Meta:
        model = Vet
        fields = ['key', 'user', 'wage_info']

    def get_wage_info(self, obj):
        if self.context.get('request').GET['date1']:
            date1 = datetime.datetime.strptime(str(self.context.get('request').GET['date1']),
                                               '%Y-%m-%d').date()
            date2 = datetime.datetime.strptime(str(self.context.get('request').GET['date2']),
                                               '%Y-%m-%d').date()
        else:
            date1=None
            date2=None
        return get_vet_sub_sector_finance_info_with_date(obj,date1,date2)