from apps.wpm.models import Mlog, WMaterial
from django.db import transaction


def correct_tuihuo_log():
    """
    矫正退火错误日志数据
    """
    mlogs = Mlog.objects.filter(mgroup__name='管料退火', count_use=0)
    for mlog in mlogs:
        try:
            count_use = mlog.count_ok + mlog.count_notok
            material_has = WMaterial.objects.get(
                batch=mlog.batch, material=mlog.material_in, belong_dept=mlog.mgroup.belong_dept)
            material_has.count = material_has.count - count_use
            if material_has.count >= 0:
                if material_has.count == 0:
                    material_has.delete()
                else:
                    material_has.save()
                mlog.count_real = count_use
                mlog.count_use = count_use
                mlog.save()
                print(f'{mlog.id}-矫正成功')
        except Exception as e:
            print(f'{mlog.id}-矫正出错:{e}')
