# Create your tasks here
from __future__ import absolute_import, unicode_literals
from apps.opm.models import Operation, Opl
from apps.utils.tasks import CustomTask
from celery import shared_task

from apps.wf.models import Ticket

@shared_task(base=CustomTask)
def correct_operation_state():
    """
    矫正作业状态
    """
    for op in Operation.objects.filter(state=Operation.OP_AUDIT):
        need_backs = []
        for opl in Opl.objects.filter(operation=op):
            if (opl.ticket is None) or (opl.ticket and opl.ticket.state.type == 1): # 如果在初始状态
                need_backs.append(True)
            else:
                need_backs.append(False)
        if False in need_backs:
            pass
        else:
            Operation.objects.filter(id=op.id).update(state=Operation.OP_CREATE)

# @shared_task(base=CustomTask)
# def opl_audit_start(ticket_id):
#     operation = Opl.objects.get(ticket__id=ticket_id).operation
#     if operation.state == Operation.OP_CREATE:
#         operation.state = Operation.OP_AUDIT
#         operation.save()


# @shared_task(base=CustomTask)
# def opl_audit_end(ticket_id):
#     opl = Opl.objects.get(ticket__id=ticket_id)
#     operation = opl.operation
#     if operation.state == Operation.OP_AUDIT:
#         operation.state = Operation.OP_WORK
#         operation.save()
    # 授予区域或围栏权限
