from rest_framework import serializers
from ..models import UserProfile
import re


class UserListSerializer(serializers.ModelSerializer):
    """
    用户列表的序列化
    """
    # roles = serializers.SerializerMethodField()
    date_joined = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    department_name = serializers.StringRelatedField(source='department')
    roles_ = serializers.StringRelatedField(source='roles', many=True)
    bcompany_name = serializers.StringRelatedField(source='bcompany')

    # def get_roles(self, obj):
    #     return obj.roles.values()

    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'name', 'department', 'position',
                  'is_active', 'roles', 'date_joined', 'is_superuser','department_name', 'avatar', 'roles_', 'pname', 'bcompany_name']
        # depth = 1

    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('superior','department', 'bcompany')
        queryset = queryset.prefetch_related('roles',)
        return queryset


class UserModifySerializer(serializers.ModelSerializer):
    """
    用户编辑的序列化
    """
    mobile = serializers.CharField(max_length=11, read_only=True)

    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'name', 'mobile', 'email', 'avatar', 'department', 'position', 'superior',
                  'is_active', 'roles', 'pname', 'bcompany']

    def validate_mobile(self, mobile):
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码不合法")
        return mobile


class UserCreateSerializer(serializers.ModelSerializer):
    """
    创建用户序列化
    """
    username = serializers.CharField(required=True)
    mobile = serializers.CharField(max_length=11, read_only=True)

    class Meta:
        model = UserProfile
        fields = ['id', 'username', 'name', 'mobile', 'email', 'department', 'position', 'is_active', 'roles',
                  'password','is_superuser', 'pname', 'bcompany']

    def validate_username(self, username):
        if UserProfile.objects.filter(username=username):
            raise serializers.ValidationError(username + ' 账号已存在')
        return username

    def validate_mobile(self, mobile):
        REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码不合法")
        if UserProfile.objects.filter(mobile=mobile):
            raise serializers.ValidationError("手机号已经被注册")
        return mobile
    
    # def create(self, validated_data):
    #     user = User(**validated_data)
    #     if validated_data['password']:
    #         user.set_password(validated_data['password'])
    #     else:
    #         user.set_password('password')
    #     user.save()
    #     return user


class UserInfoListSerializer(serializers.ModelSerializer):
    """
    公共users
    """

    class Meta:
        model = UserProfile
        fields = ('id', 'name', 'mobile', 'email', 'position', 'username', 'is_active')
