import json
import logging
import traceback
from datetime import datetime
from libs.es import es_query, get_must_query, get_es, es_msearch, es_index_adapt
from libs.error import logging_exception
from gm_rpcd.all import bind
from search.utils.service import filter_service
from recommend.models import DeviceInterest, DeviceInterestService
from recommend.utils.service import get_hot_service_by_tags, get_point_service_by_diff_tags, \
    get_user_service_portrait2_redis, get_user_history_order_tags
from recommend.utils.device import get_realtime_interest
from search.views.sku import query_sku

from django.conf import settings
from gm_types.gaia import SERVICE_ORDER_TYPE
from search.utils.service import recall_sku
import redis
from libs.cache import redis_client


def get_device_interest(device_id, size=3):
    interest_tags = DeviceInterest.objects.filter(device_id=device_id).order_by("-rank")[0:size]
    return [interest_tag.tag_id for interest_tag in interest_tags]


def get_ensure_service(current_city_tag_id=None, offset=0, size=10):
    filters = {'city_tag_id': current_city_tag_id}
    res = filter_service(offset=offset, size=size, filters=filters)
    return res["service_ids"]


def get_willbuy_tags(device_id):
    tags = set()
    realtime_tag = get_realtime_interest(device_id)
    if realtime_tag:
        tags.add(realtime_tag)

    items = DeviceInterestService.objects.filter(device_id=device_id).order_by("-rank")[0:(settings.MAX_TAG - 1)]
    for item in items:
        tags.add(item.tag_id)
    tags_size = len(tags)
    fill_size = settings.MAX_TAG - tags_size
    if fill_size > 0:
        fill_tags = get_device_interest(device_id, size=fill_size)
        for tag in fill_tags:
            tags.add(tag)
    return list(tags)


# @desc 基于用户兴趣推荐美购
# http://wiki.gengmei.cc/pages/viewpage.action?pageId=4150998
# @rd 郑伟
# @param  device_id 用户手机设备id
# @param  current_city_tag_id 用户美购首页选择城市tag_id
# @param  size 一次推荐多少条美购
# @date 20170616
@bind('dymas/recommend/service')
def recommend_service(device_id, current_city_tag_id=None, sort_type=SERVICE_ORDER_TYPE.DEFAULT, filters={}, offset=0,
                      size=10):
    """
    interest_tags = get_device_interest(device_id)
    #当设备没有兴趣特征时， 使用默认的美购智能排序算法返回头部10个美购
    service_ids = []
    if interest_tags:
        service_ids = get_hot_service_by_tags(interest_tags, area_tag_id=current_city_tag_id, offset=0, size=size)
        recommend_size = len(service_ids)
        if  recommend_size < size: #兜底
            ensure_size = size - recommend_size
            ensure_service_ids = get_ensure_service(current_city_tag_id, ensure_size)
            for service_id in ensure_service_ids:
                if service_id not in service_ids:
                    service_ids.append(service_id)
    if len(service_ids) == 0:
        #兜底
        service_ids = get_ensure_service(current_city_tag_id, 0, size)
    """
    res = recall_sku(
        query='',
        offset=offset,
        size=size,
        sort_type=sort_type,
        filters=filters
    )

    service_ids = list()
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        if 'inner_hits' in item:
            hit = item['inner_hits']
            hit_item = hit['sku_list']['hits']['hits'][0]
            # sku_id = sku['_source']['sku_id']
            service_id = hit_item["_id"]
            service_ids.append(service_id)

    return {"service_ids": service_ids}


@bind("dymas/recommend/interest_tag")
def get_recommend_interest_tag(device_id):
    interest_tags = get_device_interest(device_id)
    return {"interest_tags": interest_tags}


@bind("dymas/willbuy/service")
def tobuy_service(device_id, current_city_tag_id=None, offset=0, size=40):
    tobuy_tags = get_willbuy_tags(device_id)
    service_ids = get_hot_service_by_tags(tobuy_tags, area_tag_id=current_city_tag_id, offset=offset, size=size)
    if len(service_ids) == 0:
        # 兜底
        service_ids = get_ensure_service(current_city_tag_id, offset, size)
    return {'service_ids': service_ids}


