#!/usr/bin/env python
# coding=utf-8
import time

from celery import shared_task

from django.db.models import Count
from django.conf import settings

from rpc.cache import doctor_traffic_cache
from rpc.tool.log_tool import doctor_stats_logger
from api.models import Shopcart
from doctor.tool.stats_tool import count_shopcart_prices, gen_shopcart_amount_cache_key


@shared_task
def real_traffic():
    start_time = time.time()

    MIN_TOTAL = 500  # 美购被收藏数大于500才提前缓存
    slave_db = settings.SLAVE_DB_NAME
    need_handles = Shopcart.objects.using(slave_db).filter(service__is_online=True).values('service__doctor').annotate(
        total=Count('service__doctor')
    ).filter(total__gt=MIN_TOTAL).order_by('-total')

    doctor_stats_logger.info('real_traffic_start, count_is>>{}'.format(need_handles.count()))

    for need in need_handles:
        doctor_id = need['service__doctor']
        money = count_shopcart_prices(doctor_id)
        doctor_traffic_cache.set(gen_shopcart_amount_cache_key(doctor_id), money, 86400)  # 缓存1d, task每两个小时更新一次

    end_time = time.time()
    doctor_stats_logger.info('real_traffic_end, user_time>>{}'.format(end_time - start_time))
