#coding=utf-8
from django.conf import settings
from rest_framework import serializers

from apps import base
from apps.base import Formater
from apps.exceptions import CustomError
from apps.foundation.models import BizLog
from apps.serializer_errors import dump_serializer_errors
from libs.booleancharfield import CountShowCharField, PriceShowCharField, AmountShowCharField, EmptyPriceShowCharField, \
    EmptyAmountShowCharField
from models import ProductionPlan, SalePlan, ProductionPlanDetail, SalePlanDetail


class ProductionPlanSerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    total_count = CountShowCharField(read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)

    check_user_text2 = serializers.CharField(source='check_user2.name', read_only=True)
    check_time2 = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_user_text3 = serializers.CharField(source='check_user3.name', read_only=True)
    check_time3 = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    class Meta:
        model = ProductionPlan
        fields = '__all__'

    @staticmethod
    def factory(user,data, id=None):
        if id:
            instance = ProductionPlan.getById(id)
        else:
            instance = None
        serializer = ProductionPlanSerializer(instance, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['department'] = self.user.department
        production = ProductionPlan.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加生产计划[%s]，id=%d" % (production.name, production.id),
            validated_data
        )
        return production

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

    def update(self, instance, validated_data):
        instance = super(ProductionPlanSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改生产计划[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance


class SalePlanSerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True)
    no = serializers.CharField(read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    customer_text = serializers.CharField(source='customer.name', read_only=True)
    goods_text = serializers.SerializerMethodField()
    total_count = CountShowCharField(read_only=True)
    total_amount = EmptyAmountShowCharField(read_only=True)

    class Meta:
        model = SalePlan
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = SalePlan.getById(id)
        else:
            instance = None
        serializer = SalePlanSerializer(instance, data=data)
        serializer.user = user
        return serializer


    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['department'] = self.user.department
        instance = SalePlan.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加销售计划[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

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


    def update(self, instance, validated_data):
        instance = super(SalePlanSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改销售计划[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

    def get_goods_text(self, obj):
        data = []
        rows = SalePlanDetail.objects.filter(main=obj)
        data.extend([row.goods.product_base.name for row in rows])
        return ','.join(data)


class ProductionPlanDetailSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='product.product_base.name', read_only=True)
    model = serializers.CharField(source='product.product_base.model', read_only=True)
    count = CountShowCharField()
    quality_request_text = serializers.CharField(source='quality_request.name', read_only=True)
    product_user_id = serializers.CharField(source='product_user.id', read_only=True)
    p_department_id = serializers.CharField(source='p_department.id', read_only=True)
    department_id = serializers.CharField(source='department.id', read_only=True)
    product_user_text = serializers.CharField(source='product_user.name', read_only=True)
    p_department_text = serializers.CharField(source='p_department.name', read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)

    class Meta:
        model = ProductionPlanDetail
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instances = ProductionPlanDetail.getById(id)
        else:
            instances = None
        serializer = ProductionPlanDetailSerializer(instances, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        production = ProductionPlanDetail.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加生产计划明细[%s]，id=%d" % (production.product.product_base.name, production.id),
            validated_data
        )
        return production

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


    def validate(self, data):
        if 'count' in data:
            data['count'] = Formater.formatCount(data['count'])
        data['department'] = None
        if 'product_user' in data and data['product_user']:
            data['department'] = data['product_user'].department
        return data

    def update(self, instance, validated_data):
        instance = super(ProductionPlanDetailSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改生产计划明细[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance


class SalePlanDetailSerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True)
    goods_text = serializers.CharField(source='goods.product_base.name', read_only=True)
    goods_model = serializers.CharField(source='goods.product_base.model', read_only=True)
    require_time_text = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    quality_request_text = serializers.CharField(source='quality_request.name', read_only=True)
    quality_request_id = serializers.CharField(source='quality_request.id', read_only=True)
    current_count = serializers.CharField(source='goods.product_base.stock_count', read_only=True)
    require_production_count = serializers.SerializerMethodField()
    require_count = CountShowCharField()
    price = EmptyPriceShowCharField(allow_blank=True)
    amount = EmptyAmountShowCharField(read_only=True)


    class Meta:
        model = SalePlanDetail
        fields = '__all__'

    @staticmethod
    def factory(user, data):
        instance = None
        serializer = SalePlanDetailSerializer(instance, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        instance = SalePlanDetail.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加销售计划明细[%s]，id=%d" % (instance.goods, instance.id),
            validated_data
        )
        return instance

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

    def get_require_production_count(self, obj):
        require_production_count = 0
        if obj.require_count > obj.goods.product_base.stock_count:
            require_production_count = obj.require_count-obj.goods.product_base.stock_count
        return Formater.formatCountShow(require_production_count)

    def validate(self, data):
        if 'require_count' in data:
            data['require_count'] = Formater.formatCount(data['require_count'])
        if 'price' in data:
            if data['price'] == '':
                data['price'] = None
            else:
                data['price'] = Formater.formatPrice(data['price'])
                data['amount'] = data['require_count'] * data['price']
        return data