#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/9/1

from datetime import datetime
from gm_types.gaia import OPERATION_ACTION
from django.core.management import BaseCommand
from api.models import BDTransfer, BDTransferOperationRecord, User


def back_to_public():
    now = datetime.now()
    objs = []
    for bd in BDTransfer.objects.filter(is_assign=True, is_back=False, potential_assess=0):
        if (not bd.single_records.exists()) and bd.current_follow_up_consultant and (now - bd.pooled_time).days >= 7:
            objs.append(bd)

    user = User.objects.get(id=31618301)
    for bd in objs:
        content = u"回抛原因: {}".format(u'超时未转化')
        updates = {"is_assign": False, "assigner": None, 'assigned_time': None,
                   'current_follow_up_consultant': None, "is_back": False, 'pooled_time': datetime.now()}
        for key, value in updates.items():
            setattr(bd, key, value)
        bd.save()
        BDTransferOperationRecord.objects.create(
            bdtransfer=bd, action=OPERATION_ACTION.RETURN, content=content, operate_user=user
        )


def sync_pool_time():
    bd_list_objs = BDTransfer.objects.all()
    counts = BDTransfer.objects.count()
    print("total counts: {nums}".format(nums=counts))
    for bd in bd_list_objs:
        print("left: {left}".format(left=counts - 1))
        if bd.single_records.exists():
            bd.pooled_time = bd.single_records.last().single_time
        elif bd.assigned_time:
            bd.pooled_time = bd.assigned_time
        else:
            bd.pooled_time = bd.create_time
        bd.save()


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        # 同步时间
        sync_pool_time()
        # 退回公池
        # back_to_public()
        print("done!")