#!/usr/bin/env python
# coding=utf-8
from doctor.models import Notification

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, bind
from gm_types.doctor import NOTIFICATION_TYPE


@bind_context('doctor/notify/last')
def last_noti(ctx, type):
    """
        根据type返回最后一条通知的信息
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    noti = Notification.objects.filter(doctor_id=doctor.id, ntype=type).order_by('-create_time').first()
    if noti:
        return noti.detail_info
    return None


@bind_context('doctor/notify/unread')
def unread(ctx):
    """未读数目"""
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    notis = Notification.objects.filter(doctor_id=doctor.id, is_viewed=False)
    return {'total': notis.count()}


@bind_context('doctor/notify/list')
@list_interface(offset_name='start_num', limit_name='count', element_model=Notification)
def noti_list(ctx, start_num=0, count=10, type=None):
    """
        获取通知列表

        type: 通知的类型，不能为空
    """
    type_arr = [
        NOTIFICATION_TYPE.RESERVATION, NOTIFICATION_TYPE.TRADE,
        NOTIFICATION_TYPE.REFUND, NOTIFICATION_TYPE.USERCASE]
    if type not in type_arr:
        return gen(CODES.NO_PERMISSION)

    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    # 标记未读的为已读
    Notification.objects.filter(doctor_id=doctor.id, ntype=type, is_viewed=False).update(is_viewed=True)

    # 根据 ntype 和 related_item_id 聚合
    notis = Notification.objects.filter(doctor_id=doctor.id, ntype=type).order_by('-create_time')
    data = []
    id_type_arr = []
    for noti in notis:
        id_type = '{}_{}'.format(noti.related_item_type, noti.related_item_id)  # 保证唯一性
        if id_type not in id_type_arr:
            if len(id_type_arr) >= start_num:  # 从start_num开始统计
                if len(id_type_arr) < start_num + count:
                    data.append(noti.detail_info)
                else:
                    break  # 够count个值了，直接跳出循环

            id_type_arr.append(id_type)  # 没有出现过的才记录
    return data


@bind('doctor/notify/create_topic')
def create_topic(doctor_id, topic, count):
    from services.doctor_notify_service import DoctorNotifyService

    ss = DoctorNotifyService.get_service(doctor_id)
    if count == 1:
        ss.notify_user_create_first_topic(topic)
    elif count > 1:
        ss.notify_user_create_topic(topic)
