import datetime
from gm_rpcd.all import bind, RPCDFaultException
from libs.es import es_query, get_must_query, get_es
from libs.filters import query_by_term
from gm_types.gaia import SERVICE_ORDER_TYPE
from search.utils.service import process_sorting
from hera.services import check_city_in_whitelist
from libs.date import datetime_to_timestamp_millis
from libs.es import es_query, get_must_query
from django.conf import settings
import logging
import time


@bind('dymas/search/guess_you_like_service')
def guess_you_like_service(hospital_id=None, tag_id=None, user_city_info=None,
                           doctor_id=None, offset=0, size=10):
    """

    :param hospital_id:
    :param tag_id:
    :param user_city_info: 用户定位的城市信息 {user_city_tag_id: 用户定位城市的tag id, user_city_id: 用户定位城市的id}
    :param doctor_id:
    :param offset:
    :param size:
    :return:
    """
    es = get_es()

    if hospital_id:
        #  新的逻辑，上线改完之后旧的逻辑要删除
        now = datetime.datetime.now()

        hospital_hitids = _query_service_ids_by_hospital(es, hospital_id, size, now)

        if len(hospital_hitids) < size and tag_id:
            tag_hitids = _query_service_ids_by_tag(es, tag_id, user_city_info, size, now)
            hhids = set(hospital_hitids)
            for hitid in tag_hitids:
                if hitid not in hhids:
                    hospital_hitids.append(hitid)

            hospital_hitids = hospital_hitids[:size]

        return {'service_ids': hospital_hitids}
    else:
        hits = []
        if doctor_id is not None:
            term = {"term": {"doctor.id": doctor_id}}
            res = query_by_term(es, term, offset, size)
            hits.extend(res)

        if tag_id is not None:
            term = {"term": {"closure_tag_ids": tag_id}}
            res = query_by_term(es, term, offset, size)
            hits.extend(res)

        news_ids = list(set(hits))
        news_ids.sort(key=hits.index)

        hitids_slice = news_ids[offset:(offset + size)]
        return {'service_ids': hitids_slice}


def _query_service_ids_by_hospital(es, hospital_id, size, now):
    now = int(time.time())
    f = [
        {"term": {"is_online": True}},
        {"term": {"is_can_be_sold": True}},
        {"range": {"can_sold_time_range.start_time_long": {"lte": now}}},
        {"range": {"can_sold_time_range.end_time_long": {"gt": now}}},
        {"term": {"doctor.hospital.id": hospital_id}}
    ]
    sorting = [
        {'smart_rank2': {'order': 'desc'}},
        {'ordering': {'order': 'asc'}},
        {'start_time': {'order': 'desc'}},
    ]

    q = get_must_query(f)
    q['sort'] = sorting
    logging.info('get _query_service_ids_by_hospital:%s' % q)
    res = es_query('service', q, 0, size, es)
    hits = res['hits']['hits']
    hit_ids = [hit['_source']['id'] for hit in hits]
    return hit_ids


def _query_service_ids_by_tag(es, tag_id, user_city_info, size, now):
    f = [
        {"term": {"is_online": True}},
        {"term": {"is_can_be_sold": True}},
        {"range": {"can_sold_time_range.start_time_long": {"lte": now}}},
        {"range": {"can_sold_time_range.end_time_long": {"gt": now}}}
    ]

    term = {"term": {"closure_tag_ids": tag_id}}
    f.append(term)

    q = get_must_query(f)

    sort_type = SERVICE_ORDER_TYPE.NEARBY_REGION

    user_city_tag_id = user_city_info.get("user_city_tag_id", None)
    user_city_tag_id = user_city_tag_id if user_city_tag_id and user_city_tag_id > 0 else -1
    in_whitelist = check_city_in_whitelist(
        user_city_info['user_city_id']) if "user_city_id" in user_city_info else False

    # TODO
    sort_params = {
        "user_city_tag_id": user_city_tag_id,
        "in_whitelist": in_whitelist
    }
    q['sort'] = process_sorting(sort_type=sort_type, sort_params=sort_params)

    res = es_query('service', q, 0, size, es)
    hits = res['hits']['hits']
    hit_ids = [hit['_source']['id'] for hit in hits]
    return hit_ids
