#coding=utf-8

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

from apps.exceptions import CustomError
from apps.serializer_errors import dump_serializer_errors
from apps.warehouse.models import WarehouseStock
from models import ProductBase

class ProductBaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductBase
        fields = '__all__'

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

        serializer = ProductBaseSerializer(instance, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        item = ProductBase.objects.filter(type=validated_data['type'], model=validated_data['model']).first()
        if item:
            raise CustomError(u'代码为[%s]的%s已存在' % (validated_data['model'],ProductBase.getTypeText(validated_data['type'])))

        instance = super(ProductBaseSerializer, self).create(validated_data)
        WarehouseStock.createByProduct(instance)
        return instance

    def update(self, instance, validated_data):
        if 'type' in validated_data:
            if validated_data['type'] != instance.type:
                raise CustomError(u'禁止修改产品的类型')

        item = ProductBase.objects.filter(Q(type=instance.type), Q(model=validated_data['model']),~Q(id=instance.id)).first()
        if item:
            raise CustomError(u'代码为[%s]的%s已存在' % (validated_data['model'], ProductBase.getTypeText(instance.type)))

        instance = super(ProductBaseSerializer, self).update(instance, validated_data)
        return instance

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