from rest_framework import serializers
from apps.am.models import Access, Area
from apps.utils.serializers import CustomModelSerializer
from rest_framework.exceptions import ParseError


class AreaSimpleSerializer(CustomModelSerializer):
    class Meta:
        model = Area
        fields = ['id', 'name', 'level', 'cate']


class AreaSerializer(CustomModelSerializer):
    manager_name = serializers.CharField(source='manager.name', read_only=True)
    belong_dept_name = serializers.CharField(source='belong_dept.name', read_only=True)

    class Meta:
        model = Area
        fields = '__all__'


class AreaCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Area
        fields = ['name', 'level', 'number', 'access_list',
                  'belong_dept', 'count_people_min', 'count_people_max', 'count_people', 'cate',
                  'stay_minute_min', 'stay_minute_max', 'manager']
        extra_kwargs = {
            'belong_dept': {'required': True},
        }


class AccessCreateSerializer(CustomModelSerializer):
    class Meta:
        model = Access
        fields = ['type', 'area', 'obj_cate', 'post', 'employee', 'dept', 'sort', 'stay_minute_min', 'stay_minute_max']

    def create(self, validated_data):
        post = validated_data.get('post', None)
        dept = validated_data.get('dept', None)
        employee = validated_data.get('employee', None)
        if post:
            validated_data['obj_cate'] = 'post'
            validated_data['employee'] = None
            validated_data['dept'] = None
        elif dept:
            validated_data['obj_cate'] = 'org'
            validated_data['post'] = None
            validated_data['employee'] = None
        elif employee:
            validated_data['obj_cate'] = 'people'
            validated_data['post'] = None
            validated_data['dept'] = None
        else:
            raise ParseError('请指定岗位或部门或具体人员')
        return super().create(validated_data)


class AccessSerializer(CustomModelSerializer):
    employee_name = serializers.CharField(source='employee.name', read_only=True)
    post_name = serializers.CharField(source='post.name', read_only=True)
    dept_name = serializers.CharField(source='dept.name', read_only=True)

    class Meta:
        model = Access
        fields = '__all__'
