#coding=utf-8

from rest_framework import serializers
from apps.exceptions import CustomError
from django.db.models import Q

from apps.foundation.models import BizLog
from .models import *
from apps.serializer_errors import dump_serializer_errors
from apps.foundation.models import BizLog

class EmployeeSerializer(serializers.ModelSerializer):
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)

    class Meta:
        model = User
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = User.getById(id)
        else:
            instance = None
        serializer = EmployeeSerializer(instance, data=data)
        serializer.user = user
        return serializer

    def validSave(self):
        if self.is_valid():
            return self.save()
        else:
            raise CustomError(dump_serializer_errors(self))

    def validate(self, data):
        if 'enabled' in data:
            data['enabled'] = True
        else:
            data['enabled'] = False
        return data


    def create(self, validated_data):
        instance = super(EmployeeSerializer, self).create(validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        BizLog.objects.addnew(self.user, BizLog.INSERT, u"添加员工[%s],id=%s" % (instance.name, instance.id),validated_data)
        return instance

    def update(self, instance, validated_data):
        BizLog.objects.addnew(self.user, BizLog.UPDATE, u"修改员工[%s],id=%s" % (instance.name, instance.id),validated_data)
        instance = super(EmployeeSerializer, self).update(instance, validated_data)
        return instance

class EmployeeSafeSerializer(serializers.ModelSerializer):
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    branch_text = serializers.CharField(source='branch.name', read_only=True)
    enabled_text = serializers.SerializerMethodField()

    class Meta:
        model = User
        exclude = ('password', )

    def get_enabled_text(self, obj):
        if obj.enabled:
            return u'是'
        return u'否'