# Create your tasks here
from __future__ import absolute_import, unicode_literals
from apps.rpm.models import Rpj, Rpjmember
from apps.rpm.services import rpj_member_leave
from apps.utils.tasks import CustomTask
from celery import shared_task
from django.utils import timezone
from datetime import datetime


@shared_task(base=CustomTask)
def close_rpj_by_leave_time():
    """
    定时关闭相关方入厂项目
    """
    now = timezone.now()
    # 正常结束/其他关闭
    rpjs = Rpj.objects.filter(leave_time__lt=now).exclude(state__in=[Rpj.RPJ_DONE, Rpj.RPJ_CLOSE])
    for i in rpjs:
        if i.state == Rpj.RPJ_WORKING:
            i.state = Rpj.RPJ_DONE
            i.save()
        else:
            i.state = Rpj.RPJ_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, '相关方入厂时间到期')
    
    for m in Rpjmember.objects.filter(rpj__in=rpjs):
        rpj_member_leave(m)

@shared_task(base=CustomTask)
def check_remployee_leave():
    """
    检查相关方是否已经离开
    """
    now = datetime.now()
    now_str = now.strftime('%Y-%m-%d %H:%M:%S')
    from apps.hrm.models import Employee
    eobjs = Employee.objects.filter(type='remployee', third_info__dh_face_card_end__lte=now_str)
    Employee.objects.filter(type='remployee', third_info__dh_face_card_end__lte=now_str).update(job_state=Employee.JOB_OFF)
    for e in eobjs:
        if e.user:
            e.user.is_deleted = True
            e.user.save()
