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

from __future__ import unicode_literals, absolute_import, print_function
import json

from django.conf import settings
from django.db.models import Q

from gm_types.gaia import POLYMER_DETAIL_TAB_TYPE

from rpc.decorators import bind

from rpc.decorators import cache_page
from polymer.models import Tag, Polymer, PolymerTab
from polymer.views.polymer import cache_polymer_discuss_follow_num

POLYMER_ID_IS_DISCUSS = settings.POLYMER_ID_IS_DISCUSS


@bind("api/polymer/polymer_info_by_question")
def get_polymer_info_by_question(tag_list=None):
    """
    根据传入的tagID，返回所属的聚合页名，相关数字，tagid图片
    """
    return get_polymer_info_by_tags(tag_list=tag_list)


@bind("api/polymer/polymer_info_by_questions")
def get_polymer_info_by_questions(tags_dict):
    result = {}

    tags_list = []
    for item in tags_dict.values():
        tags_list.extend(item)

    tags_polymers = get_polymer_info_by_tags_v2(tag_list=tags_list)

    for question_id, tags_ids in tags_dict.items():
        for tag_id in tags_ids:
            if question_id not in result:
                result[question_id] = []

            result[question_id].extend(tags_polymers.get(tag_id, []))

    return result


@cache_page(timeout=1 * 30 * 60)
def get_polymer_info_by_tags(tag_list=None, is_discuss=False, external_display=True):

    if not tag_list:
        return []

    query = Q(tags__id__in=tag_list) & Q(is_online=True)
    if external_display:
        query &= Q(external_display=True)
    polymer_info_list = Polymer.objects.filter(query).values("id", "name")

    if not polymer_info_list:
        return []

    tmp_polymer_ids = [polymer["id"] for polymer in polymer_info_list]
    polymer_type_is_discuss = list(PolymerTab.objects.filter(
        polymer_id__in=tmp_polymer_ids,
        tab_type=POLYMER_DETAIL_TAB_TYPE.DISSCUSS,
        enable=True
    ).values_list("polymer_id", flat=True).distinct())

    if is_discuss:
        # 只过滤处讨论聚合页
        polymer_info_list = filter(lambda i: i["id"] in polymer_type_is_discuss, polymer_info_list)
        tmp_polymer_ids = polymer_type_is_discuss

    tag_info_list = Tag.objects.filter(polymer__id__in=tmp_polymer_ids, is_online=True).values("id", "icon_url", "polymer__id")

    polymer_image_dict = dict()
    for tag_info in tag_info_list:
        if tag_info["polymer__id"] not in polymer_image_dict:
            polymer_image_dict[tag_info["polymer__id"]] = list()
        polymer_image_dict[tag_info["polymer__id"]].append(tag_info["icon_url"])

    result = list()
    for polymer in polymer_info_list:
        polymer_id = polymer["id"]
        tag_img = list(filter(None, polymer_image_dict.get(polymer_id, [])))
        _data = {
            "id": polymer_id,
            "name": polymer["name"],
            "tag_img": (tag_img and tag_img[0]) or ''
        }
        if polymer["id"] in POLYMER_ID_IS_DISCUSS + polymer_type_is_discuss:
            polymer_sum = cache_polymer_discuss_follow_num(polymer_id=polymer_id)
            _polymer_type = POLYMER_DETAIL_TAB_TYPE.DISSCUSS
        else:
            polymer_sum = cache_polymer_discuss_follow_num(polymer_id=polymer_id)
            _polymer_type = ""
        _data.update({
            "polymer_sum": polymer_sum,
            "polymer_type": _polymer_type,
        })
        if _data not in result:
            result.append(_data)

    result.sort(key=lambda x: (sort_func(x['id']), x['polymer_type'], -x['polymer_sum']))

    return result


def sort_func(x):
    try:
        return POLYMER_ID_IS_DISCUSS.index(x)
    except:
        return len(POLYMER_ID_IS_DISCUSS)


def get_polymer_info_by_tags_v2(tag_list=None):

    if not tag_list:
        return {}

    query = Q(tags__id__in=tag_list) & Q(is_online=True)
    polymer_info_list = Polymer.objects.filter(query).values("id", "name", "rank")

    if not polymer_info_list.exists():
        return {}

    tmp_polymer_ids = [polymer["id"] for polymer in polymer_info_list]

    polymer_type_is_discuss = list(PolymerTab.objects.filter(
        polymer_id__in=tmp_polymer_ids,
        tab_type=POLYMER_DETAIL_TAB_TYPE.DISSCUSS,
        enable=True
    ).values_list("polymer_id", flat=True).distinct())

    tag_info_list = Tag.objects.filter(polymer__id__in=tmp_polymer_ids, is_online=True).values("id", "icon_url", "polymer__id")

    result = {}  # {tag_id: {}}
    for polymer in polymer_info_list:

        polymer_id = polymer["id"]
        for tag_info in tag_info_list:
            if tag_info["polymer__id"] != polymer_id:
                continue

            tag_id = tag_info["id"]
            if tag_id not in result:
                result[tag_id] = []

            _data = {
                "id": polymer_id,
                "name": polymer["name"],
                "tag_img": tag_info["icon_url"],
                "rank": polymer.get("rank", 999),
            }

            discuss = False
            if polymer["id"] in POLYMER_ID_IS_DISCUSS + polymer_type_is_discuss:
                discuss = True
            _data["is_discuss"] = discuss

            result[tag_id].append(_data)

    return result
