#!/usr/bin/env python
# coding=utf-8
from doctor.models import Notification, Patient
from api.tool.user_tool import get_doctor_from_context
from rpc.tool.error_code import gen, CODES
from rpc.decorators import bind_context, list_interface
from rpc.cache import doctor_patient_cache

from gm_types.gaia import TYPES, ORDER_STATUS, REFUND_STATUS


@bind_context('doctor/patient/list')
@list_interface(offset_name='start_num', limit_name='count')
def patient_list(ctx, start_num=0, count=10):
    """
        医生患者 since 2.2.0
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    patients = []
    person_ids = doctor_patient_cache.lrange(doctor.id, start_num, start_num+count-1)
    for person_id in person_ids:
        patient = Patient.data(doctor.id, person_id)
        if patient:
            patients.append(patient)
    return patients


@bind_context('doctor/patient/get')
def patient_detail(ctx, id):
    """
        医生患者详情 since 2.2.0
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    return Patient.data(doctor.id, id)


@bind_context('doctor/patient/about_order')
@list_interface(offset_name='start_num', limit_name='count')
def order_notis(ctx, id, start_num=0, count=10):
    """获取患者的购买记录
        购买记录包括：下单、验证、申请退款、退款完成
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    notis = Notification.objects.filter(
            person_id=id, doctor_id=doctor.id, related_item_type__in=[TYPES.ORDER, TYPES.REFUND_ORDER]
        ).order_by('-create_time')
    return [noti.detail_info for noti in notis[start_num: start_num+count]]


@bind_context('doctor/patient/about_diary')
@list_interface(offset_name='start_num', limit_name='count')
def diary_notis(ctx, id, start_num=0, count=10):
    """获取患者的康复日记
        创建或更新日记本的notification
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    notis = Notification.objects.filter(
                    person_id=id, doctor_id=doctor.id, related_item_type=TYPES.DIARY
                ).order_by('-create_time')
    return [noti.detail_info for noti in notis[start_num: start_num+count]]
