#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals, absolute_import, print_function
import json
from datetime import datetime, timedelta

from rpc.decorators import bind_context
from api.tool.user_tool import get_user_from_context

from polymer.models import Polymer, PolymerExtra
from relation.models import UserTagRelation

from polymer.views.polymer import cache_polymer_type_disscuss
from polymer.views.polymer import cache_polymer_follow_num
from polymer.views.polymer import cache_polymer_discuss_follow_num

from rpc.cache import common_cache as redis_client
from gm_types.gaia import USER_TAG_CHOICES


@bind_context("api/polymer/recommend_zones")
def recommend_polymer(ctx, device_id, count=3):
    user = get_user_from_context(ctx)

    # 用户关注的小组
    polymer_info_list = []
    if user:
        user_follow_tag_list = UserTagRelation.objects.filter(user_id=user.id,
                                                              related_tag__is_online=True,
                                                              tag_type=USER_TAG_CHOICES.FOLLOWED)\
                                                        .values_list("related_tag_id", flat=True)
        if user_follow_tag_list:
            polymer_info_list = Polymer.objects.filter(tags__id__in=user_follow_tag_list,
                                                       is_online=True).values_list("id", flat=True)

    # 遍历讨论类型小组，过滤出用户未关注的讨论小组,并增加关注数字段
    polymer_type_disscuss = cache_polymer_type_disscuss()
    recommend_polymer = []
    for i in polymer_type_disscuss:
        if i["id"] not in polymer_info_list:
            recommend_polymer.append(i)

    # 获取小组互动数
    polymer_id_list = [x["id"] for x in recommend_polymer]
    polymer_interactive_list = PolymerExtra.objects.filter(polymer_id__in=polymer_id_list) \
        .values("polymer_id", "total_cnt")

    # 将小组互动数字加入recommend_polymer列表中
    polymer_interactive_dict = dict()
    for i in polymer_interactive_list:
        polymer_interactive_dict[i["polymer_id"]] = i["total_cnt"]

    recommend_polymer.sort(key=lambda x: -polymer_interactive_dict.get(x["id"], 0))

    """
    需求临时变更，以下是以前的逻辑
    recommend_polymer_ids = [i["id"] for i in recommend_polymer]

    if user:
        identification = user.id
    else:
        identification = device_id

    # 已读池
    read = RecommendRead.load(identification)
    ret = list(set(recommend_polymer_ids) - set(read))
    ret.sort(key=recommend_polymer_ids.index)  # 保证顺序
    ret = ret[:count]
    v = list(set(read) | set(ret))
    v.sort(key=(read + ret).index)  # 保证顺序
    if not ret:
        RecommendRead.store(identification, recommend_polymer_ids[:count], ex=1 * 60 * 60)
        v = recommend_polymer_ids[:count]
        read = []
    else:
        RecommendRead.store(identification, v, ex=1 * 60 * 60)

    res = []
    for item in recommend_polymer:
        if item["id"] not in read and item["id"] in v:
            item["polymer_attent_num"] = cache_polymer_discuss_follow_num(polymer_id=item["id"])
            res.append(item)

    return res
    """
    res = []
    for item in recommend_polymer:
        item["polymer_attent_num"] = cache_polymer_discuss_follow_num(polymer_id=item["id"])
        res.append(item)

    return res


class RecommendRead(object):
    """记录设备或者用户已读推荐信息。"""

    tpl_key = "{identification}-{date}-read"

    @staticmethod
    def current_date():
        return datetime.now().strftime('%Y-%m-%d')

    @classmethod
    def load(cls, identification):

        key = cls.tpl_key.format(identification=identification, date=cls.current_date())
        ids = redis_client.get(key)

        id_list = []
        if ids:
            id_list = json.loads(ids.decode("utf-8"))

        return id_list

    @classmethod
    def store(cls, identification, id_list, ex=None):

        if not id_list:
            return

        key = cls.tpl_key.format(identification=identification, date=cls.current_date())

        if not ex:
            # 当天剩余时间设置为过期时间
            now = datetime.now()
            ex = int((now.replace(hour=0, second=0, minute=0, microsecond=0) + timedelta(days=1) - now).total_seconds())

        redis_client.set(key, json.dumps(id_list), ex)
