#coding=utf-8
from django.db.models import Q
from django.utils import timezone
from rest_framework import serializers

from apps.exceptions import CustomError
from apps.serializer_errors import dump_serializer_errors
from models import Customer

from apps.foundation.models import BizLog
from apps import base

class CustomerSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)

    class Meta:
        model = Customer
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = Customer.getById(id)
        else:
            instance = None
        serializer = CustomerSerializer(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 create(self, validated_data):
        validated_data['create_user'] = self.user
        item = Customer.objects.filter(mobile=validated_data['mobile']).first()
        if item:
            raise CustomError(u'手机号[%s]已存在' % validated_data['mobile'])

        instance = super(CustomerSerializer, self).create(validated_data)
        BizLog.objects.addnew(self.user, BizLog.INSERT, u"添加客户档案[%s]，id=%d" % (
            instance.name, instance.id), validated_data)
        return instance

    def update(self, instance, validated_data):
        item = Customer.objects.filter(Q(mobile=validated_data['mobile']), ~Q(id=instance.id)).first()
        if item:
            raise CustomError(u'手机号[%s]已存在' % validated_data['mobile'])

        BizLog.objects.addnew(self.user, BizLog.UPDATE, u"修改供客户档案[%s]，id=%d" % (
            instance.name, instance.id), validated_data)
        instance = super(CustomerSerializer, self).update(instance, validated_data)
        return instance
