from rest_framework.serializers import ModelSerializer, \
    PrimaryKeyRelatedField, ManyRelatedField

from common.utils.exceptions import ValidationError
from .models import Team, TeamSchedule, HandOverRecord, \
    TEAM_TYPE, HANDOVER_TYPE
from common.accounts.models import Users

team_tp_map = dict(TEAM_TYPE)


class TeamSerializer(ModelSerializer):
    """
    Team Serializer
    """

    # team_headman = PrimaryKeyRelatedField(queryset=Users.objects.all())
    # leader = PrimaryKeyRelatedField(queryset=Users.objects.all())
    member = ManyRelatedField(
        child_relation=PrimaryKeyRelatedField(queryset=Users.objects.all()),
        required=False,
        allow_null=True,
        allow_empty=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['member'] = instance.member.values_list("nickname", flat=True)
        if instance.leader:
            ret['leader'] = instance.leader.nickname

        if instance.team_headman:
            ret['team_headman'] = instance.team_headman.nickname
        if instance.type:
            ret['type'] = team_tp_map.get(instance.type)
        return ret

    class Meta:
        model = Team
        fields = ('id', 'name', 'team_headman', 'member', 'type', 'car_number',
                  'leader', 'enterprise')

    def validate(self, attrs):
        team_headerman = attrs.get('team_headman')
        if not team_headerman:
            raise ValidationError('需要添加组长')
        flag = Team.objects.filter(team_headman=team_headerman, deleted=False)
        member = attrs.get('member')
        pk = self.initial_data.get('id')
        if not pk:
            if flag.exists():
                raise ValidationError('该组长已经担任其他组组长')
            else:
                flag2 = Team.objects.filter(member=team_headerman,
                                            deleted=False)
                if flag2.exists():
                    raise ValidationError('该组长已经担任其他组组员')
            for item in member:
                if Team.objects.filter(team_headman=item,
                                       deleted=False).exists():
                    raise ValidationError('该组员已经担任组长')
                if Team.objects.filter(member=item, deleted=False).exists():
                    raise ValidationError('该组员已经担任其他组组员')

        else:
            team = Team.objects.filter(id=self.initial_data['id'],
                                       deleted=False).first()
            if flag.exists():
                origin_team_headman = team.team_headman
                if team_headerman != origin_team_headman:
                    raise ValidationError('该组长已经担任其他组组长')
            else:
                flag2 = Team.objects.filter(member=team_headerman,
                                            deleted=False)
                if flag2.exists():
                    raise ValidationError('该组长已经担任其他组组员')
            for item in member:
                if Team.objects.filter(team_headman=item,
                                       deleted=False).exists():
                    raise ValidationError('该组员已经担任组长')
                if Team.objects.filter(member=item, deleted=False).exists():
                    for t in Team.objects.filter(deleted=False).all():
                        members = t.member.all()
                        if item in members:
                            if t.id != self.initial_data['id']:
                                raise ValidationError('该组员已经担任其他组组员')
        return attrs


class TeamIDSerializer(ModelSerializer):
    """
    Team ID Serializer
    """
    team_headman = PrimaryKeyRelatedField(queryset=Users.objects.all())
    leader = PrimaryKeyRelatedField(queryset=Users.objects.all(),
                                    allow_null=True,
                                    allow_empty=True)
    member = ManyRelatedField(
        child_relation=PrimaryKeyRelatedField(queryset=Users.objects.all()),
        required=False,
        allow_null=True,
        allow_empty=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['member'] = [{
            "id": x.id,
            "nickname": x.nickname
        } for x in instance.member.all()]
        if instance.leader:
            ret['leader'] = {
                "id": instance.leader.id,
                "nickname": instance.leader.nickname
            }

        if instance.team_headman:
            ret['team_headman'] = {
                "id": instance.team_headman.id,
                "nickname": instance.team_headman.nickname
            }
        if instance.type:
            ret['type'] = {
                "id": instance.type,
                "name": team_tp_map.get(instance.type)
            }
        return ret

    class Meta:
        model = Team
        fields = ('id', 'name', 'team_headman', 'member', 'type', 'car_number',
                  'leader')

    def validate(self, attrs):
        team_headerman = attrs.get('team_headman')
        if not team_headerman:
            raise ValidationError('需要添加组长')
        flag = Team.objects.filter(team_headman=team_headerman, deleted=False)
        member = attrs.get('member')
        pk = self.initial_data.get('id')
        if not pk:
            if flag.exists():
                raise ValidationError('该组长已经担任其他组组长')
            else:
                flag2 = Team.objects.filter(member=team_headerman,
                                            deleted=False)
                if flag2.exists():
                    raise ValidationError('该组长已经担任其他组组员')
            for item in member:
                if Team.objects.filter(team_headman=item,
                                       deleted=False).exists():
                    raise ValidationError('该组员已经担任组长')
                if Team.objects.filter(member=item, deleted=False).exists():
                    raise ValidationError('该组员已经担任其他组组员')

        else:
            team = Team.objects.filter(id=self.initial_data['id'],
                                       deleted=False).first()
            if flag.exists():
                origin_team_headman = team.team_headman
                if team_headerman != origin_team_headman:
                    raise ValidationError('该组长已经担任其他组组长')
            else:
                flag2 = Team.objects.filter(member=team_headerman,
                                            deleted=False)
                if flag2.exists():
                    raise ValidationError('该组长已经担任其他组组员')
            for item in member:
                if Team.objects.filter(team_headman=item,
                                       deleted=False).exists():
                    raise ValidationError('该组员已经担任组长')
                if Team.objects.filter(member=item, deleted=False).exists():
                    for t in Team.objects.filter(deleted=False).all():
                        members = t.member.all()
                        if item in members:
                            if t.id != self.initial_data['id']:
                                raise ValidationError('该组员已经担任其他组组员')
        return attrs


class TeamScheduleSerializer(ModelSerializer):
    """
    TeamSchedule Serializer
    """
    team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['team'] = instance.team.name
        return ret

    class Meta:
        model = TeamSchedule
        fields = ('id', 'team', 'schedule_date')


class HandOverRecordSerializer(ModelSerializer):
    """
    HandOverRecord Serializer
    """
    transfer_team = PrimaryKeyRelatedField(queryset=Team.objects.all())
    recieve_team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.transfer_team:
            ret['transfer_team'] = instance.transfer_team.name
        if instance.recieve_team:
            ret['recieve_team'] = instance.recieve_team.name
        if instance.type:
            for k, v in HANDOVER_TYPE:
                if instance.type == str(k):
                    ret['type'] = v
        return ret

    class Meta:
        model = HandOverRecord
        fields = ('id', 'station', 'transfer_team', 'recieve_team',
                  'handover_time', 'type', 'inspect', 'changes', 'overhaul',
                  'work_situation', 'equipment_inspect', 'station_work',
                  'work_ticket', 'handover_work', 'tool_check', 'other',
                  'dispatch_options')


class HandOverRecordDutySerializer(ModelSerializer):
    """
    HandOverRecord Serializer
    """
    transfer_team = PrimaryKeyRelatedField(queryset=Team.objects.all())
    recieve_team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.transfer_team:
            ret['transfer_team'] = instance.transfer_team.name
        if instance.recieve_team:
            ret['recieve_team'] = instance.recieve_team.name
        if instance.type:
            for k, v in HANDOVER_TYPE:
                if instance.type == str(k):
                    ret['type'] = v
        return ret

    class Meta:
        model = HandOverRecord
        fields = ('id', 'station', 'transfer_team', 'recieve_team',
                  'handover_time', 'type', 'inspect', 'changes', 'overhaul',
                  'work_situation', 'equipment_inspect', 'station_work',
                  'work_ticket', 'handover_work', 'tool_check', 'other')


class HandOverRecordDispatchSerializer(ModelSerializer):
    """
    HandOverRecord Serializer
    """
    transfer_team = PrimaryKeyRelatedField(queryset=Team.objects.all())
    recieve_team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.transfer_team:
            ret['transfer_team'] = instance.transfer_team.name
        if instance.recieve_team:
            ret['recieve_team'] = instance.recieve_team.name
        if instance.type:
            for k, v in HANDOVER_TYPE:
                if instance.type == str(k):
                    ret['type'] = v
        return ret

    class Meta:
        model = HandOverRecord
        fields = ('id', 'station', 'transfer_team', 'recieve_team',
                  'handover_time', 'type', 'other', 'dispatch_options')


class HandOverRecordListSerializer(ModelSerializer):
    """
    HandOverRecord Serializer
    """
    transfer_team = PrimaryKeyRelatedField(queryset=Team.objects.all())
    recieve_team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.transfer_team:
            ret['transfer_team'] = instance.transfer_team.name
        if instance.recieve_team:
            ret['recieve_team'] = instance.recieve_team.name
        if instance.type:
            for k, v in HANDOVER_TYPE:
                if instance.type == str(k):
                    ret['type'] = v
        return ret

    class Meta:
        model = HandOverRecord
        fields = ('id', 'station', 'transfer_team', 'recieve_team', 'type',
                  'handover_time')


class TeamFileSerializer(ModelSerializer):
    """
    Team Serializer
    """
    team_headman = PrimaryKeyRelatedField(queryset=Users.objects.all())
    leader = PrimaryKeyRelatedField(queryset=Users.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['member'] = [x.nickname for x in instance.member.all()]
        if instance.leader:
            ret['leader'] = instance.leader.nickname
        if instance.team_headman:
            ret['team_headman'] = instance.team_headman.nickname
        if instance.type:
            for k, v in TEAM_TYPE:
                if instance.type == str(k):
                    ret['type'] = v
        return ret

    class Meta:
        model = Team
        fields = ('id', 'name', 'type', 'team_headman', 'member', 'car_number',
                  'leader')


class TeamScheduleFileSerializer(ModelSerializer):
    """
    TeamSchedule Serializer
    """
    team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        return {
            'id': instance.id,
            'team': instance.team.name,
            'schedule_date': instance.schedule_date,
        }

    class Meta:
        model = TeamSchedule
        fields = ('id', 'team', 'schedule_date')


class HandOverRecordFileSerializer(ModelSerializer):
    """
    HandOverRecord Serializer
    """
    transfer_team = PrimaryKeyRelatedField(queryset=Team.objects.all())
    recieve_team = PrimaryKeyRelatedField(queryset=Team.objects.all())

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.transfer_team:
            ret['transfer_team'] = instance.transfer_team.name
        if instance.recieve_team:
            ret['recieve_team'] = instance.recieve_team.name
        if instance.type:
            for k, v in HANDOVER_TYPE:
                if instance.type == str(k):
                    ret['type'] = v
        return ret

    class Meta:
        model = HandOverRecord
        fields = ('id', 'station', 'transfer_team', 'recieve_team', 'type',
                  'handover_time')


# class TeamHandmanSerializer(ModelSerializer):
#     """
#     Team headman Serializer
#     """
#
