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

from rpc.all import get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception


def get_interpose(offset, size, keyword, filters, sort_type, interpose_type):
    tag_ids = []
    city_tag_id = None
    for k, v in filters.items():
        if k == 'area_tag_id' and isinstance(v, (long, int)):
        # if k == 'city_tag_id' and isinstance(v, (long, int)):
            city_tag_id = v
        elif k == 'service_tag_ids' and isinstance(v, list) and v:
            tag_ids = v
        elif k == 'tag_ids' and isinstance(v, list) and v:
            tag_ids = v
        elif k == 'bodypart_tag_id':
            # compatibility
            if isinstance(v, list) and v:
                tag_ids = v
            elif isinstance(v, (int, long)):
                tag_ids.append(v)
    if len(tag_ids) > 1:
        return None

    rpc_invoker = get_rpc_remote_invoker()
    result = rpc_invoker['doris/interpose/get'](
        interpose_type=interpose_type,
        city_tag_id=city_tag_id,
        tag_id=tag_ids[0] if tag_ids else None,
        sort_order=sort_type,
        keyword=keyword,
    ).unwrap()
    if result:
        result = result[offset:offset+size]
    return result


def search_interpose(offset, size, keyword, filters, sort_type, interpose_type):
    try:
        doctor_ids = get_interpose(offset, size, keyword, filters, sort_type, interpose_type)
        if not doctor_ids:
            return None
        res = {
            'hits': {
                'total': len(doctor_ids)
            },
        }
        hits = []
        for doctor_id in doctor_ids:
            hit = {
                '_source': {},
                '_id': doctor_id,
            }
            hits.append(hit)
        res['hits']['hits'] = hits
        return res
    except:
        logging_exception()


def filter_interpose(offset, size, filters, sort_type, interpose_type):
    try:
        doctor_ids = get_interpose(offset, size, None, filters, sort_type, interpose_type)
        if not doctor_ids:
            return None
        res = {
            'doctor_ids': doctor_ids,
            'total_count': len(doctor_ids)
        }
        return res
    except:
        logging_exception()
