from django.db import transaction
from rest_framework import exceptions, serializers

from apps.inm.models import IProduct
from apps.inm.serializers import IProductListSerializer

from .models import Contract, Customer, Order, Sale, SaleProduct

from apps.mtm.serializers import MaterialSimpleSerializer

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

class CustomerCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ['name', 'address', 'contact', 'contact_phone', 'description']

class CustomerSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ['id', 'name']

class ContractSerializer(serializers.ModelSerializer):
    customer_  = CustomerSimpleSerializer(source='customer', read_only=True)
    class Meta:
        model = Contract
        fields = '__all__'

class ContractSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contract
        fields = ['id', 'name', 'number']

class ContractCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contract
        fields = ['name', 'number', 'amount', 'customer', 'sign_date', 'description']


class OrderCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ['number', 'customer', 'contract', 'product', 'count', 'delivery_date']

class OrderSerializer(serializers.ModelSerializer):
    contract_ =  ContractSimpleSerializer(source='contract', read_only=True)
    customer_  = CustomerSimpleSerializer(source='customer', read_only=True)
    product_  = MaterialSimpleSerializer(source='product', read_only=True)
    class Meta:
        model = Order
        fields = '__all__'

class OrderSimpleSerializer(serializers.ModelSerializer):
    contract_ =  ContractSimpleSerializer(source='contract', read_only=True)
    class Meta:
        model = Order
        fields = '__all__'

class SaleCreateSerializer(serializers.ModelSerializer):
    iproducts = serializers.PrimaryKeyRelatedField(queryset=IProduct.objects.all(), many=True)
    class Meta:
        model = Sale
        fields = ['customer', 'order', 'product', 'iproducts']
    
    def validate(self, attrs):
        order = attrs.get('order', None)
        if order:
            if order.customer:
                attrs['customer'] = order.customer
            attrs['product'] = order.product
        for i in attrs['iproducts']:
            if i.material !=  attrs['product']:
                raise exceptions.APIException('产品选取错误')
        return super().validate(attrs)


class SaleListSerializer(serializers.ModelSerializer):
    customer_ = CustomerSimpleSerializer(source='customer', read_only=True)
    order_ = OrderSimpleSerializer(source='order', read_only=True)
    product_ = MaterialSimpleSerializer(source='product', read_only=True)
    class Meta:
        model = Sale
        fields = '__all__'

class SaleProductListSerializer(serializers.ModelSerializer):
    iproduct_ = IProductListSerializer(source='iproduct', read_only=True)
    class Meta:
        model = SaleProduct
        fields = '__all__'

class SaleProductCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SaleProduct
        fields = ['sale', 'iproduct']

    def create(self, validated_data):
        validated_data['number'] = validated_data['iproduct'].number
        instance = SaleProduct.objects.create(**validated_data)
        instance.sale.count = SaleProduct.objects.filter(sale=instance.sale).count()
        instance.sale.save()
        return instance