# coding=utf-8
import datetime

from celery import shared_task
from django.conf import settings
from django.db.models import Avg
from django.db.models import Q
from helios.rpc import create_default_invoker

from rank.models import DoctorStat
from rank.utils.cache import redis_client


def export_email_task(to_user_email):
    rpc = create_default_invoker(debug=settings.DEBUG)
    rpc['search/doris/export'](to_user_email=to_user_email).unwrap()

def _delete_old_doris_data():
    delete_date = (datetime.datetime.now() - datetime.timedelta(days=3)).strftime('%Y%m%d')
    DoctorStat.objects.filter(stat_date=delete_date).delete()



@shared_task
def doctor_statdata_2_cache():
    stat_date = (datetime.datetime.now() - datetime.timedelta(days=2)).strftime("%Y%m%d")
    for d_s in DoctorStat.objects.filter(stat_date=stat_date).filter(last_30d_uv__gt=0).filter(
            last_30d_payment__gt=0):
        last_30d_uv = d_s.last_30d_uv if d_s.last_30d_uv>100 else 100
        xiadan_index = d_s.last_30d_payment / (last_30d_uv + 1)
        if xiadan_index > 300:
            xiadan_index = 300
        d_s.xiadan_index = xiadan_index
        d_s.save()
    average_xiadan_index = DoctorStat.objects.filter(stat_date=stat_date).filter(last_30d_uv__gte=0).filter(
        last_30d_payment__gte=0).aggregate(Avg('xiadan_index'))['xiadan_index__avg']
    f = Q(last_30d_uv__lt=0) | Q(last_30d_payment__lt=0)
    DoctorStat.objects.filter(f).update(xiadan_index=average_xiadan_index)
    for d_s in DoctorStat.objects.filter(stat_date=stat_date):
        redis_client.set(d_s.redis_key, d_s.stat_json)
    _delete_old_doris_data()