from django.db.models.signals import post_save
from django.dispatch import receiver
from apps.mtm.models import Material
from apps.pm.models import SubProductionPlan, SubProductionProgress

@receiver(post_save, sender=SubProductionProgress)
def update_subplan_main(sender, instance, created, **kwargs):
    """
    根据生产进度统计表更新子计划进度表相关字段
    """
    if instance.is_main:
        subplan = instance.subproduction_plan
        if created:
            subplan.main_product = instance.material
            subplan.main_count = instance.count
        subplan.main_count_real = instance.count_real
        subplan.main_count_ok = instance.count_ok
        if instance.count_ok >= instance.count and instance.count_ok > 0:
            subplan.state = SubProductionPlan.SUBPLAN_STATE_DONE
        elif instance.count_ok < instance.count and instance.count_ok > 0:
            subplan.state = SubProductionPlan.SUBPLAN_STATE_WORKING
        subplan.save()
        if subplan.main_product.type == Material.MA_TYPE_GOOD:
            # 如果是产品，更新主计划进度
            plan = subplan.production_plan
            plan.count_real = subplan.count_real
            plan.count_ok = subplan.count_ok
            plan.save()
            

            
