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

import json
from collections import defaultdict
from random import choice
from distutils.version import LooseVersion

from django.db.models import F

from gm_types.gaia import (
    FEED_SHOW_TYPE,
    TAB_OPERATE_VERSION,
    FEED_OPERATE_VERSION,
    INDEX_CARD_TYPE
)

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


def version_gte(version, target_version):

    if not target_version or not version:
        return True

    try:
        return LooseVersion(version) >= LooseVersion(target_version)
    except:
        pass

    return False

@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, version=FEED_OPERATE_VERSION.V1,
                 relevance_tag=None, plastic_template=None, plastic_tab_type=None,
                 app_version=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, version=version,
                              relevance_tag=relevance_tag, plastic_template=plastic_template,
                              plastic_tab_type=plastic_tab_type)
    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())

            position_rand = [item for item in position_rand if version_gte(app_version, item[7])]
            if not position_rand:
                hera_feed_logger.info("此处没有符合版本{}要求的数据：{}".format(app_version, json.dumps(val)))
                continue

            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],
                "name": card_rand[6],
                "version_limit": card_rand[7],
            }
            result.append(card_info)

    if not result:
        hera_feed_logger.info(
            "卡片位{}到{}未获取到数据，参数为:tab_type:{},tab_id:{},city_id:{},device_id:{},platform:{},version:{},app_versioon:{}" \
                .format(min_position, max_position, tab_type, tab_id, city_id, device_id, platform, version, app_version))

    return {"hera_feed": result}


@bind('api/hera_tab_operate/v1')
@cache_page(120)
def hera_tab_operate_v2(version=TAB_OPERATE_VERSION.V1):
    """
    返回首页 横滑tab所有的后台配置的tab项
    :return:
    """
    data = {"tab_info": []}
    result = TabOperateV2.objects.filter(is_online=True, version=version).annotate(tags_id=F('tags__id')).order_by("rank", "-id").values(
        "name", "id", "tags_id", "rank", "tab_classify")

    tab_tags_v3 = TabOperateV2TagV3.objects.filter(tab_operate_v2_id__in=list(set([item["id"] for item in result])))
    tab_tags = defaultdict(list)
    for item in tab_tags_v3:
        tab_tags[item.tab_operate_v2_id].append(item.tag_v3_id)

    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'])
        temp[item['id']]["tags_v3_id"] = tab_tags.get(item['id'], [])

    result = list(temp.values())
    result.sort(key=lambda x: (x["rank"]))
    data["tab_info"] = result
    return data


@bind('api/hera_tab_operate/image')
@cache_page(120)
def hera_tab_operate_v2(ids=[]):
    feed_operate_v2 = FeedOperateV2.objects.filter(card_id__in=ids, card_type=INDEX_CARD_TYPE.VISUAL_PAGE)
    result = {}
    for f in feed_operate_v2:
        result[str(f.card_id)] = f.image
    return result
