# coding: utf-8
from api.models.hera import SpecialPool
from .es import tzlc
import logging
from api.models.city import City
from search.utils.es import get_es, get_highlight, es_index_adapt, tzlc, get_highlight_query
from rpc.tool.log_tool import search_logger, info_logger
from django.conf import settings
import traceback


def get_special(instance):
    s = instance
    assert isinstance(s, SpecialPool)
    tag_names, info_tags = s.get_tag_names
    res = {
        "id": s.id,
        "name": s.name,
        "is_online": s.is_online,
        "order": s.order,
        "created_time": tzlc(s.created_time),
        "update_time": tzlc(s.update_time),
        "tag_ids": s.get_tag_ids,
        "tag_names": tag_names,
        "info_tags": info_tags,
        "has_position_image": 1 if s.a_position_image or s.b_position_image or s.c_d_position_image else 0
    }
    res['city_info'] = []
    all_city_info = City.objects.filter(is_online=True).values_list("tag_id", flat=True)
    for item in all_city_info:
        score = get_special_score(city_id=item, tag_ids=s.get_tag_ids)
        res['city_info'].append({"city_id": item, "score": score, "scores": score})

    logging.info("get_special_data:%s" % res)
    return res


def get_special_score(city_id, tag_ids):
    try:
        score = 0
        query = {
            "query": {
                "bool": {
                    "must": [
                        {"term": {"is_online": True}}
                    ],
                    "should": [
                        {"terms": {"tagv3_ids": tag_ids}},
                        {"terms": {"second_positions_ids": tag_ids}},
                        {"terms": {"second_solutions_ids": tag_ids}},
                        {"terms": {"second_demands_ids": tag_ids}},
                        {"terms": {"first_demands_ids": tag_ids}},
                        {"terms": {"first_solutions_ids": tag_ids}},
                        {"terms": {"first_positions_ids": tag_ids}}
                    ],
                    "minimum_should_match": 1
                }
            },
            "sort": [
                {'_script': {
                    'lang': "groovy",
                    'script_file': 'sort_service-default',
                    'type': 'number',
                    'params': {
                        'user_city_tag_id': int(city_id)
                    },
                    'order': 'desc',
                    '_cache': True,
                }},
                {'smart_rank2': {'order': 'desc'}}
            ]

        }
        es = get_es()
        index = es_index_adapt(
            index_prefix=settings.ES_INDEX_PREFIX,
            doc_type='service',
            rw='read'
        )
        res = es.search(
            index=index,
            doc_type='service',
            timeout=settings.ES_SEARCH_TIMEOUT,
            body=query,
            from_=0,
            size=6)
        if res['hits']['total']:
            for item in res['hits']['hits']:
                smart_rank2 = item['_source']['smart_rank2']
                score += smart_rank2

        return score
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        return 0
