# coding=utf8
from rpc.decorators import bind_context
from api.tool.user_tool import get_user_from_context
from search.utils.conversation import doctor_search_conversation
from message.utils.db import read_conversation_extra_from_es
from services.unread.stat import UserUnread
from gm_types.msg import CONVERSATION_TYPE, CONVERSATION_ORDER
from rpc.tool.error_code import gen, CODES
from api.models import Doctor


@bind_context('search/conversation/doctor_backend_list', login_required=True)
def conversation_doctor_backend_search(
        ctx, offset=0, size=50, query={}, is_unread=None,
        ask_all=False, search_filters={}, sort_type=CONVERSATION_ORDER.UNREAD):
    """
        added at 7.4.5 search_filters add params user_ids, NOTE user_id must be the related doctors managed by
        logged in officer, type list

        added at 7.4.5 search_filter add params is_star, type boolean
    """
    # TODO Skyler "ask_all"参数一定不要使用!!!! 下个版本去掉
    user = get_user_from_context(ctx)

    user_ids = [user.id, ]
    if 'user_ids' in search_filters and search_filters['user_ids']:
        user_ids = search_filters['user_ids']
        del search_filters['user_ids']

    filters = {
        'user_ids': user_ids,
    }

    if is_unread is not None:
        d = {
            'multi_filter': {
                'is_unread': bool(is_unread),
                'user_ids': user_ids,
            }
        }
        filters.update(d)

    filters.update(search_filters)
    es_result = doctor_search_conversation(offset=offset, size=size, filters=filters, query=query, sort_type=sort_type)

    conversation_ids = []
    conversations = []
    for c in es_result['conversations']:
        conversation_ids.append(c.id)
        conversations.append(c.conversation_info(user))
    conversation_extra = read_conversation_extra_from_es(conversation_ids=conversation_ids)
    for c in conversations:
        if c['id'] in conversation_extra:
            c.update(conversation_extra[c['id']])
        # 初始化未读数, 忽略客服的
        default = 1 if c['is_new'] else 0
        c['unread_num'] = default
        if c['conversation_type'] == CONVERSATION_TYPE.MESSAGE:
            c['unread_num'] = UserUnread(user.id).get_conversation_unread(c['id'], default=default)

    result = {
        'conversation_list': conversations,
        'total_count': es_result['total_count'],
    }

    return result


@bind_context('search/conversation/doctor_backend_list_v2', login_required=False)
def conversation_doctor_backend_search(
        ctx, doctor_id, is_star=None, offset=0, size=50, query={}, is_unread=None,
        ask_all=False, search_filters={}, sort_type=CONVERSATION_ORDER.UNREAD):
    """
        added at 7.4.5 search_filters add params user_ids, NOTE user_id must be the related doctors managed by
        logged in officer, type list

        added at 7.4.5 search_filter add params is_star, type boolean
    """
    # TODO Skyler "ask_all"参数一定不要使用!!!! 下个版本去掉
    # user = get_user_from_context(ctx)

    try:
        user = Doctor.objects.get(pk=doctor_id).user
    except Doctor.DoesNotExist:
        gen(CODES.MESSAGE_UNKNOWN_USER)

    user_ids = [user.id, ]
    if 'user_ids' in search_filters and search_filters['user_ids']:
        user_ids = search_filters['user_ids']
        del search_filters['user_ids']

    filters = {
        'user_ids': user_ids,
    }

    if is_star:
        filters['is_star']=is_star

    if is_unread is not None:
        d = {
            'multi_filter': {
                'is_unread': bool(is_unread),
                'user_ids': user_ids,
            }
        }
        filters.update(d)

    filters.update(search_filters)
    es_result = doctor_search_conversation(offset=offset, size=size, filters=filters, query=query, sort_type=sort_type)

    conversation_ids = []
    conversations = []
    for c in es_result['conversations']:
        conversation_ids.append(c.id)
        conversations.append(c.conversation_info(user,doctor_id=doctor_id))
    conversation_extra = read_conversation_extra_from_es(conversation_ids=conversation_ids)
    for c in conversations:
        if c['id'] in conversation_extra:
            c.update(conversation_extra[c['id']])
        # 初始化未读数, 忽略客服的
        default = 1 if c['is_new'] else 0
        c['unread_num'] = default
        if c['conversation_type'] == CONVERSATION_TYPE.MESSAGE:
            c['unread_num'] = UserUnread(user.id).get_conversation_unread(c['id'], default=default)

    result = {
        'conversation_list': conversations,
        'total_count': es_result['total_count'],
    }

    return result