# 用户画像相关
# def get_user_portrait_scores(gm_kv_ins, cl_id, size=None):
#     try:
#         cl_id_portrait_key = "user:portrait_tags:cl_id:" + str(cl_id)
#         if gm_kv_ins.exists(cl_id_portrait_key):
#             cl_id_portrait = json.loads(gm_kv_ins.get(cl_id_portrait_key))
#             return cl_id_portrait[:size]
#         else:
#             return []
#     except:
#         logging.error("catch exception,err_msg:%s" % traceback.format_exc())
#         logging_exception()
#         return []
#
#
# def get_user_service_portrait_tags(gm_kv_ins, cl_id, size=None):
#     try:
#         cl_id_portrait_key = "user:service_portrait_tags:cl_id:" + str(cl_id)
#         if gm_kv_ins.exists(cl_id_portrait_key):
#             cl_id_portrait = json.loads(gm_kv_ins.get(cl_id_portrait_key))
#             result = [i['tag2'] for i in cl_id_portrait]
#             return result[:size]
#         else:
#             return []
#     except:
#         logging.error("catch exception,err_msg:%s" % traceback.format_exc())
#         logging_exception()
#         return []


# def get_user_history_order_tags(gm_kv_ins, user_id, size=None):
#     try:
#         user_history_order_tags_key = "user:history_order:tags:user_id:" + str(user_id)
#         if gm_kv_ins.exists(user_history_order_tags_key):
#             user_history_order_tags = json.loads(gm_kv_ins.get(user_history_order_tags_key))
#             return user_history_order_tags[:size]
#         else:
#             return []
#     except:
#         logging.error("catch exception,err_msg:%s" % traceback.format_exc())
#         logging_exception()
#         return []


def get_user_tags_service_ids(user_portrait_scores, had_read_service_list, size, user_city_tag_id, in_whitelist):
    try:
        tags_length = len(user_portrait_scores)
        if tags_length == 1:
            dsize = [size]
        elif tags_length == 2:
            ele_length = size // 2
            dsize = [size - ele_length, ele_length]
        elif tags_length == 3:
            ele_length = size // 3
            dsize = [size - 2 * ele_length, ele_length, ele_length]
        elif tags_length == 4:
            ele_length = size // 4
            dsize = [size - 3 * ele_length, ele_length, ele_length, ele_length]
        elif tags_length == 5:
            ele_length = size // 5
            dsize = [size - 4 * ele_length, ele_length, ele_length, ele_length, ele_length]

        query_body = ""
        service_index_name = es_index_adapt(index_prefix=settings.ES_INDEX_PREFIX, doc_type="service", rw="read")
        service_header_dict = {'index': service_index_name, 'type': "service"}
        for i in range(len(user_portrait_scores)):
            if user_portrait_scores[i]['type'] == 'search_word':
                q = dict()
                q = {'query': {'multi_match': {'query': user_portrait_scores[i]['content'],
                                               'type': 'cross_fields',
                                               'operator': 'and',
                                               'fields': ['short_description^8',
                                                          'name^7',
                                                          'doctor.name^4',
                                                          'doctor.hospital.name^3',
                                                          'hospital.name^3',
                                                          'doctor.hospital.city_name^2',
                                                          'doctor.hospital.city_province_name^2',
                                                          'closure_tags^2']}},
                     'size': dsize[i],
                     '_source': {'includes': ['id']},
                     'filter': {'bool': {'filter': {'term': {'is_online': True}},
                                         'must_not': {'terms': {'id': had_read_service_list}}}},
                     'sort': [
                         {
                             '_script': {
                                 'type': 'number',
                                 'order': 'desc',
                                 "script": {
                                     "id": "service-region-related",
                                     "params": {
                                         "user_city_tag_id": user_city_tag_id,
                                         "in_whitelist": in_whitelist
                                     }
                                 }
                             }
                         },
                         {'smart_rank2': {'order': 'desc'}},
                         {'_score': {'order': 'desc'}}]}
                query_body += "{}\n{}\n".format(json.dumps(service_header_dict), json.dumps(q))
            else:
                q = dict()
                q = {'query': {'bool': {'filter': [{'term': {'closure_tag_ids': user_portrait_scores[i]['content']}},
                                                   {'term': {'is_online': True}}],
                                        'must_not': {'terms': {'id': had_read_service_list}}}},
                     'size': dsize[i],
                     '_source': {'includes': ['id']},
                     'sort': [
                         {
                             '_script': {
                                 'type': 'number',
                                 'order': 'desc',
                                 "script": {
                                     "id": "service-region-related",
                                     "params": {
                                         "user_city_tag_id": user_city_tag_id,
                                         "in_whitelist": in_whitelist
                                     }
                                 }
                             }
                         },
                         {'smart_rank2': {'order': 'desc'}},
                         {'_score': {'order': 'desc'}}]}
                query_body += "{}\n{}\n".format(json.dumps(service_header_dict), json.dumps(q))
        res = es_msearch(query_body, es_hosts_config=settings.ES_SERVICE_HOSTS)
        logging.info("get query:%s" % query_body)
        if res:
            service_ids = []
            for i in res['responses']:
                for j in i['hits']['hits']:
                    service_ids.append(j['_source']['id'])
            return list(set(service_ids))
        else:
            return []

    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        logging_exception()
        return []


