from django.contrib.auth.models import User, Group
from django.db.models import Q

from authentication.models import (
    UserProfile,
    Address,
    BankCard,
    SystemUserProfile,
    PermissionLevel, ExternalTransaction
)
from rest_framework import serializers
from authentication.permission_views import GroupSerializer
from authentication.serializers import SystemAddressSerializer, UserSerializer, ProvinceSerializer, CitySerializer
from panel.models import KillHouse, WagePayment, ProvinceKillRequest


# سریالایزر مربوط به مدل آدرس
class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = [
            'key',
            'title',
            'country',
            'province',
            'city',
            'address',
            'postal_code',
            'breeding_unique_id',
            'phone',
            'phone_type',
            'no',
            'floor',
            'unit',
        ]

    def create(self, validated_data):
        return Address.objects.create(**validated_data)


# سریالایزر مربوط به مدل اطلاعات بانکی
class BankCardSerializer(serializers.ModelSerializer):
    class Meta:
        model = BankCard
        exclude = (
            'id',
            'create_date',
            'modify_date',
            'trash',
            'created_by',
            'modified_by',
        )
        extra_kwargs = {
            'name_of_bank_user': {'required': False, 'allow_null': True},
            'bank_name': {'required': False, 'allow_null': True},
            'card': {'required': False, 'allow_null': True},
            'shaba': {'required': False, 'allow_null': True},
            'account': {'required': False, 'allow_null': True},
        }


# سریالایزر مربوط به مدل کاربر
class UserProfileSerializer(serializers.ModelSerializer):
    user_bank_info = BankCardSerializer(read_only=True)
    address = AddressSerializer(read_only=True)
    role = GroupSerializer(read_only=True)
    job = serializers.SerializerMethodField('get_job')

    def get_job(self, instance):
        # if instance.role.name == 'Poultry':
        #     pass
        # if instance.role.name == 'CityOperator':
        #     pass
        # if instance.role.name == 'ProvinceOperator':
        #     pass
        if instance.role.name == 'KillHouse':
            kill_house = KillHouse.objects.get(user=instance).name
            return kill_house
        else:
            return None

    class Meta:
        model = UserProfile
        fields = [
            'key',
            'create_date',
            # 'token',
            'fullname',
            'first_name',
            'last_name',
            'natinal_id',
            'mobile',
            'birthday',
            'image',
            'state',
            'role',
            'address',
            'unit_name',
            'gis_code',
            'operating_licence_capacity',
            'number_of_halls',
            'tenant',
            'person_type',
            'economic_code',
            'system_code',
            'epidemiological_code',
            'breeding_unique_id',
            'total_capacity',
            'licence_number',
            'health_certificate_number',
            'number_of_requests',
            'hatching_date',
            'last_party_date',
            'number_of_incubators',
            'herd_age_by_day',
            'herd_age_by_week',
            'number_of_party',
            'communication_type',
            'cooperative',
            'date_of_register',
            'unit_status',
            'samasat_user_code',
            'user_bank_info',
            'job',
            'incubation_date',
        ]


class SystemUserProfileForAutoAllocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'first_name', 'last_name', 'base_order', 'mobile', 'national_id', 'national_code', 'key',
                  'city', 'unit_name', 'unit_national_id', 'unit_registration_number', 'unit_economical_number',
                  'unit_province', 'unit_city', 'unit_postal_code', 'unit_address']
        depth = 1


class SystemUserProfileForGuildSerializer(serializers.ModelSerializer):
    city = serializers.CharField(source='city.name', read_only=True)

    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'first_name', 'last_name', 'mobile', 'national_id', 'city','father_name','gender','is_alive','birthday','national_code']
        depth = 1


class SystemUserProfileForInspectionSerializer(serializers.ModelSerializer):
    province_name = serializers.CharField(source='province.name', read_only=True)
    city_name = serializers.CharField(source='city.name', read_only=True)

    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'first_name', 'last_name', 'mobile', 'national_id', 'province_name', 'city_name','is_alive','national_code','gender','father_name','birthday',
                  'password']


