# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db.models import Q
from gm_rpcd.all import bind
from gm_types.gaia import PROBLEM_FLAG_CHOICES, TOPIC_TYPE

from talos.libs.datetime_utils import get_humanize_datetime
from talos.manager.diary import diary_list_manager
from talos.models.topic import TopicReply, Problem
from talos.rpc import to_dict
from talos.services import DoctorService


def model_filter(model, and_filter=None, or_filter=None, order_by=None, values=None, limit=10, is_count=False):
    q = Q()
    if and_filter is not None:
        q &= Q(**and_filter)

    if or_filter is not None:
        q |= Q(**or_filter)

    filtered_instance = model.objects.filter(q)

    if is_count:
        return filtered_instance.count()
    else:
        if order_by is not None:
            ordered_instance = filtered_instance.order_by(order_by)
        else:
            ordered_instance = filtered_instance

        if values is not None:
            ms = list(ordered_instance.values(*values)[:limit])
        else:
            limited_instance = ordered_instance[:limit]
            ms = list(map(lambda t: to_dict(t), limited_instance))

        return ms


@bind('topic/simple_filter')
def topic_simple_filter(and_filter=None, or_filter=None, order_by=None, values=None, limit=10, is_count=False):
    kw = locals()
    model = Problem
    return model_filter(model, **kw)


@bind('topic/count')
def topic_count(user_id):
    topic_filter = Q(flag=PROBLEM_FLAG_CHOICES.NORMAL, is_online=True)
    diary_q = Q(diary__isnull=True) | (
        Q(diary__isnull=False) & Q(diary__is_online=True))
    user_q = Q(user_id=user_id)
    topic_filter = topic_filter & diary_q & user_q
    c = Problem.objects.filter(topic_filter).count()
    return c


@bind('topic/topic_reply/filter')
def topic_reply_filter(and_filter=None, or_filter=None, order_by=None, values=None, limit=10, is_count=False):
    kw = locals()
    model = TopicReply
    return model_filter(model, **kw)


@bind('topic/diary/for_es_query')
def diary_for_es_query(diary_ids, user_id):
    return diary_list_manager.get_diary_list_for_esquery_by_diary_ids(diary_ids, user_id)


@bind('topic/doctor/answer')
def doctor_answer(doctor_id=0):
    results = []
    doctor = DoctorService.get_doctor_from_doctor_id(id=doctor_id)
    if not doctor:
        return results

    # 根据医生来筛选问题
    replies_ids = TopicReply.objects.filter(doctor_id=doctor.id, problem__isnull=False).values_list('id', flat=True).order_by("-id")[:10]
    if replies_ids:
        replies = TopicReply.objects.filter(id__in=list(replies_ids)).order_by("-id")
        count = 0
        for reply in replies:
            if count >= 2:
                break

            if reply.problem.is_offline:
                continue

            item = {
                "topic_id": reply.problem_id,
                "reply_date": get_humanize_datetime(reply.reply_date),
                "my_content": reply.content,
                "old_content": reply.replied_topic.content if reply.replied_topic_id else (
                reply.problem.ask or reply.problem.answer)
            }
            results.append(item)
            count += 1

    return results
