#!/usr/bin/env python
# coding=utf-8
from django.conf import settings

from api.models import Shopcart, ServiceItem
from rpc.cache import doctor_traffic_cache


def get_shopcart_amount(doctor_id):
    """
        根据doctor_id获取医生的 在购物车中sku的金额总数
        1. 先从 doctor.tasks.stats.real_traffic 异步任务缓存中取值
        2. 没有的话 再直接从数据库查找, 结果缓存1min
    """
    cache_key = gen_shopcart_amount_cache_key(doctor_id)
    money = doctor_traffic_cache.get(cache_key)
    if not money:
        money = count_shopcart_prices(doctor_id)
    return int(money)


def gen_shopcart_amount_cache_key(doctor_id):
    return u'{}:shopcart_amount'.format(doctor_id)


def count_shopcart_prices(doctor_id):
    """
        根据doctor_id获取医生的 在购物车中sku的金额总数
        使用 从库 去查询
        use method `get_shppcart_prices(doctor_id)`
    """
    money = 0
    slave_db = settings.SLAVE_DB_NAME
    cache_price = {}
    for sc in Shopcart.objects.using(slave_db).filter(service__doctor_id=doctor_id, service__is_online=True,
                                                      service_item__is_delete=False):
        key = u'{}_{}'.format(sc.service_id, sc.service_item_id)
        if sc.service_item_id:
            item_price = cache_price.get(key)
            if not item_price:
                service_item = ServiceItem.objects.using(slave_db).filter(id=sc.service_item_id).first()
                item_price = service_item.gengmei_price if service_item else 0
                cache_price[key] = item_price
            money += item_price * sc.number
        else:
            service_price = cache_price.get(key)
            if not service_price:
                service_price = sc.service.gengmei_price
                cache_price[key] = service_price
            money += service_price * sc.number
    return money
