from django.db.models.expressions import F
from django.db.models.signals import post_save
from apps.mtm.models import Step, SubprodctionMaterial
from apps.pm.models import ProductionPlan, SubProductionPlan, SubProductionProgress
from apps.qm.models import TestRecord
from apps.wf.models import Ticket
from django.dispatch import receiver
from rest_framework import exceptions
from apps.wpm.models import WProduct, WproductFlow, WprouctTicket
from apps.wpm.models import OperationWproduct
from apps.wpm.services import WpmServies


@receiver(post_save, sender=Ticket)
def handleTicket(sender, instance, created, **kwargs):
    if instance.workflow.name == '不合格品审理单':
        if created:
            ticket_data = instance.ticket_data
            """
            创建关联信息表
            """
            obj = WprouctTicket()
            wproduct = WProduct.objects.get(id=ticket_data['wproduct'])
            obj.wproduct = wproduct
            obj.number = wproduct.number
            obj.material = wproduct.material
            obj.step = wproduct.step
            obj.subproduction_plan = wproduct.subproduction_plan
            obj.ticket = instance
            
            # test_record = TestRecord.objects.filter(wproduct=wproduct, is_deleted=False, is_testok=False).order_by('-id').first()
            obj.save()

            # 工单绑定半成品
            wproduct.ticket = instance
            wproduct.save()
            WpmServies.add_wproduct_flow_log(wproduct, 'ticket_create')


        elif instance.act_state == Ticket.TICKET_ACT_STATE_FINISH:
            """
            执行操作决定
            """
            ticket_data = instance.ticket_data
            wt = WprouctTicket.objects.get(ticket=instance)
            wp = wt.wproduct
            decision = WProduct.NG_BACK_WORK
            
            if 'decision_2' in ticket_data and ticket_data['decision_2']:
                decision = ticket_data['decision_2']
            elif 'decision_1' in ticket_data and ticket_data['decision_1']:
                decision = ticket_data['decision_1']


            wp.ng_sign = decision
            wt.decision = decision
            if decision in [WProduct.NG_BACK_WORK, WProduct.NG_BACK_FIX]:
                step = Step.objects.get(id=ticket_data['back_step'])
                wp.step = step
                # 找到当时所属的计划
                sp = SubProductionPlan.objects.filter(ow_subplan__wproduct=wp, 
                ow_subplan__operation__is_submited=True, ow_subplan__operation__step=step).first()
                if sp:
                    wp.subproduction_plan = sp
                    wt.save()
                    wp.ticket = None # 解除当前工单
                    wp.act_state = WProduct.WPR_ACT_STATE_DOWAIT
                    wp.save()                  
                else:
                    raise exceptions.APIException('返回步骤点错误')
    
            elif decision in [WProduct.NG_ACCEPT, WProduct.NG_PERMIT]:
                wp.act_state = WProduct.WPR_ACT_STATE_OK
                wp.ng_sign = decision
                wt.save()
                wp.ticket = None # 解除当前工单
                wp.save()
            
            # 添加日志
            WpmServies.add_wproduct_flow_log(wp, 'ticket_finish')
            # 更新子计划合格进度
            WpmServies.update_subproduction_progress_main(sp=wp.subproduction_plan)
    
