from .models import MaterialBatch, MIOItem
from apps.mtm.models import Material, Mgroup
from apps.system.models import Dept
from rest_framework.exceptions import ParseError
from django.db.models import F, Sum
from django.db import transaction
from .services import InmService

def correct_material_batch():
    """矫正物料批次
    """
    mgroups = Mgroup.objects.all()
    p_dict = {}
    for mgroup in mgroups:
        if mgroup.process:
            processId = mgroup.process.id
            dept: Dept = mgroup.belong_dept
            if processId not in p_dict:
                p_dict[processId] = dept
            else:
                raise ParseError('存在多个同工序的工段：{}'.format(mgroup.name))
    mbs = MaterialBatch.objects.filter(material__type__in=[Material.MA_TYPE_GOOD, Material.MA_TYPE_HALFGOOD], 
    production_dept=None)
    for mb in mbs:
        if mb.material.process:
            processId = mb.material.process.id
            mb.production_dept = p_dict[processId]
            mb.save()


def correct_mb_count_notok():
    """矫正因count_notok未记录导致的错误数据
    """
    mis = MIOItem.objects.filter(mio__state=20, count_notok=0).exclude(
        test_date=None,
        count_notok=F('count_n_zw') + F('count_n_tw') + F('count_n_qp') + F('count_n_wq') + F('count_n_dl') + F('count_n_pb') + F('count_n_dxt') + F('count_n_js') + F('count_n_qx') + F('count_n_zz') + F('count_n_ysq') + F('count_n_hs') + F('count_n_b') + F('count_n_qt')
    )
    for mi in mis:
        count_notok = mi.count_n_zw + mi.count_n_tw + mi.count_n_qp + mi.count_n_wq + mi.count_n_dl + mi.count_n_pb + mi.count_n_dxt + mi.count_n_js + mi.count_n_qx + mi.count_n_zz + mi.count_n_ysq + mi.count_n_hs + mi.count_n_b + mi.count_n_qt
        # 先处理库存
        try:
            with transaction.atomic():
                MIOItem.objects.filter(id=mi.id).update(count_notok=count_notok)
                InmService.update_mb_after_test(mi)
        except ParseError as e:
            MIOItem.objects.filter(id=mi.id).update(test_date=None)
