# coding=utf-8
from django.conf import settings
from gm_protocol.user_protocol import GmProtocol
from helios.rpc import RPCFaultException
from gm_types.gaia import HOT_SEARCH_JUMP_TYPE
from api.tool.log_tool import logging_exception
from rpc.all import get_rpc_remote_invoker


gm_protocol = GmProtocol(settings.BACKEND_API_HOST, settings.WEB_API_HOST)

# 协议映射表
protocol_map = [
    'get_webview',
    'get_webview',
    'get_service_special_list',
    'get_webview',
    'get_activity_detail',
    'get_live_list',
    'get_article',
    'get_question_detail',
    'get_answer_list',
    'get_diary_detail',
    'get_service_list',
    'get_service_detail',
    'get_expert_home',
    'get_hospital_home',
    '',#正常搜索，留空
    'get_webview',              # 新秒杀跳转 common_webview 站位
    'get_webview',              # 新秒杀聚合 common_webview
    'get_webview',              # 新专题聚合 common_webview
]


def zhiboconfig_id_to_channel_id(zhiboconfig_id):
    rpc_client = get_rpc_remote_invoker()
    try:
        live_channel = rpc_client['mimas/live/get_channel_info_by_zhiboconfig_id'](zhiboconfig_id=zhiboconfig_id).unwrap()
    except RPCFaultException:
        live_channel = dict()

    return live_channel.get('channel_id', '')


def format_search_keyword(jump_type, jump_data):
    protocol_url = str()

    if not jump_data or jump_data.startswith("gengmei://"):
        protocol_url = jump_data
    else:
        try:
            # 新人礼包页或网页或秒杀
            method = getattr(gm_protocol, protocol_map[int(jump_type)], None)
            if callable(method):
                if jump_type == HOT_SEARCH_JUMP_TYPE.ZHIBO:
                    jump_data = zhiboconfig_id_to_channel_id(jump_data)
                elif jump_type in [HOT_SEARCH_JUMP_TYPE.NEW_SECKILL,
                                   HOT_SEARCH_JUMP_TYPE.SECKILL_POLYMER,
                                   HOT_SEARCH_JUMP_TYPE.TOPIC_POLYMER]:
                    return jump_data
                protocol_url = method(jump_data)
            else:
                protocol_url = ''
        except (TypeError, ValueError):
            logging_exception()

    return protocol_url