def get_service_ids_from_tags(tags, had_read_service_list, size, user_city_tag_id, in_whitelist, offset=0,
                              check_in=False):
    try:
        if check_in:
            q = {'query': {'bool': {'filter': [{'terms': {'closure_tag_ids': tags}},
                                               {'term': {'is_online': True}}],
                                    'must_not': {'terms': {'id': had_read_service_list}}}},
                 '_source': {'includes': ['id']},
                 'sort': [
                     {
                         '_script': {
                             'type': 'number',
                             'order': 'desc',
                             "script": {
                                 "id": "service-region-related",
                                 "params": {
                                     "user_city_tag_id": user_city_tag_id,
                                     "in_whitelist": in_whitelist
                                 }
                             }
                         }
                     },
                     {'smart_rank2': {'order': 'desc'}},
                     {'_score': {'order': 'desc'}}]}
        else:
            q = {'query': {'bool': {'filter': [{'terms': {'closure_tag_ids': tags}},
                                               {'term': {'is_online': True}}],
                                    'must_not': {'terms': {'id': had_read_service_list}}}},
                 '_source': {'includes': ['id']},
                 'sort': [
                     {
                         '_script': {
                             'type': 'number',
                             'order': 'desc',
                             "script": {
                                 "id": "service-region-related",
                                 "params": {
                                     "user_city_tag_id": user_city_tag_id,
                                     "in_whitelist": in_whitelist
                                 }
                             }
                         }
                     },
                     {
                         "sku_list.price": {
                             "order": "asc",
                             "mode": "min",
                             "nested_path": "sku_list",
                             "nested_filter": {
                                 "bool": {
                                     "must": [
                                         {
                                             "range": {
                                                 "sku_list.start_time": {"lte": "now"}
                                             }
                                         },
                                         {
                                             "range": {
                                                 "sku_list.end_time": {"gt": "now"}
                                             }
                                         }
                                     ]
                                 }
                             }
                         }
                     },
                     {'smart_rank2': {'order': 'desc'}},
                     {'_score': {'order': 'desc'}}]}
        res = es_query("service", q, offset, size)
        logging.info("get  res:%s" % q)
        if res:
            service_ids = [i['_source']['id'] for i in res['hits']['hits']]
            if len(service_ids) == size:
                return service_ids
            else:
                return []
        else:
            return []
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        logging_exception()
        return []


def get_tags_from_service_ids(service_ids):
    try:
        q = {"query": {"bool": {"must": {"terms": {"id": service_ids}}}},
             "_source": {"includes": ["closure_tag_ids"]}}
        size = len(service_ids)
        res = es_query("service", q, 0, size)
        if res:
            service_tags = []
            for i in res['hits']['hits']:
                if 'closure_tag_ids' in i['_source']:
                    service_tags.extend(i['_source']['closure_tag_ids'])
            if service_tags:
                return list(set(service_tags))
            else:
                return []
        else:
            return []
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        logging_exception()
        return []


