# Create your tasks here
from __future__ import absolute_import, unicode_literals
from apps.pm.models import Mtask, Utask
from apps.utils.tasks import CustomTask
from celery import shared_task
from datetime import datetime, timedelta
from django.db.models import F
from apps.pm.services import PmService

@shared_task(base=CustomTask)
def complete_mtask():
    """
    将2天前未提交的任务且数量已达标的任务标记为已完成
    """
    now = datetime.now().date()
    Mtask.objects.filter(state=Mtask.MTASK_ASSGINED,
                        end_date__lte=now-timedelta(days=2),
                        count_ok__gte=F('count')).update(state=Mtask.MTASK_SUBMIT)
    Mtask.objects.filter(state=Mtask.MTASK_ASSGINED,
                        end_date__lte=now-timedelta(days=7)).update(state=Mtask.MTASK_SUBMIT)

    utasks = Utask.objects.filter(state__in=[Utask.UTASK_ASSGINED, Utask.UTASK_WORKING],
                                  end_date__lte=now-timedelta(days=2))

    for utask in utasks:
        PmService.utask_submit(utask=utask, raise_e=False)