#coding=utf-8

from rest_framework import serializers
from django.db.models import Q

from apps.serializer_errors import dump_serializer_errors
from libs.booleancharfield import BooleanCharField
from apps.exceptions import CustomError

from apps.foundation.models import BizLog
from models import Option

class OptionSerializer(serializers.ModelSerializer):
    enabled_text = BooleanCharField(source='enabled', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)

    class Meta:
        model = Option
        fields = '__all__'
        #fields = ('id', 'name', 'notes', 'enabled')

    @staticmethod
    def factory(user, data,id=None):
        if id:
            instance = Option.getById(id)
        else:
            instance = None

        serializer = OptionSerializer(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):
        item = Option.objects.filter(type=validated_data['type'], name=validated_data['name']).first()
        if item:
            raise CustomError(u'类型为[%s]的自定义项[%s]已存在' % (Option.getTypeText(validated_data['type']), validated_data['name']))

        instance = super(OptionSerializer, 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):
        if validated_data['type'] != instance.type:
            raise CustomError(u'禁止修改类别')
        item = Option.objects.filter(Q(type=instance.type), Q(name=validated_data['name']), ~Q(id=instance.id)).first()
        if item:
            raise CustomError(u'类型为[%s]的自定义项[%s]已存在' % (Option.getTypeText(validated_data['type']), validated_data['name']))

        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改自定义项[%s]，id=%s" % (validated_data['name'], id),
            validated_data
        )
        instance = super(OptionSerializer, self).update(instance, validated_data)
        return instance
