# -*- coding: UTF-8 -*-

from __future__ import unicode_literals, absolute_import, print_function
import datetime
from django.db.models import Count
from rpc.decorators import bind

from api.models import ServiceItem, Order
from api.models import HOSPITAL_TYPE
from api.tool.datetime_tool import add_day, add_month
from api.tool.coupon_tool import get_sku_id_to_doctor_coupon_info_list

def format_sku(sku):
    price_info = sku.get_current_price_info()
    doctor = sku.service.doctor
    hospital = doctor.hospital
    info = {
        'title': sku.service.name,
        'sku_id': sku.id,
        'service_id': sku.service.id,
        'item': u'+'.join(sku.items_name),
        'bd': doctor.business_partener.username,
        'price': {
            'platform': price_info['gengmei_price'],
            'market': price_info['original_price'],
            'prepay': price_info['pre_payment_price'],
            'postpay': price_info['gengmei_price'] - price_info['pre_payment_price'],
        },
        'doctor': {
            'id': doctor.id,
            'name': doctor.name,
            'hospital_id': doctor.hospital.id,
        },
        'hospital': {
            'id': hospital.id,
            'name': hospital.name,
            'city': hospital.city.name,
            'type': HOSPITAL_TYPE.getDesc(hospital.hospital_type),
        }
    }
    return info


@bind('gaia/rival/sku/get')
def sku_get(sku_id):
    sku = ServiceItem.objects.get(id=sku_id)
    info = format_sku(sku)
    return info


@bind('gaia/rival/sku/get_multi')
def sku_get_multi(sku_ids):
    skus = ServiceItem.objects.filter(parent_id=0, id__in=sku_ids)
    sku_infos = {}
    for sku in skus:
        info = format_sku(sku)
        sku_infos[str(sku.id)] = info
    return sku_infos


@bind('gaia/rival/sku/get_doctor_coupon_infos')
def sku_get_multi(sku_ids):
    sku_id_to_coupon_infos = get_sku_id_to_doctor_coupon_info_list(sku_ids)
    return sku_id_to_coupon_infos


@bind('gaia/rival/sku/topsales')
def sku_top_sales(month=None, start=0, step=500):
    if month is None:
        today = datetime.date.today()
        month = add_month(today, -1)
    else:
        try:
            month = datetime.date.strptime('%Y-%m', month)
        except:
            today = datetime.date.today()
            month = add_month(today, -1)
    month = add_day(month, -month.day+1)  # 获取当月第一天

    sku_ids = Order.objects.filter(pay_time__range=[month, add_month(month, 1)])\
        .values_list('service_item_id', flat=True)\
        .annotate(cnt=Count('service_item_id'))\
        .order_by('-cnt')
    skus = ServiceItem.objects.filter(parent_id=0, id__in=list(sku_ids[start: start + step]))
    sku_infos = []
    for sku in skus:
        info = format_sku(sku)
        sku_infos.append(info)
    return sku_infos
