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

import pickle
import collections
from django.db.models import F
from django.conf import settings
from api.models import FeedOperateV2
from api.tool.get_query import get_feed_query
from rpc.cache import hera_feeds_cache as redis_client
from gm_types.gaia import FEED_SHOW_TYPE, FEED_OPERATE_VERSION
from api.tool.log_tool import hera_feed_logger

TIMEOUT = settings.FEED_CARD_TIMEOUT


class UserFeedsRead(object):
    tpl_key = "feed_{identification}_{tab}_{city}_{relevance_tag}_{plastic_template}_{plastic_tab_type}_v2"
    FEED_POSITION_MAX_CNT = 3

    def __init__(self, user, platform=None, device_id=None, tab_type=None, city_id=None,
                 tab_id=0, version=FEED_OPERATE_VERSION.V1, relevance_tag=None, plastic_template=None,
                 plastic_tab_type=None):
        self.tab_type = tab_type
        self.tab_id = tab_id or 0
        self.platform = platform
        self.device_id = device_id
        self.city_id = city_id
        self.user = user
        self.version = version
        self.relevance_tag = relevance_tag or 0
        self.plastic_template = plastic_template or ""
        self.plastic_tab_type=plastic_tab_type

    def get_query(self):
        query = get_feed_query(self.user, platform=self.platform, device_id=self.device_id, city_id=self.city_id,
                               tab_id=self.tab_id, location=self.tab_type, version=self.version,
                               relevance_tag=self.relevance_tag, plastic_template=self.plastic_template,
                               plastic_tab_type=self.plastic_tab_type)
        return query

    def get_key(self):
        tab = self.tab_type or self.tab_id
        key = self.device_id or 'key'
        return self.tpl_key.format(identification=key, tab=tab, city=self.city_id,
                                   relevance_tag=self.relevance_tag,
                                   plastic_template=self.plastic_template, plastic_tab_type=self.plastic_tab_type
                                   )

    def load(self):
        result = redis_client.get(self.get_key())
        if not result:
            result = self.store()
        return pickle.loads(result)

    def store(self):

        query = get_feed_query(self.user, platform=self.platform, device_id=self.device_id, city_id=self.city_id,
                               tab_id=self.tab_id, location=self.tab_type, version=self.version,
                               relevance_tag=self.relevance_tag, plastic_template=self.plastic_template,
                               plastic_tab_type=self.plastic_tab_type)

        data = FeedOperateV2.objects.filter(query).annotate(minus_1_rank=F('rank') - 1).order_by("rank", "show_type")
        if not data:
            hera_feed_logger.info("未获取到数据query为:{}".format(query))
        # http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=21990723    feed展示策略
        rank_container = collections.defaultdict(dict)
        remove_duplicate_from_feed_D = []
        position = -1
        for item in data:
            """
            补位中不能展示出其他位置配置的卡片。
            remove_duplicate_from_feed_D为当前rank中除了补位以外的卡片。position 记录当前遍历到了哪个rank(用户看到的位置)
            遍历data过程中，当rank发生变化，则更新remove_duplicate_from_feed_D。
            如果遍历到补位中的卡片，则判断是否存在于remove_duplicate_from_feed_D。如果存在，则舍弃这个卡片。
            实现补位中与其他卡片去重

            """

            if item.minus_1_rank == position and item.show_type != FEED_SHOW_TYPE.D:
                remove_duplicate_from_feed_D.append((item.card_type, item.card_id))
            elif item.minus_1_rank != position:
                remove_duplicate_from_feed_D = [(item.card_type, item.card_id)]
                position = item.minus_1_rank
            elif (item.card_type, item.card_id) in remove_duplicate_from_feed_D:
                continue
            else:
                remove_duplicate_from_feed_D.append((item.card_type, item.card_id))

            if item.show_type not in rank_container[item.minus_1_rank]:
                rank_container[item.minus_1_rank].update({item.show_type: []})
            rank_container[item.minus_1_rank][item.show_type].append(
                [
                    #  不要更改以下顺序
                    item.card_type.encode('utf-8'),
                    item.card_id,
                    item.image.encode('utf-8'),
                    item.width,
                    item.height,
                    item.service_type.encode('utf-8'),
                    item.name.encode('utf-8'),
                    item.version_limit.encode('utf-8'),
                ]
            )
        result = pickle.dumps(dict(rank_container))
        redis_client.set(self.get_key(), result, TIMEOUT)
        return result
