from apps.wpmw.models import Wpr
from apps.wpm.models import Mlogbw
from apps.qm.models import Ftest, FtestDefect, FtestItem
from rest_framework.exceptions import ParseError
from apps.mtm.models import Mgroup

def main(wprId, mgroup:Mgroup):
    wpr = Wpr.objects.get(id=wprId)
    data = {}
    mgroup_name = mgroup.name
    mlogbw = Mlogbw.objects.filter(wpr=wpr, mlogb__mlog__submit_time__isnull=False).order_by("-update_time").first()
    data[f"{mgroup_name}_批次号"] = mlogbw.mlogb.batch
    data[f"{mgroup_name}_日期"] = mlogbw.mlogb.mlog.handle_date.strftime("%Y-%m-%d")
    ftestitems = FtestItem.objects.filter(ftest__mlogbw_ftest__wpr=wpr,
                                          ftest__mlogbw_ftest__mlogb__mlog__mgroup=mgroup,
                                          ftest__mlogbw_ftest__mlogb__mlog__submit_time__isnull=False,
                                          ftest__mlogbw_ftest__mlogb__mlog__is_fix=False)
    for ftestitem in ftestitems:
        data[f"{mgroup_name}_检测项_{ftestitem.testitem.name}"] = ftestitem.test_val_json
    
    ftestdefects = FtestDefect.objects.filter(ftest__mlogbw_ftest__wpr=wpr,
                                    ftest__mlogbw_ftest__mlogb__mlog__mgroup=mgroup,
                                    ftest__mlogbw_ftest__mlogb__mlog__submit_time__isnull=False,
                                    ftest__mlogbw_ftest__mlogb__mlog__is_fix=False)
    for ftestdefect in ftestdefects:
        data[f"{mgroup_name}_缺陷项_{ftestdefect.defect.name}"] = 1 if ftestdefect.has is True else 0
    
    old_data:dict = wpr.data
    if old_data:
        for item in list(old_data.keys()):
            if f'{mgroup_name}_' in item:
                del old_data[item]
    old_data.update(data)
    wpr.data = old_data
    wpr.save(update_fields=["data"])