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

def main(wprId, mgroup:Mgroup=None):
    wpr = Wpr.objects.get(id=wprId)
    if mgroup is None:
        mgroup_ids = Mlogbw.objects.filter(
            wpr=wpr,
            mlogb__mlog__submit_time__isnull=False,
            mlogb__mlog__is_fix=False
        ).values_list(
            'mlogb__mlog__mgroup', 
            flat=True
        ).distinct()
        mgroups = Mgroup.objects.filter(id__in=mgroup_ids)
    else:
        mgroups = [mgroup]
    data = {}
    for mgroup in mgroups:
        mgroup_name = mgroup.name
        mlogbw = Mlogbw.objects.filter(wpr=wpr, 
            mlogb__mlog__mgroup=mgroup, 
            mlogb__mlog__submit_time__isnull=False, mlogb__mlog__is_fix=False).order_by("-update_time").first()
        if mlogbw:
            mlog:Mlog = mlogbw.mlogb.mlog
            data[f"{mgroup_name}_批次号"] = mlogbw.mlogb.batch
            data[f"{mgroup_name}_设备编号"] = mlog.equipment.number if mlog.equipment else None
            data[f"{mgroup_name}_操作人"] = mlog.handle_user.name if mlog.handle_user else None
            data[f"{mgroup_name}_日期"] = mlog.handle_date.strftime("%Y-%m-%d")
            # 日志操作数据
            if mlog.oinfo_json:
                oinfo_keys = list(mlog.oinfo_json.keys())
                oinfo_keys_qs = TestItem.objects.filter(id__in=oinfo_keys)
                for item in oinfo_keys_qs:
                    data[f"{mgroup_name}_操作项_{item.name}"] = mlog.oinfo_json[item.id]
            # 子工序操作人和日期
            mlogusers = MlogUser.objects.filter(mlog=mlog)
            if mlogusers.exists():
                datab = mlogusers.values("handle_user__name", "process__name", "handle_date", "equipment__name")
                for ind, item in enumerate(datab):
                    data[f"{mgroup_name}_{item['process__name']}_操作人"] = item["handle_user__name"]
                    data[f"{mgroup_name}_{item['process__name']}_日期"] = item["handle_date"].strftime("%Y-%m-%d")
                    if item["equipment__name"]:
                        data[f"{mgroup_name}_{item['process__name']}_使用设备"] = item["equipment__name"]
            # 检测数据
            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"])