# coding=utf-8
from __future__ import unicode_literals, absolute_import

from dateutil.parser import parse
from django.conf import settings
from gm_types.gaia import HODGEPODGE_ORDER_TYPE
from gm_types.gaia import MULTITOPIC_REVIEW_TYPE
from rpc.decorators import cache_page

from .es import es_multi_index_adapt
from .es import get_es


def process_filters(filters):
    f = [
        {'term': {'is_online': True}},
    ]
    for k, v in filters.iteritems():
        if k == 'in_whitelist':
            f.append({
                'term': {'in_whitelist': v}
            })
        if k == 'in_multitopic':
            f.append({
                'term': {'in_multitopic': v}
            })
    return f


def process_sorting(sort_type):
    # 机构罚单下沉
    sort = [
        {
            '_script': {
                'lang': settings.ES_SCRIPT_LANG,
                'script_file': 'sort_question-sink-by-org',
                'type': 'number',
                'order': 'asc',
            }
        }
    ]
    if sort_type == HODGEPODGE_ORDER_TYPE.POPULAR:  # 热门
        sort += [
            {'_script': {
                'lang': settings.ES_SCRIPT_LANG,
                'script_file': 'sort_hodgepodge-popular',  # 回复数不足3打到最后
                'type': 'number',
                'order': 'desc',
            }},
            {'last_update_time': {'order': 'desc'}},
        ]

    elif sort_type == HODGEPODGE_ORDER_TYPE.LASTEST:  # 最新
        sort += [
            {'_script': {
                'lang': settings.ES_SCRIPT_LANG,
                'script_file': 'sort_hodgepodge-lastest',
                'type': 'number',
                'order': 'desc',
            }},
        ]
    return sort


@cache_page(600)
def hodgepodge_filter(offset=0, size=5, sort_type=HODGEPODGE_ORDER_TYPE.LASTEST, filters=None, sort_params=None):
    size = min(size, settings.COUNT_LIMIT)
    filters = filters or {}
    f = process_filters(filters)
    sort = process_sorting(sort_type=sort_type)
    doc_type_list = ['problem', 'question']
    q = {
        'query': {'filtered': {
            'query': {'match_all': {}},
            'filter': {'bool': {'must': f}}
        }},
        'sort': sort,
    }

    es = get_es()

    indexes = es_multi_index_adapt(
        index_prefix=settings.ES_INDEX_PREFIX,
        doc_type_list=doc_type_list,
        rw='read'
    )

    res = es.search(
        index=indexes,
        doc_type=['problem', 'question'],
        timeout=settings.ES_SEARCH_TIMEOUT,
        body=q,
        from_=0,
        size=settings.HODGEPODGE_TOP)
    problem_filters = {}
    for idx, hit in enumerate(res['hits']['hits']):
        if hit['_type'] == 'problem' and hit['_source'].get('diary_id'):
            if hit['_source']['diary_id'] in problem_filters:

                if parse(hit['_source']['created_time']) > problem_filters[hit['_source']['diary_id']][0] and hit['_source']['replys_num'] > 3:

                    res['hits']['hits'][problem_filters[hit['_source']['diary_id']][
                        1]] = None  # replace with new problem id that has a larger created_time
                    problem_filters.update(
                        {
                            hit['_source']['diary_id']: (parse(hit['_source']['created_time']), idx)
                        }
                    )
                else:
                    res['hits']['hits'][idx] = None
            else:
                problem_filters.update(
                    {
                        hit['_source']['diary_id']: (parse(hit['_source']['created_time']), idx)
                    }
                )

    res['hodgepodge_ids'] = []
    for hit in res['hits']['hits']:
        if not hit:
            continue
        res['hodgepodge_ids'].append(
            {
                'hodgepodge_type': MULTITOPIC_REVIEW_TYPE.PROBLEM if
                hit['_type'] == 'problem'else MULTITOPIC_REVIEW_TYPE.QUESTION,
                'hodgepodge_id': hit['_source']['id']
            }
        )
    # size = min(size, settings.COUNT_LIMIT)
    res['hodgepodge_ids'] = res['hodgepodge_ids'][offset: offset + size]
    res['total_count'] = int(res['hits']['total'])
    return res
