from django.db.models.aggregates import Sum
from apps.pm.models import ProductionPlan, SubProductionPlan

class PmService:

    @classmethod
    def update_plan_process_json(cls, plan:ProductionPlan):
        """
        更新计划按工序统计字段
        """
        ret = {}
        subplans = SubProductionPlan.objects.filter(production_plan=plan, is_deleted=False)
        qs = subplans.values('process', 'process__name', 'process__number').annotate(count=Sum('count'), 
        count_real=Sum('count_real'), count_ok=Sum('count_ok'), count_notok=Sum('count_notok'))
        qs_list = list(qs)
        for i in qs_list:
            ret[i['process__number']] = {
                'process':i['process'],
                'process_number':i['process__number'],
                'process_name':i['process__name'],
                'count':i['count'],
                'count_real':i['count_real'],
                'count_ok':i['count_ok'],
                'count_notok':i['count_notok'],
                'rate': round((i['count_ok']/(i['count_ok']+i['count_notok']))*100,2) if (i['count_ok']+i['count_notok']) > 0 else 0
            }
        plan.process_json = ret
        plan.save()

        
