import datetime

from django.db.models import Sum, F
from rest_framework import serializers

from authentication.serializer.serializer import SystemUserProfileSerializer, BankCardSerializer, \
    SystemUserProfileForGuildSerializer
from authentication.serializers import SystemAddressSerializer
from panel.CityOperator.helpers import get_city_sub_sector_finance_info, get_city_sub_sector_finance_info_with_date
from panel.models import CityOperatorCheckRequest, CityOperator, ProvinceKillRequest, ProvinceCheckOperatorRequest, \
    WageType, PercentageOfWageType, PoultryHatching, Poultry, PoultryRequest, KillHouseFreeBarInformation, \
    KillHouseFreeSaleBarInformation, KillHouse
from panel.poultry.serializers import PoultryRequestSerializer


# سریالایزر مربوط به اپراتور شهرستان
class CityOperatorSerializer(serializers.ModelSerializer):
    user = SystemUserProfileSerializer(read_only=True)
    address = SystemAddressSerializer(read_only=True)
    user_bank_info = BankCardSerializer(read_only=True, required=False)

    class Meta:
        model = CityOperator
        exclude = (
            'id',
            'create_date',
            'modify_date',
            # 'trash',
            'created_by',
            'modified_by',
        )


class CityOperatorForAllUserSerializer(serializers.ModelSerializer):
    address = SystemAddressSerializer(read_only=True)
    user_bank_info = BankCardSerializer(read_only=True, required=False)

    class Meta:
        model = CityOperator
        fields = ['address', 'user_bank_info', 'identity_documents', 'phone', 'unit_name']


class CityOperatorForPoultrySerializer(serializers.ModelSerializer):
    address = SystemAddressSerializer(read_only=True)

    class Meta:
        model = CityOperator
        fields = ['key', 'address', 'unit_name']


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

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


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

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


    def get_wage_info(self, obj):
        date1=None
        date2=None
        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()
        poultries = Poultry.objects.filter(city_operator=obj.unit_name,trash=False).order_by('id')
        info=get_city_sub_sector_finance_info(poultries,obj,date1,date2)
        return info



# سریالایزر مربوط به بررسی درخواست مرغدار توسط شهرستان (تایید یا رد)
class CityOperatorCheckRequestSerializer(serializers.ModelSerializer):
    poultry_request = PoultryRequestSerializer(read_only=True)
    quantity = serializers.SerializerMethodField('get_quantity')

    # city_operator = CityOperatorSerializer()

    class Meta:
        model = CityOperatorCheckRequest
        fields = '__all__'

    def get_quantity(self, instance):
        allocated_number = 0
        returned_number = 0
        assignable_number = 0
        province_check_req = ProvinceCheckOperatorRequest.objects.filter(city_request_Poultry=instance)
        if province_check_req.count() > 0:
            province_check_req = province_check_req.last()
            assignable_number = province_check_req.quantity
        else:
            assignable_number = instance.poultry_request.quantity

        province_kill_requests = ProvinceKillRequest.objects.filter(province_request__city_request_Poultry=instance,
                                                                    trash=False, state__in=('pending', 'accepted'))
        if province_kill_requests.count() > 0:
            for province_kill_request in province_kill_requests:
                if province_kill_request.return_to_province == False:
                    allocated_number += province_kill_request.main_quantity
                else:
                    returned_number += province_kill_request.main_quantity

        quantity = {
            "allocated_number": allocated_number,
            "assignable_number": assignable_number,
            "returned_number": returned_number,
        }
        return quantity


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

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


    def get_wage_info(self, obj):
        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()

        poultries = Poultry.objects.filter(city_operator=obj.unit_name,trash=False).order_by('id')
        info=get_city_sub_sector_finance_info_with_date(poultries,obj,date1,date2)
        return info