#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 User, Group,SubDepartment,SubEmployee
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)
    status_text = serializers.CharField(source='get_status_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 'status' not in data:
            data['status'] = User.DIMISSION
        return data

    def create(self, validated_data):
        groups = validated_data.pop('groups')

        instance = super(EmployeeSerializer, self).create(validated_data)
        instance.set_password(validated_data['password'])
        instance.save()

        for group in groups:
            instance.groups.add(group)

        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):
        instance.groups.clear()
        groups = validated_data.pop('groups')
        for group in groups:
            instance.groups.add(group)

        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)
    status_text = serializers.CharField(source='get_status_display',read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    groups = serializers.StringRelatedField(many=True, read_only=True)
    group_ids = serializers.PrimaryKeyRelatedField(source='groups', many=True, read_only=True)
    sub_department_ids = serializers.SerializerMethodField()
    sub_employee_ids = serializers.SerializerMethodField()

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

    def get_sub_department_ids(self, obj):
        data = []
        rows = SubDepartment.objects.filter(user=obj)
        data.extend([s.department_id for s in rows])
        return data

    def get_sub_employee_ids(self, obj):
        data = []
        rows = SubEmployee.objects.filter(user=obj)
        data.extend([s.employee_id for s in rows])
        return data

class GroupSerializer(serializers.ModelSerializer):
    employees = serializers.StringRelatedField(source='user_set', many=True, read_only=True)

    class Meta:
        model = Group
        fields = '__all__'

class GroupComboboxSerializer(serializers.ModelSerializer):
    value = serializers.CharField(source='id', read_only=True)

    class Meta:
        model = Group
        fields = ('value', 'name', )