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

from apps.exceptions import CustomError
from apps.foundation.models import BizLog
from apps.serializer_errors import dump_serializer_errors
from apps.supplier.models import Supplier
from libs.booleancharfield import BooleanCharField


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

    class Meta:
        model = Supplier
        fields = '__all__'

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

        serializer = SupplierSerializer(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 = Supplier.objects.filter(name=validated_data['name'], type=validated_data['type']).first()
        if item:
            if validated_data['type'] == Supplier.MATERIAL:
                raise CustomError(u'原料供应商[%s]已存在' % validated_data['name'])
            if validated_data['type'] == Supplier.CONSUMABLE:
                raise CustomError(u'耗材供应商[%s]已存在' % validated_data['name'])

        instance = super(SupplierSerializer, 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 = Supplier.objects.filter(Q(type=validated_data['type']), Q(name=validated_data['name']),~Q(id=instance.id)).first()
        if item:
            if validated_data['type'] == Supplier.MATERIAL:
                raise CustomError(u'原料供应商[%s]已存在' % validated_data['name'])
            if validated_data['type'] == Supplier.CONSUMABLE:
                raise CustomError(u'耗材供应商[%s]已存在' % validated_data['name'])

        BizLog.objects.addnew(self.user, BizLog.UPDATE, u"修改供应商[%s]，id=%d" % (
            instance.name, instance.id), validated_data)
        instance = super(SupplierSerializer, self).update(instance, validated_data)
        return instance
