from gm_rpcd.all import bind
from gm_types.gaia import SERVICE_ORDER_TYPE
from gm_rpcd.all import bind
from gm_types.doris import RANK_MODE
from recommend.utils.device import get_realtime_interest
from search.utils.service import recall_spu, SMARTRANK_SORT


@bind('dymas/search/query_spu')
def query_spu(query='', user_city_tag_id=None, offset=0, size=10,
              sort_type=SERVICE_ORDER_TYPE.DEFAULT, filters={}, sort_params={}, or_filters=[]):
    if sort_type == SERVICE_ORDER_TYPE.DEFAULT_REALTIME and ('device_id' in sort_params):
        device_id = sort_params['device_id']
        interest_tag = get_realtime_interest(device_id)
        if interest_tag:
            sort_params['interest_tags'] = [interest_tag]
    if user_city_tag_id is not None:
        sort_params['user_city_tag_id'] = user_city_tag_id

    res = recall_spu(
        query=query,
        offset=offset,
        size=size,
        sort_type=sort_type,
        filters=filters,
        sort_params=sort_params,
        or_filters=or_filters
    )
    service_ids = []
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        service_ids.append(item['_source']['id'])

    res = {
        'service_ids': service_ids,
        'total_count': res['hits']['total'],
        'adver_position': {}
        }

    if 'adver_postion' in filters:
        res['adver_position'].update({int(s['_id']): s['fields']['adver_id'][0] for s in res['hits']['hits']})

    if sort_type in SMARTRANK_SORT:
        mode = RANK_MODE.CPC
    else:
        mode = RANK_MODE.DEFAULT
    res['rank_mode'] = mode

    return res
