# -*- coding: UTF-8 -*-

from random import choice
from django.db.models import F

from rpc.decorators import bind_context, bind, cache_page
from api.util.unread_cache import UserFeedsRead
from api.models import TabOperateV2
from api.tool.user_tool import get_user_from_context
from gm_types.gaia import FEED_SHOW_TYPE
from api.tool.log_tool import hera_feed_logger


@bind_context('api/hera_feed/v1')
def hera_feed_v1(ctx, tab_type, min_position, max_position, platform=None, device_id=None, tab_id=0, city_id=None):
    """

    :param ctx:
    :param tab_type:   用户选择的tab 类型， 精选('choice')， 或者后台配置的 'tab_operate'
    :param min_position:  用户当前会看到的数据卡片索引范围
    :param max_position: 用户当前会看到的数据卡片索引范围
    :param platform:
    :param device_id:
    :param tab_id:   访问的tab id  0 为精选  其他tab_id为后台配置的tab 主键id
    :param city_id:  用户所在城市
    :return:
    """
    user = get_user_from_context(ctx)
    user_read = UserFeedsRead(user, platform=platform, device_id=device_id, tab_type=tab_type, tab_id=tab_id,
                              city_id=city_id)
    data = user_read.load()
    result = []
    for key, val in data.items():
        if key >= min_position and key < max_position:
            if val.get(FEED_SHOW_TYPE.D):
                position_rand = val.get(choice([FEED_SHOW_TYPE.A,FEED_SHOW_TYPE.B,FEED_SHOW_TYPE.C]), val[FEED_SHOW_TYPE.D])
            else:
                position_rand = choice(val.values())
            card_rand = choice(position_rand)
            card_info = {
                "location": key,
                "card_type": card_rand[0],
                "card_id": card_rand[1],
                "image": card_rand[2],
                "width": card_rand[3],
                "height": card_rand[4],
                "transaction_type": card_rand[5]
            }
            result.append(card_info)
    hera_feed_logger.info(
        "卡片位{}到{}未获取到数据，参数为:tab_type:{},tab_id:{},city_id:{},device_id:{},platform:{}," \
            .format(min_position, max_position, tab_type, tab_id, city_id, device_id, platform))
    return {"hera_feed": result}


@bind('api/hera_tab_operate/v1')
@cache_page(120)
def hera_tab_operate_v1():
    """
    返回首页 横滑tab所有的后台配置的tab项
    :return:
    """
    data = {"tab_info": []}
    result = TabOperateV2.objects.filter(is_online=True).annotate(tags_id=F('tags__id')).order_by("rank", "-id").values(
        "name", "id", "tags_id", "rank", "tab_classify")
    temp = {}
    for item in result:
        if item['id'] not in temp:
            temp.update({item['id']: {'id': item['id'], 'rank': item['rank'], 'name': item['name'],
                                      'tags_id': [], 'tab_classify': item['tab_classify']}})
        if item['tags_id']:
            temp[item['id']]['tags_id'].append(item['tags_id'])
    result = list(temp.values())
    result.sort(key=lambda x: (x["rank"]))
    data["tab_info"] = result
    return data
