# coding:utf8

import re
import random
import time, datetime
from celery import shared_task
from gm_types.gaia import YOUNGDOCTOR_CASE_TYPE
from api.models.activity import YoungDoctorCase, YoungDoctorVote
from api.models import YoungDoctorRegistrationer
from rpc.cache import yd_vote
from api.tool.log_tool import logging_exception, info_logger

@shared_task
def update_case_cache():
    info_logger.info('update_case_cache....')
    for case_type in YOUNGDOCTOR_CASE_TYPE:
        case_key = 'case_cache:{}'.format(case_type[0])
        caseids = YoungDoctorCase.objects.filter(
            case_type=case_type[0],
            is_online=True,
            ).exclude(description='').order_by('?').values_list('id', flat=True)

        yd_vote.expire(case_key, -1)
        time.sleep(1)
        if caseids:
            yd_vote.lpush(case_key, *caseids)


@shared_task
def update_vote_info():
    info_logger.info('update_vote_info....')
    real_vote_key = yd_vote.keys('yd_vote:*:real')

    for o in real_vote_key:
        case_id = re.findall('yd_vote:([0-9]*):real', o)
        if not case_id or not case_id[0]:
            continue

        vote_num = yd_vote.get(case_id[0]) or 0
        real_num = yd_vote.get('{}:real'.format(case_id[0])) or 0
        if not vote_num or not real_num:
            continue

        try:
            obj, _ = YoungDoctorVote.objects.get_or_create(case_id=case_id[0])
            obj.vote_num = vote_num
            obj.real_vote = real_num
            obj.last_modify_time = datetime.datetime.now()
            obj.save()
        except:
            logging_exception()


def rest_of_day():
    '''
    当天的剩余秒数
    '''
    today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d")
    tomorrow = today + datetime.timedelta(days=1)
    nowTime = datetime.datetime.now()
    return (tomorrow - nowTime).total_seconds()    # 剩余秒数

FULL_SECONDS = 1800

@shared_task
def watering_vote_count(doctor_id, award_id):
    '''
    青年医生灌水 1905
    '''
    left_sec = rest_of_day()
    full_tag = left_sec < FULL_SECONDS
    result = YoungDoctorRegistrationer.watering_vote_count(doctor_id, award_id, full_tag)
    if result: # 灌满水
        pass
    else:
        watering_vote_count.apply_async((doctor_id, award_id), countdown=random.randint(10, min(FULL_SECONDS, left_sec)))