def supplement_service_ids(user_city_tag_id, in_whitelist, had_read_service_list, size):
    try:
        q = {'query': {'bool': {'filter': [{'term': {'is_online': True}}],
                                'must_not': {'terms': {'id': had_read_service_list}}}},
             '_source': {'includes': ['id']},
             'sort': [
                 {
                     '_script': {
                         'type': 'number',
                         'order': 'desc',
                         "script": {
                             "id": "service-region-related",
                             "params": {
                                 "user_city_tag_id": user_city_tag_id,
                                 "in_whitelist": in_whitelist
                             }
                         }
                     }
                 },
                 {'smart_rank2': {'order': 'desc'}},
                 {'_score': {'order': 'desc'}}]}
        res = es_query("service", q, 0, size)
        logging.info("get  res:%s" % q)
        if res:
            service_ids = [i['_source']['id'] for i in res['hits']['hits']]
            if len(service_ids) == size:
                return service_ids
            else:
                return []
        else:
            return []
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        logging_exception()
        return []


@bind('dymas/recommend/order/service')
def get_recommend_order_service(service_ids, query_params):
    # params
    try:
        user_id = query_params['user_id']
        cl_id = query_params['cl_id']
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        start_num = query_params['start_num']
        size = query_params['size']
        in_whitelist = query_params['in_whitelist']

        # gm_kv_ins = None
        # for gm_kv_host_item in settings.GM_KV_HOSTS:
        #     gm_kv_ins = redis.Redis(host=gm_kv_host_item["host"], port=gm_kv_host_item["port"],
        #                             db=gm_kv_host_item["db"], password=gm_kv_host_item["password"], socket_timeout=2)
        #     if gm_kv_ins:
        #         break
        # 过滤已读
        had_read_service_list = []
        had_read_service_list_key = "doris:recommend:order:service:user_id:" + str(user_id)
        had_read_service_list.extend(service_ids)
        if redis_client.exists(had_read_service_list_key):
            p = redis_client.smembers(had_read_service_list_key)
            if len(p) > 100:
                redis_client.delete(had_read_service_list_key)
            else:
                redis_had_read_service_list = list(map(int, p))
                had_read_service_list.extend(redis_had_read_service_list)
        if service_ids:
            redis_client.sadd(had_read_service_list_key, *service_ids)

        # 可推荐标签组
        history_order_tags = []
        current_order_tags = []
        user_portrait_scores = []
        user_portrait_tags = []
        if user_id:
            history_order_tags = get_user_history_order_tags(user_id)
        if service_ids:
            current_order_tags = get_tags_from_service_ids(service_ids)
            history_order_tags.extend(current_order_tags)
        if cl_id:
            user_portrait_tags = get_user_service_portrait2_redis(cl_id, n=10)
        available_service_tags = list(set(user_portrait_tags).difference(set(history_order_tags)))
        logging.info("doris:recommend:order:service:cl_id:{}:user_portrait_tags:{}:history_order_tags:{}"
                     .format(cl_id, user_portrait_tags, history_order_tags))
        recommend_service_ids = get_service_ids_from_tags(available_service_tags, had_read_service_list, size,
                                                          user_city_tag_id, in_whitelist, check_in=True)
        if len(recommend_service_ids) < size:
            had_read_service_list.extend(recommend_service_ids)
            size = size - len(recommend_service_ids)
            supplement = supplement_service_ids(user_city_tag_id, in_whitelist, had_read_service_list, size)
            recommend_service_ids += supplement
        if recommend_service_ids:
            redis_client.sadd(had_read_service_list_key, *recommend_service_ids)
        logging.info("doris:recommend:order:service:recommend_service_ids:{}".format(recommend_service_ids))
        return {"service_ids": recommend_service_ids}
    except:
        logging.error("dymas/recommend/order/service,catch exception,err_msg:%s" % traceback.format_exc())
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        start_num = query_params['start_num']
        size = query_params['size']
        res_service_ids = get_ensure_service(user_city_tag_id, start_num, size)
        logging_exception()
        return {"service_ids": res_service_ids}


