#coding=utf-8

from rest_framework import serializers

from apps import base
from apps.account.models import User
from apps.base import Formater
from apps.exceptions import CustomError
from apps.foundation.models import BizLog
from apps.office.models import Notice, NoticeReply, NoticeBrowseRecord
from apps.serializer_errors import dump_serializer_errors
from libs.booleancharfield import CountShowCharField



class NoticeSerializer(serializers.ModelSerializer):
    department_name = serializers.CharField(source='department.name', read_only=True)
    priority_text = serializers.CharField(source='get_priority_display', read_only=True)
    dendline = serializers.DateTimeField(format=base.DATE_FORMAT)
    company_name = serializers.CharField(source='company.name', read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT1, read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    receiver_count = serializers.SerializerMethodField()
    reply_count = serializers.SerializerMethodField()
    null = serializers.SerializerMethodField()

    class Meta:
        model = Notice
        fields = '__all__'

    def get_receiver_count(self, obj):
        receiver_count = User.objects.filter(department__lft__gte=obj.department.lft, department__rgt__lte=obj.department.rgt,status=User.INSERVICE).count()
        return receiver_count

    def get_reply_count(self, obj):
        reply_count = NoticeReply.objects.filter(notice=obj).values_list('create_user', flat=True).distinct().count()
        return reply_count

    def get_null(self, obj):
        receiver_count = User.objects.filter(department__lft__gte=obj.department.lft,
                                             department__rgt__lte=obj.department.rgt, status=User.INSERVICE).count()
        reply_count = NoticeReply.objects.filter(notice=obj).values_list('create_user', flat=True).distinct().count()
        if receiver_count == 0:
            null = '0%'
        else:
            null = str(round(reply_count * 1.0 / receiver_count * 100 * 100) / 100) + '%'
        return null

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

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['create_user_department'] = self.user.department
        validated_data['company'] = self.user.department.getCompany()
        notice = Notice.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加公告[%s]，id=%d" % (notice.title, notice.id),
            validated_data
        )
        return notice

    def update(self, instance, validated_data):
        instance = super(NoticeSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改公告[%s]，id=%d" % (instance.title, instance.id),
            validated_data
        )
        return instance

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

class NoticeBrowseRecordSerializer(serializers.ModelSerializer):
    browse_user_text = serializers.CharField(source='browse_user.name', read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    class Meta:
        model = NoticeBrowseRecord
        fields = '__all__'

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

    def create(self, validated_data):
        validated_data['browse_user'] = self.user
        validated_data['department'] = self.user.department
        instance = NoticeBrowseRecord.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加浏览记录[%s]，id=%d" % (instance.notice.title, instance.id),
            validated_data
        )
        return instance

    def update(self, instance, validated_data):
        instance = super(NoticeBrowseRecordSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改浏览记录[%s]，id=%d" % (instance.notice.title, instance.id),
            validated_data
        )
        return instance

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


class NoticeReplySerializer(serializers.ModelSerializer):
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    class Meta:
        model = NoticeReply
        fields = '__all__'

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

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['department'] = self.user.department
        instance = NoticeReply.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加回复[%s]，id=%d" % (instance.notice.title, instance.id),
            validated_data
        )
        return instance

    def update(self, instance, validated_data):
        instance = super(NoticeReplySerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改回复[%s]，id=%d" % (instance.notice.title, instance.id),
            validated_data
        )
        return instance

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