# coding=utf-8
# create by oldman at 2018/4/20
import datetime

from hippo.models.businessdata import BusinessData, ToHospital
from hippo.tool.user_tool import get_doctor_from_context
from hippo.utils import get_merchant
from rpc.decorators import bind_context


@bind_context('doctor/business_data/get')
def get_business_data(ctx, time_type):
    """

    :param ctx:
    :param time_type:当月为1， 三个月内为2，六个月为3
    :return:仪表盘数据
    """
    doctor = get_doctor_from_context(ctx)
    merchant = get_merchant(doctor_id=doctor.id)
    business_data = BusinessData.objects.get(merchant=merchant, time_type=time_type)
    return business_data.get_data()


@bind_context('doctor/business_data/get_to_hospital')
def get_to_the_hospital(ctx, start_time, end_time):
    """
    获取医生的到院数据
    :param ctx:
    :param start_time:
    :param end_time:
    :return:
    """
    doctor = get_doctor_from_context(ctx)
    merchant = get_merchant(doctor_id=doctor.id)
    res = ToHospital.objects.filter(merchant_id=merchant.id,
                                    tohospital_time__gte=start_time,
                                    tohospital_time__lte=end_time).order_by(
        'tohospital_time')

    data_dict = {}
    data_res = []
    for item in res:
        data_dict[item.tohospital_time.strftime('%Y-%m-%d')] = item.num
    start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d')
    end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d')
    begin = start_time
    while begin <= end_time:
        num = data_dict.get(begin.strftime('%Y-%m-%d'), 0)
        data_res.append({
            'time': begin.strftime('%Y-%m-%d'),
            'num': num
        })
        begin = begin + datetime.timedelta(days=1)
    return data_res


@bind_context('doctor/business_data/go_to_hospital')
def update_to_the_hospital(ctx, data_info):
    doctor = get_doctor_from_context(ctx)
    merchant = get_merchant(doctor_id=doctor.id)
    for item in data_info:
        to_hospital, _ = ToHospital.objects.get_or_create(
            merchant_id=merchant.id,
            tohospital_time=item['time'],
            doctor_id=doctor.id
        )
        to_hospital.num = item['num']
        to_hospital.save()
