from apps.wpm.models import Mlog, BatchSt
from apps.mtm.models import Mgroup
from apps.system.models import Dept
from apps.inm.models import MIOItem
from apps.qm.models import FtestWork
from django.utils import timezone
from datetime import datetime
from server.conf import BASE_PROJECT_CODE

def get_alldata_with_batch_and_store(batch: str):
    """
    获取某个批次的整体生产数据并保存
    """
    if BASE_PROJECT_CODE == "gzerp":
        last_time, data = get_alldata_with_batch(batch)
        bobj, _ = BatchSt.objects.get_or_create(batch=batch, defaults={
            "last_time": last_time
        })
        bobj.last_time = last_time
        bobj.data = data
        bobj.save()

def get_alldata_with_batch(batch: str):
    """
    获取某个批次的整体生产数据
    """
    last_time = timezone.make_aware(datetime(1990, 4, 4, 0, 0, 0))
    data = {"产品批次编号": batch}
    dept7 = Dept.objects.get(name='7车间')
    dept6 = Dept.objects.get(name='6车间')
    dept10 = Dept.objects.get(name='10车间')
    mgroup_blcx = Mgroup.objects.get(name="棒料成型")
    mlogs_blcx_qs = Mlog.objects.filter(submit_time__isnull=False, mgroup=mgroup_blcx, batch=batch)

    mlog_count_fields = Mlog.count_fields()

    if mlogs_blcx_qs.exists():
        data["产品规格"] = []
        data["棒料成型_出料人"] = []
        data["棒料成型_切料人"] = []
        data["棒料成型_备注"] = ""
        for item in mlogs_blcx_qs:
            last_time = item.update_time if item.update_time > last_time else last_time
            data["产品规格"].append(item.material_out)  # 对象
            if item.handle_user:
                data["棒料成型_出料人"].append(item.handle_user)  # 对象
            if item.handle_user_2:
                data["棒料成型_切料人"].append(item.handle_user_2) # 对象
            if item.note:
                data["棒料成型_备注"] = ";".join([data["棒料成型_备注"], item.note])
            for field in mlog_count_fields:
                if getattr(item, field) > 0  or field in ["count_real", "count_ok"]:
                    if f'棒料成型_{field}' not in data:
                        data[f'棒料成型_{field}'] = getattr(item, field)
                    else:
                        data[f'棒料成型_{field}'] += getattr(item, field)
        # 整理棒料成型数据
        data["产品规格"] = list(set(data["产品规格"]))
        data["产品规格"] = ";".join([item.specification for item in data["产品规格"]])
        data["棒料成型_出料人"] = list(set(data["棒料成型_出料人"]))
        data["棒料成型_出料人"] = ";".join([item.name for item in data["棒料成型_出料人"]])
        data["棒料成型_切料人"] = list(set(data["棒料成型_切料人"]))
        data["棒料成型_切料人"] = ";".join([item.name for item in data["棒料成型_切料人"]])
        data["棒料成型_合格率"] = round((data["棒料成型_count_ok"]  * 100/ data["棒料成型_count_real"]), 1)
    
    # 管料成型数据
    mgroup_glcx = Mgroup.objects.get(name="管料成型")
    mlogs_glcx_qs = Mlog.objects.filter(submit_time__isnull=False, mgroup=mgroup_glcx, batch=batch)
    if mlogs_glcx_qs.exists():
        data["产品规格"] = []
        data["管料成型_备注"] = ""
        for item in mlogs_glcx_qs:
            last_time = item.update_time if item.update_time > last_time else last_time
            data["产品规格"].append(item.material_out)  # 对象
            if item.note:
                data["管料成型_备注"] = ";".join([data["管料成型_备注"], item.note])
            for field in mlog_count_fields:
                if getattr(item, field) > 0 or field in ["count_real", "count_ok"]:
                    if f'管料成型_{field}' not in data:
                        data[f'管料成型_{field}'] = getattr(item, field)
                    else:
                        data[f'管料成型_{field}'] += getattr(item, field)
        data["产品规格"] = list(set(data["产品规格"]))
        data["产品规格"] = ";".join([item.specification for item in data["产品规格"]])
        data["管料成型_合格率"] = round((data["管料成型_count_ok"] * 100 / data["管料成型_count_real"]), 1)

    # 7车间生产入库数据/ 8车间中检数据
    mioitem_count_fields = MIOItem.count_fields()
    mioitem_qs = MIOItem.objects.filter(mio__belong_dept=dept7, mio__type="do_in", batch=batch,  mio__submit_time__isnull=False)
    if mioitem_qs.exists():
        data["七车间入库_日期"] = []
        data["七车间入库_车间执行人"] = []
        data["七车间入库_仓库执行人"] = []
        data["七车间入库_检验备注"] = ""
        for item in mioitem_qs:
            last_time = item.update_time if item.update_time > last_time else last_time
            data["七车间入库_日期"].append(item.mio.inout_date)
            if item.test_note:
                data["七车间入库_检验备注"] = ";".join([data["七车间入库_检验备注"], item.test_note])
            if item.mio.mio_user:
                data["七车间入库_车间执行人"].append(item.mio.mio_user)
            if item.mio.do_user:
                data["七车间入库_仓库执行人"].append(item.mio.do_user)
            for field in mioitem_count_fields:
                if getattr(item, field) > 0 or field in ["count", "count_notok"]:
                    if f'七车间入库_{field}' not in data:
                        data[f'七车间入库_{field}'] = int(getattr(item, field))
                    else:
                        data[f'七车间入库_{field}'] += int(getattr(item, field))
        data["七车间入库_合格率"] = round((data["七车间入库_count"] - data["七车间入库_count_notok"]) * 100/ data["七车间入库_count"], 1)
        data["七车间入库_日期"] = list(set(data["七车间入库_日期"]))
        data["七车间入库_日期"] = ";".join([item.strftime("%Y-%m-%d") for item in data["七车间入库_日期"]])
        data["七车间入库_车间执行人"] = list(set(data["七车间入库_车间执行人"]))
        data["七车间入库_车间执行人"] = ";".join([item.name for item in data["七车间入库_车间执行人"]])
        data["七车间入库_仓库执行人"] = list(set(data["七车间入库_仓库执行人"]))
        data["七车间入库_仓库执行人"] = ";".join([item.name for item in data["七车间入库_仓库执行人"]])

    # 十车间入库检验
    mioitem10_qs = MIOItem.objects.filter(mio__belong_dept=dept10, mio__type="do_in", batch=batch,  mio__submit_time__isnull=False)
    if mioitem10_qs.exists():
        
        data["十车间入库_抽检人"] = []
        data["十车间入库_仓库执行人"] = []
        data["十车间入库_日期"] = []
        data["十车间入库_检验备注"] = ""
        for item in mioitem10_qs:
            last_time = item.update_time if item.update_time > last_time else last_time
            if item.test_note:
                data["十车间入库_检验备注"] = ";".join([data["十车间入库_检验备注"], item.test_note])
            if item.mio.do_user:
                data["十车间入库_仓库执行人"].append(item.mio.do_user)
            if item.test_user:
                data["十车间入库_抽检人"].append(item.test_user)
            for field in mioitem_count_fields:
                if getattr(item, field) > 0 or field in ["count", "count_notok", "count_sampling"]:
                    if f'十车间入库_{field}' not in data:
                        data[f'十车间入库_{field}'] = int(getattr(item, field))
                    else:
                        data[f'十车间入库_{field}'] += int(getattr(item, field))
        data["十车间入库_抽检人"] = list(set(data["十车间入库_抽检人"]))
        data["十车间入库_抽检人"] = ";".join([item.name for item in data["十车间入库_抽检人"]])
        if data["十车间入库_count_sampling"] > 0:
            data["十车间入库_抽检合格数"] = data["十车间入库_count_sampling"] - data["十车间入库_count_notok"]
            data["十车间入库_抽检合格率"] = round(data["十车间入库_抽检合格数"] * 100/ data["十车间入库_count_sampling"], 1)
        data["十车间入库_仓库执行人"] = list(set(data["十车间入库_仓库执行人"]))
        data["十车间入库_仓库执行人"] = ";".join([item.name for item in data["十车间入库_仓库执行人"]])
        data["十车间入库_日期"] = list(set(data["十车间入库_日期"]))
        data["十车间入库_日期"] = ";".join([item.strftime("%Y-%m-%d") for item in data["十车间入库_日期"]])
        data["十车间入库_合格数"] = data["十车间入库_count"] - data["十车间入库_count_notok"]
        data["十车间入库_合格率"] = round((data["十车间入库_count"] - data["十车间入库_count_notok"]) * 100/ data["十车间入库_count"], 1)

    # 管料退火生产数据
    mgroup_gltx = Mgroup.objects.get(name="管料退火")
    mlogs_glth_qs = Mlog.objects.filter(submit_time__isnull=False, mgroup=mgroup_gltx, batch=batch)
    if mlogs_glth_qs.exists():
        data["管料退火_日期"] = []
        data["管料退火_操作人"] = []
        data["管料退火_备注"] = ""
        data["产品规格"] = []
        for item in mlogs_glth_qs:
            data["产品规格"].append(item.material_out)
            last_time = item.update_time if item.update_time > last_time else last_time
            if item.note: 
                data["管料退火_备注"] = ";".join([data["管料退火_备注"], item.note])
            if item.handle_date:
                data["管料退火_日期"].append(item.handle_date)
            if item.handle_user:
                data["管料退火_操作人"].append(item.handle_user)
            for field in mlog_count_fields: 
                if getattr(item, field) > 0 or field in ["count", "count_notok"]:
                    if f'管料退火_{field}' not in data:
                        data[f'管料退火_{field}'] = int(getattr(item, field))
                    else:
                        data[f'管料退火_{field}'] += int(getattr(item, field))
        data["管料退火_日期"] = list(set(data["管料退火_日期"]))
        data["管料退火_日期"] = ";".join([item.strftime("%Y-%m-%d") for item in data["管料退火_日期"]])
        data["管料退火_操作人"] = list(set(data["管料退火_操作人"]))
        data["管料退火_操作人"] = ";".join([item.name for item in data["管料退火_操作人"]])
        data["产品规格"] = list(set(data["产品规格"]))
        data["产品规格"] = ";".join([item.specification for item in data["产品规格"]])


    # 六车间领料数据
    mioitem6_qs = MIOItem.objects.filter(mio__belong_dept=dept6, mio__type="do_out", 
                                         batch=batch,  
                                         mio__submit_time__isnull=False)
    if mioitem6_qs.exists():
        data["六车间领料_日期"] = []
        data["六车间领料_车间执行人"] = []
        data["六车间领料_仓库执行人"] = []
        data["产品规格"] = []
        for item in mioitem6_qs:
            data["产品规格"].append(item.material)
            last_time = item.update_time if item.update_time > last_time else last_time
            data["六车间领料_日期"].append(item.mio.inout_date)
            if item.mio.do_user:
                data["六车间领料_仓库执行人"].append(item.mio.do_user)
            if item.mio.mio_user:
                data["六车间领料_车间执行人"].append(item.mio.mio_user)
            for field in mioitem_count_fields:
                if getattr(item, field) > 0:
                    if f'六车间领料_{field}' not in data:
                        data[f'六车间领料_{field}'] = int(getattr(item, field))
                    else:
                        data[f'六车间领料_{field}'] += int(getattr(item, field))
        data["六车间领料_日期"] = list(set(data["六车间领料_日期"]))
        data["六车间领料_日期"] = ";".join([item.strftime("%Y-%m-%d") for item in data["六车间领料_日期"]])
        data["六车间领料_仓库执行人"] = list(set(data["六车间领料_仓库执行人"]))
        data["六车间领料_仓库执行人"] = ";".join([item.name for item in data["六车间领料_仓库执行人"]])
        data["六车间领料_车间执行人"] = list(set(data["六车间领料_车间执行人"]))
        data["六车间领料_车间执行人"] = ";".join([item.name for item in data["六车间领料_车间执行人"]])
        data["产品规格"] = list(set(data["产品规格"]))
        data["产品规格"] = ";".join([item.specification for item in data["产品规格"]])

    # 六车间工段生产数据

    # 六车间工段生产数据
    mgroup_list = ["平头", "粘铁头", "粗中细磨", "抛光", "开槽"]
    for mgroup_name in mgroup_list:
        mgroup = Mgroup.objects.get(name=mgroup_name)
        mlogs_qs = Mlog.objects.filter(submit_time__isnull=False, mgroup=mgroup, batch=batch)
        if mlogs_qs.exists():
            last_time = item.update_time if item.update_time > last_time else last_time
            data[f'六车间_{mgroup_name}_日期'] = []
            data[f'六车间_{mgroup_name}_操作人'] = []
            data[f'六车间_{mgroup_name}_备注'] = ""
            for item in mlogs_qs:
                if item.note:
                    data[f'六车间_{mgroup_name}_备注'] = ";".join([data[f'六车间_{mgroup_name}_备注'], item.note])
                if item.handle_date:
                    data[f'六车间_{mgroup_name}_日期'].append(item.handle_date)
                if item.handle_user:
                    data[f'六车间_{mgroup_name}_操作人'].append(item.handle_user)
                for field in mlog_count_fields:
                    if getattr(item, field) > 0 or field in ["count_ok", "count_real"]:
                        if f'六车间_{mgroup_name}_{field}' not in data:
                            data[f'六车间_{mgroup_name}_{field}'] = getattr(item, field)
                        else:
                            data[f'六车间_{mgroup_name}_{field}'] += getattr(item, field)
            data[f'六车间_{mgroup_name}_日期'] = list(set(data[f'六车间_{mgroup_name}_日期']))
            data[f'六车间_{mgroup_name}_日期'] = ";".join([item.strftime("%Y-%m-%d") for item in data[f'六车间_{mgroup_name}_日期']])
            data[f'六车间_{mgroup_name}_操作人'] = list(set(data[f'六车间_{mgroup_name}_操作人']))
            data[f'六车间_{mgroup_name}_操作人'] = ";".join([item.name for item in data[f'六车间_{mgroup_name}_操作人']])
            data[f'六车间_{mgroup_name}_合格率'] = round(data[f'六车间_{mgroup_name}_count_ok'] * 100/ data[f'六车间_{mgroup_name}_count_real'], 1)

    # 六车间入库/检验数据
    # mioitem6_qs2 = MIOItem.objects.filter(mio__belong_dept=dept6, mio__type="do_in", 
    #                                      batch=batch,  
    #                                      mio__submit_time__isnull=False)
    # if mioitem6_qs2.exists():
    #     data["六车间生产入库_日期"] = []
    #     for item in mioitem6_qs:
    #         data["六车间生产入库_日期"].append(item.mio.inout_date)
    #         for field in mioitem_count_fields:
    #             if getattr(item, field) > 0:
    #                 if f'六车间生产入库_{field}' not in data:
    #                     data[f'六车间生产入库_{field}'] = getattr(item, field)
    #                 else:
    #                     data[f'六车间生产入库_{field}'] += getattr(item, field)
    #     data["六车间生产入库_日期"] = list(set(data["六车间生产入库_日期"]))
    #     data["六车间生产入库_日期"] = ";".join([item.strftime("%Y-%m-%d") for item in data["六车间生产入库_日期"]])

    # 成品检验数据
    ftestwork_count_fields = FtestWork.count_fields()
    ftestwork_qs = FtestWork.objects.filter(batch=batch)
    if ftestwork_qs.exists():
        data["成品检验_日期"] = []
        data['成品检验_检验人'] = []
        for item in ftestwork_qs:
            last_time = item.update_time if item.update_time > last_time else last_time
            if item.test_date:
                data["成品检验_日期"].append(item.test_date)
            if item.test_user:
                data['成品检验_检验人'].append(item.test_user)
            for field in ftestwork_count_fields:
                if field == 'count_notok_json':
                    for k, v in getattr(item, field).items():
                        if f'成品检验_{k}' not in data:
                            data[f'成品检验_{k}'] = v
                        else:
                            data[f'成品检验_{k}'] += v
                else:
                    if getattr(item, field) > 0 or field in ["count", "count_ok"]:
                        if f'成品检验_{field}' not in data:
                            data[f'成品检验_{field}'] = getattr(item, field)
                        else:
                            data[f'成品检验_{field}'] += getattr(item, field)
        data["成品检验_日期"] = list(set(data["成品检验_日期"]))
        data["成品检验_日期"] = ";".join([item.strftime("%Y-%m-%d") for item in data["成品检验_日期"]])
        data['成品检验_检验人'] = list(set(data['成品检验_检验人']))
        data['成品检验_检验人'] = ";".join([item.name for item in data['成品检验_检验人']])
        data['成品检验_合格率'] = round(data['成品检验_count_ok'] * 100/ data['成品检验_count'], 1)
        data["六车间_批次生产合格率"] = round(data["成品检验_count_ok"] * 100/ data["六车间领料_count"], 1)
        if data["棒料成型_count_real"]:
            data["七车间_批次应出合格率"] = round(data["成品检验_count_ok"] * 100/ data["棒料成型_count_real"], 1)

    return last_time, data
        