# coding=utf-8

from rest_framework import serializers
from utils.exceptions import CustomError
from apps.account.models import User
from apps.tenant.employee.models import Employee

class UserSerializer(serializers.ModelSerializer):
    type = serializers.IntegerField(read_only=True)
    password = serializers.CharField(write_only=True, allow_blank=True)
    active_text = serializers.SerializerMethodField()

    def get_active_text(self, obj):
        return obj.is_active and u'是' or u'否'

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        validated_data['type'] = User.SUPER
        if validated_data['password'].strip() == '':
            raise CustomError(u'密码不能为空！')
        instance = super(UserSerializer, self).create(validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        Employee.getOrRegister(user=instance)
        return instance

    def update(self, instance, validated_data):
        instance.update_item(validated_data)
        # if not 'password' in validated_data or not validated_data['password']:
        #     validated_data['password'] = instance.password
        #     instance = super(UserSerializer, self).update(instance, validated_data)
        # else:
        #     instance = super(UserSerializer, self).update(instance, validated_data)
        #     instance.set_password(validated_data['password'])
        # instance.save()
        return instance
