# Create your tasks here
from __future__ import absolute_import, unicode_literals
from apps.vm.models import Visit
from apps.utils.tasks import CustomTask
from celery import shared_task
from django.utils import timezone


@shared_task(base=CustomTask)
def close_visit_by_leave_time():
    """
    定时关闭访客入厂项目
    """
    now = timezone.now()
    # 正常结束/其他关闭
    vs = Visit.objects.filter(leave_time__lt=now).exclude(state__in=[Visit.V_DONE, Visit.V_CLOSE])
    for i in vs:
        if i.state in [Visit.V_WORKING, Visit.V_ENTER]:
            i.state = Visit.V_DONE
            i.save()
        else:
            i.state = Visit.V_CLOSE
            i.save()
            # 工单审批如果还未结束，直接关闭
            from apps.wf.models import Ticket
            from apps.wf.services import WfService
            if i.ticket and i.ticket.state != Ticket.TICKET_ACT_STATE_FINISH:
                WfService.close_by_task(i.ticket, '访客入厂时间到期')
