from rest_framework import serializers

from apps.inm.models import FIFO, FIFOItem, FIFOItemProduct, IProduct, MaterialBatch, WareHouse,Inventory
from apps.qm.models import TestRecord, TestRecordItem

from apps.system.serializers import UserSimpleSerializer
from apps.mtm.serializers import MaterialSimpleSerializer
from django.db import transaction

class WareHouseSerializer(serializers. ModelSerializer):
    create_by_=UserSimpleSerializer('create_by', read_only=True)
    class Meta:
        model = WareHouse
        fields = '__all__'

class WareHouseCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = WareHouse
        fields = ['name', 'number', 'place']

class WareHouseSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = WareHouse
        fields = ['name', 'number', 'place']

class InventorySerializer(serializers. ModelSerializer):
    material_= MaterialSimpleSerializer(source='material', read_only=True)
    warehouse_ = WareHouseSimpleSerializer(source='warehouse', read_only=True)
    class Meta:
        model = Inventory
        fields = '__all__'

class MaterialBatchSerializer(serializers. ModelSerializer):
    material_= MaterialSimpleSerializer(source='material', read_only=True)
    warehouse_ = WareHouseSimpleSerializer(source='warehouse', read_only=True)
    class Meta:
        model = MaterialBatch
        fields = '__all__'

class IProductListSerializer(serializers.ModelSerializer):
    material_= MaterialSimpleSerializer(source='material', read_only=True)
    warehouse_ = WareHouseSimpleSerializer(source='warehouse', read_only=True)
    class Meta:
        model = IProduct
        fields = '__all__'
    

class FIFOListSerializer(serializers.ModelSerializer):
    auditor_ = UserSimpleSerializer(source='auditor', read_only=True)
    create_by_ = UserSimpleSerializer(source='create_by', read_only=True)
    class Meta:
        model=FIFO
        fields = '__all__'

class FIFOItemSerializer(serializers.ModelSerializer):
    warehouse_ = WareHouseSimpleSerializer(source='warehouse', read_only=True)
    material_= MaterialSimpleSerializer(source='material', read_only=True)
    class Meta:
        model= FIFOItem
        fields = '__all__'

class IProductInPurSerializer(serializers.ModelSerializer):
    class Meta:
        model = IProduct
        fields = ['number']
    
class FIFODetailInPurSerializer(serializers.ModelSerializer):
    details = IProductInPurSerializer(many=True, required=False)
    class Meta:
        model = FIFOItem
        fields = ['material', 'count', 'batch', 'details', 'warehouse']

class MaterialBatchQuerySerializer(serializers.Serializer):
    warehouse = serializers.IntegerField(label="仓库ID", required=False)
    materials = serializers.ListField(child=serializers.IntegerField(label="物料ID"), required=False)


class FIFOInPurSerializer(serializers.ModelSerializer):
    """
    采购入库序列化
    """
    details = FIFODetailInPurSerializer(many=True)
    class Meta:
        model = FIFO
        fields = ['details', 'inout_date']

    def create(self, validated_data):
        details = validated_data.pop('details')
        if len(details)>0:
            pass
        else:
            raise serializers.ValidationError('没有入库内容')

        # for i in details:
        #     # 校验批次
        #     try:
        #         if i['batch']:
        #             obj = MaterialBatch.objects.get(batch=i['batch'], material=i['material'])
        #             if obj.warehouse != validated_data['warehouse']:
        #                 raise serializers.ValidationError('批次号{}在其他仓库已存在'.format(i['batch']))
        #     except:
        #         pass
        
        # 创建采购入库
        with transaction.atomic():
            validated_data['type'] = FIFO.FIFO_TYPE_PUR_IN
            obj = FIFO(**validated_data)
            obj.save()
            for i in details:
                if 'details' in i:
                    p_details = i.pop('details')
                    if len(p_details) != i['count']:
                        raise serializers.ValidationError('数目对不上')
                    else:
                        i['fifo'] = obj
                        fifoitem = FIFOItem.objects.create(**i)
                        p_list0 = []
                        for x in p_details:
                            x['material'] = i['material']
                            x['fifoitem'] = fifoitem
                            p_list0.append(FIFOItemProduct(**x))
                        FIFOItemProduct.objects.bulk_create(p_list0)

                        p_list = []
                        for x in p_details:
                            x['material'] = i['material']
                            x['warehouse'] = validated_data['warehouse']
                            x['batch'] = i['batch']
                            p_list.append(IProduct(**x))
                        IProduct.objects.bulk_create(p_list)
                else:
                    i['fifo'] = obj
                    FIFOItem.objects.create(**i)
        return obj



class InmTestRecordItemCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TestRecordItem
        fields = ['form_field', 'field_value', 'is_testok']

class InmTestRecordCreateSerializer(serializers.ModelSerializer):
    record_data = InmTestRecordItemCreateSerializer(many=True)
    fifo_item = serializers.PrimaryKeyRelatedField(queryset=FIFOItem.objects.all(), required=True)
    is_testok = serializers.BooleanField()
    class Meta:
        model = TestRecord
        fields = ['form', 'record_data', 'is_testok', 'fifo_item']


class IProductMtestSerializer(serializers.ModelSerializer):
    class Meta:
        model = IProduct
        fields = ['remark_mtest', 'is_mtestok']