class SystemUserProfileForAllUsersSerializer(serializers.ModelSerializer):
    role = serializers.SerializerMethodField('get_role')

    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'national_id', 'mobile', 'birthday', 'password', 'role']

    def get_role(self, instance):
        role_list = []
        for item in instance.role.all():
            role_list.append(item.name)
        return role_list


class SystemUserProfileSerializer(serializers.ModelSerializer):
    # user=UserSerializer(read_only=True)
    address = SystemAddressSerializer(read_only=True, required=False)
    role = serializers.SerializerMethodField('get_role')
    city = serializers.SerializerMethodField('get_city')
    province = serializers.SerializerMethodField('get_province')

    class Meta:
        model = SystemUserProfile
        exclude = (
            'id',
            'create_date',
            'modify_date',
            'trash',
            'token',
            'created_by',
            'modified_by',
            'user',
            # 'password',
            'access_level',
        )
        # extra_kwargs = {"access_level": {"required": False, "allow_null": True}}

    def get_city(self, instance):
        if instance.city == None:
            pass
        else:
            return instance.city.name

    def get_province(self, instance):
        if instance.province == None:
            pass
        else:
            return instance.province.name

    def get_role(self, instance):
        role_list = []
        for item in instance.role.all():
            role_list.append(item.name)
        return role_list


class SystemUserProfileForFactorSerializer(serializers.ModelSerializer):
    class Meta:
        model = SystemUserProfile
        fields = ['key', 'fullname', 'first_name', 'last_name', 'mobile', 'unit_name', 'unit_national_id',
                  'unit_registration_number', 'unit_economical_number', 'unit_province', 'unit_city',
                  'unit_postal_code', 'unit_address']


class SystemUserProfileBaseInfoSerializer(serializers.ModelSerializer):
    role = GroupSerializer(many=True)
    city = CitySerializer(read_only=True, required=False)
    province = ProvinceSerializer(read_only=True, required=False)

    class Meta:
        model = SystemUserProfile
        exclude = (
            'id',
            'create_date',
            'modify_date',
            'trash',
            'token',
            'created_by',
            'modified_by',
            'user',
            'state',
            # 'password',
            'access_level',
        )


class ExternalTransactionSerializer(serializers.ModelSerializer):
    receiver = SystemUserProfileForAutoAllocationSerializer(read_only=True)
    creator = SystemUserProfileForAutoAllocationSerializer(read_only=True)
    information = serializers.SerializerMethodField('get_information')

    class Meta:
        model = ExternalTransaction
        fields = '__all__'

    def get_information(self, obj):
        total_weight = 0
        total_quantity = 0
        total_request = 0
        wage_payment = WagePayment.objects.filter(Q(orderId=obj.orderId) | Q(tracking_code=obj.saleReferenceId),
                                                  trash=False).first()
        if wage_payment.province_kill_request != None:
            total_request = len(wage_payment.province_kill_request)
            for province_kill_req in wage_payment.province_kill_request:
                province_kill = ProvinceKillRequest.objects.get(key=province_kill_req, trash=False)
                total_weight += province_kill.total_killed_weight
                total_quantity += province_kill.total_killed_quantity
        return {
            "total_weight": total_weight,
            "total_quantity": total_quantity,
            "total_request_number": total_request,
        }


class SystemUserProfileForPoultryLocSerializer(serializers.ModelSerializer):
    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'mobile']


class SystemUserProfileBaseInfoForTicketSerializer(serializers.ModelSerializer):
    role = GroupSerializer(many=True)
    city = CitySerializer(read_only=True, required=False)
    province = ProvinceSerializer(read_only=True, required=False)

    class Meta:
        model = SystemUserProfile
        fields = ['birthday', 'first_name', 'fullname', 'key', 'last_name', 'mobile', 'national_code', 'role', 'city',
                  'province']


class SystemUserProfileForPoultryScienceSerializer(serializers.ModelSerializer):
    role = serializers.SerializerMethodField('get_role')

    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'mobile','role']

    def get_role(self, instance):
        role_list = []
        for item in instance.role.all():
            role_list.append(item.name)
        return role_list


class SystemUserProfileForPoultryScienceWithoutRoleSerializer(serializers.ModelSerializer):
    city = CitySerializer(read_only=True, required=False)

    class Meta:
        model = SystemUserProfile
        fields = ['fullname', 'mobile','city']