@bind('dymas/recommend/shopcart/service')
def get_recommend_shopcart_service(service_ids, query_params):
    try:
        # params
        user_id = query_params['user_id']
        cl_id = query_params['cl_id']
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        start_num = query_params['start_num']
        size = query_params['size']
        in_whitelist = query_params['in_whitelist']
        check_in = False
        if "check_in" in query_params:
            check_in = query_params["check_in"]

        # gm_kv_ins = None
        # for gm_kv_host_item in settings.GM_KV_HOSTS:
        #     gm_kv_ins = redis.Redis(host=gm_kv_host_item["host"], port=gm_kv_host_item["port"],
        #                             db=gm_kv_host_item["db"], password=gm_kv_host_item["password"], socket_timeout=2)
        #     if gm_kv_ins:
        #         break
        logging.info("doris:recommend:shopcart:service:cl_id:{}:query_params:{}:service_ids:{}"
                     .format(cl_id, query_params, service_ids))
        # 已读
        had_read_service_list = []
        had_read_service_list_key = "doris:recommend:shopcart:service:user_id:" + str(user_id)
        had_read_service_list.extend(service_ids)
        if redis_client.exists(had_read_service_list_key):
            p = redis_client.smembers(had_read_service_list_key)
            if len(p) > 100:
                redis_client.delete(had_read_service_list_key)
            else:
                redis_had_read_service_list = list(map(int, p))
                had_read_service_list.extend(redis_had_read_service_list)
        if service_ids:
            redis_client.sadd(had_read_service_list_key, *service_ids)

        # 可推荐标签组
        shopcart_tags = []
        history_order_tags = []
        user_portrait_tags = []
        if service_ids:
            shopcart_tags = get_tags_from_service_ids(service_ids)
        if cl_id:
            user_portrait_tags = get_user_service_portrait2_redis(cl_id, n=10)
            user_portrait_tags += shopcart_tags
        if user_id:
            history_order_tags = get_user_history_order_tags(user_id)
        available_service_tags = list(set(user_portrait_tags).difference(set(history_order_tags)))
        logging.info("doris:recommend:shopcart:service:cl_id:{}:user_portrait_tags:{}:history_order_tags:{}"
                     .format(cl_id, user_portrait_tags, history_order_tags))
        recommend_service_ids = get_service_ids_from_tags(available_service_tags, had_read_service_list, size,
                                                          user_city_tag_id, in_whitelist, check_in=check_in)
        if len(recommend_service_ids) < size:
            had_read_service_list.extend(recommend_service_ids)
            size = size - len(recommend_service_ids)
            supplement = supplement_service_ids(user_city_tag_id, in_whitelist, had_read_service_list, size)
            recommend_service_ids += supplement
        if recommend_service_ids:
            redis_client.sadd(had_read_service_list_key, *recommend_service_ids)
        logging.info("doris:recommend:shopcart:service:recommend_service_ids:{}".format(recommend_service_ids))
        return {"service_ids": recommend_service_ids}
    except:
        logging.error("dymas/recommend/shopcart/service,catch exception,err_msg:%s" % traceback.format_exc())
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        start_num = query_params['start_num']
        size = query_params['size']
        res_service_ids = get_ensure_service(user_city_tag_id, start_num, size)
        logging_exception()
        return {"service_ids": res_service_ids}


