from rest_framework import serializers as serializer

from common.accounts.models import Users
from console.message.models import Message, UserMessage
from console.message.services import send_message
from console.message.services import get_user_by_department
from console.customer.models import CustomerAdmin

from console.message.models import Notifications as Notification


class MessageSerializer(serializer.ModelSerializer):
    reciever = serializer.SerializerMethodField()
    sender = serializer.SerializerMethodField()

    def get_sender(self, obj):
        return {
            "id": obj.sender.id,
            "username": obj.sender.username
        } if obj.sender else None

    def get_reciever(self, obj):
        user = UserMessage.objects.filter(message=obj).values_list("user")
        return Users.objects.filter(id__in=user).values("id", "nickname")

    class Meta:
        model = Message
        fields = ("id", "content", "sender", "send_type", "reciever",
                  "created_time", "type")


class MessageCreateSerializer(serializer.Serializer):
    content = serializer.CharField(required=True,
                                   allow_null=False,
                                   allow_blank=False)
    send_type = serializer.CharField(required=True,
                                     allow_blank=False,
                                     allow_null=True)
    reciever = serializer.ListField(child=serializer.IntegerField(),
                                    allow_null=True,
                                    required=False)
    department = serializer.ListField(child=serializer.IntegerField(),
                                      required=False,
                                      allow_null=True)
    type = serializer.IntegerField(required=False, allow_null=True)
    customer = serializer.ListField(child=serializer.IntegerField(),
                                    required=False,
                                    allow_null=True,
                                    allow_empty=True)

    def validate(self, attrs):
        send_type = attrs.get("send_type").split(",")
        for item in send_type:
            if item not in ["0", "1", "2"]:
                raise serializer.ValidationError("发送类型非法")
        if attrs.get("type") is None and attrs.get("type") not in [0, 1]:
            raise serializer.ValidationError("type's value is not correct")
        return attrs

    def create(self, validated_data):
        request = self.context.get("request")

        # 创建消息
        message = Message.objects.create(
            content=validated_data.get("content"),
            sender=request.user,
            send_type=validated_data.get("send_type"),
            type=validated_data.get("type", 0))
        user_message = []
        user_id = validated_data.get("reciever", [])
        if validated_data.get("department"):
            user_id += get_user_by_department(validated_data.get("department"))
        if validated_data.get("customer"):
            user_id += CustomerAdmin.objects.filter(
                customer_id__in=validated_data.get("customer")).values_list(
                "user_id", flat=True)
        for id in list(set(user_id)):
            user_message.append(UserMessage(user_id=id, message=message))
        UserMessage.objects.bulk_create(user_message)
        data = {
            "sender": request.user,
            "message": message,
            "send_type": validated_data.get("send_type"),
            "reciever": user_id,
            "content": validated_data.get("content")
        }
        # 发送通知
        send_message(**data)
        return message


class NotificationSerializer(serializer.ModelSerializer):
    unread = serializer.SerializerMethodField()

    def get_unread(self, obj):
        return 1 if obj.unread else 0

    class Meta:
        model = Notification
        fields = ("id", "unread", "description", "verb", "timestamp",
                  "recipient_id", "type", "is_pop")
