#coding=utf-8

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

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

from models import  Warehouse,WarehouseAdmin,WarehouseStock
from apps.foundation.models import BizLog

class WarehouseSerializer(serializers.ModelSerializer):
    enabled_text = BooleanCharField(source='enabled', read_only=True)
    is_default_text = BooleanCharField(source='is_default', read_only=True)
    user_text = serializers.SerializerMethodField()
    user_ids = serializers.SerializerMethodField()

    class Meta:
        model = Warehouse
        fields = '__all__'

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

        serializer = WarehouseSerializer(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 get_user_text(self, obj):
        data = []
        rows = WarehouseAdmin.objects.filter(warehouse=obj)
        data.extend([s.user.name for s in rows])
        return ','.join(data)

    def get_user_ids(self, obj):
        data = []
        rows = WarehouseAdmin.objects.filter(warehouse=obj)
        data.extend([s.user_id for s in rows])
        return data

    def create(self, validated_data):
        item = Warehouse.objects.filter(type=validated_data['type'],name=validated_data['name']).first()
        if item:
            raise CustomError(u'仓别[%s]已存在' % validated_data['name'])

        instance = super(WarehouseSerializer, self).create(validated_data)
        Warehouse.updateDefault(instance)
        WarehouseStock.createByWarehouse(instance)

        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 'type' in validated_data:
            if validated_data['type'] != instance.type:
                raise CustomError(u'禁止修改仓别的类型')

        item = Warehouse.objects.filter(Q(type=instance.type), Q(name=validated_data['name']),~Q(id=instance.id)).first()
        if item:
            raise CustomError(u'仓别[%s]已存在' % validated_data['name'])

        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改仓别[%s]，id=%s" % (instance.name, instance.id),
            validated_data
        )
        instance = super(WarehouseSerializer, self).update(instance,validated_data)
        Warehouse.updateDefault(instance)
        return instance