@bind('dymas/recommend/point/service')
def get_recommend_point_service(service_ids, query_params):
    try:
        user_id = query_params['user_id']
        cl_id = query_params['cl_id']
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        start_num = query_params['start_num']
        size = query_params['size']
        in_whitelist = query_params['in_whitelist']
        logging.info("/recommend/point/service" + str(query_params))

        gm_kv_ins = None
        for gm_kv_host_item in settings.GM_KV_HOSTS:
            gm_kv_ins = redis.Redis(host=gm_kv_host_item["host"], port=gm_kv_host_item["port"],
                                    db=gm_kv_host_item["db"], password=gm_kv_host_item["password"], socket_timeout=2)
            if gm_kv_ins:
                break
        logging.info("gm_kv_info:" + str(gm_kv_ins))
        # 过滤已读
        had_read_service_list = []
        had_read_service_list_key = "doris:recommend:point:service:user_id:" + str(user_id)
        if gm_kv_ins.exists(had_read_service_list_key):
            p = gm_kv_ins.smembers(had_read_service_list_key)
            if len(p) > 100:
                gm_kv_ins.delete(had_read_service_list_key)
            else:
                redis_had_read_service_list = list(map(int, p))
                had_read_service_list.extend(redis_had_read_service_list)
        logging.info("/recommend/point/service:" + str(had_read_service_list))
        # 召回
        point_hot_tags_key = "doris:recommend:point:service:hot:tags:type2"
        if gm_kv_ins.exists(point_hot_tags_key):
            point_hot_tags_dict = json.loads(gm_kv_ins.get(point_hot_tags_key))
            point_hot_tags = [i['id'] for i in point_hot_tags_dict]
        else:
            point_hot_tags = []
        logging.info("/recommend/point/service:" + str(point_hot_tags))

        user_service_portrait_tags_key = "user:service_portrait_tags:cl_id:" + str(cl_id)
        if gm_kv_ins.exists(user_service_portrait_tags_key):
            user_service_portrait_tags_dict = json.loads(gm_kv_ins.get(user_service_portrait_tags_key))
            user_service_portrait_tags = [i['tag2'] for i in user_service_portrait_tags_dict]
        else:
            user_service_portrait_tags = []

        logging.info("/recommend/point/service:" + str(user_service_portrait_tags))
        service_ids = []
        if not user_service_portrait_tags:
            service_ids = get_point_service_by_diff_tags(point_hot_tags, point_hot_tags, had_read_service_list, size,
                                                         user_city_tag_id, in_whitelist)
        else:
            service_ids = get_point_service_by_diff_tags(point_hot_tags, user_service_portrait_tags,
                                                         had_read_service_list, size, user_city_tag_id, in_whitelist)
        if len(service_ids) < size:
            size = size - len(service_ids)
            had_read_service_list.extend(service_ids)
            supplement_ids = get_point_service_by_diff_tags(point_hot_tags, point_hot_tags, had_read_service_list, size,
                                                            user_city_tag_id, in_whitelist)
            service_ids.extend(supplement_ids)
        logging.info("recommend/point/service:device:{}:service_ids:{}".format(cl_id, service_ids))
        gm_kv_ins.sadd(had_read_service_list_key, *service_ids)
        return {"service_ids": service_ids}
    except:
        logging.error("dymas/recommend/point/service,catch exception,err_msg:%s" % traceback.format_exc())
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        start_num = query_params['start_num']
        size = query_params['size']
        service_ids = get_ensure_service(user_city_tag_id, start_num, size)
        logging_exception()
        return {"service_ids": service_ids}


# 小程序签到页面美购展示接口
@bind('dymas/recommend/views/wechat_check_in')
def wechat_check_in(query_params):
    try:
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        size = query_params['size']
        # in_whitelist = query_params['in_whitelist']
        tag_key = "wechat_check_in_meigou_tags"
        filters = {}
        if redis_client.exists(tag_key):
            tags = list(redis_client.smembers(tag_key))
            tags = [int(i) for i in tags]
            filters = {"tag_ids": tags}
        data_dict = query_sku(user_city_tag_id=user_city_tag_id, size=size, sort_params=query_params, filters=filters,
                              offset=10, query_type="wechat_check_in")
        return {"service_ids": data_dict["service_ids"]}
    except:
        logging.error("dymas/recommend/views/wechat_check_in,catch exception,err_msg:%s" % traceback.format_exc())
        return {"service_ids": []}


# 美购app签到接口
@bind('dymas/recommend/views/check_in')
def check_in_service_ids(query_params):
    try:
        # params
        # device_id = query_params['device_id']
        user_city_tag_id = query_params['user_city_tag_id']
        if user_city_tag_id is None:
            user_city_tag_id = -1
        size = query_params['size']
        # in_whitelist = query_params['in_whitelist']
        tag_key = "wechat_check_in_meigou_tags"
        filters = {}
        if redis_client.exists(tag_key):
            tags = list(redis_client.smembers(tag_key))
            tags = [int(i) for i in tags]
            filters = {"tag_ids": tags}
        data_dict = query_sku(user_city_tag_id=user_city_tag_id, size=size, sort_params=query_params, filters=filters,
                              offset=10, query_type="check_in")
        return {"service_ids": data_dict["service_ids"]}
    except:
        logging.error("dymas/recommend/views/check_in,catch exception,err_msg:%s" % traceback.format_exc())
        logging_exception()
        return {"service_ids": []}
