# coding:utf-8

from __future__ import absolute_import, unicode_literals, print_function
import math

from celery import shared_task
from django.db.models import Q

from gm_types.gaia import POLYMER_DETAIL_TAB_TYPE

from polymer.models import PolymerTab, PolymerExtra, Polymer
from rpc.context import get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception

rpc_invoker = get_rpc_remote_invoker()


@shared_task
def cal_disscuss_polymer_extra():
    """获取对应的聚合页列表信息。"""

    tab_types = [POLYMER_DETAIL_TAB_TYPE.DISSCUSS]
    polymer_tab_query = Q(enable=True) & Q(tab_type__in=tab_types)

    page_num = 50
    count = PolymerTab.objects.filter(polymer_tab_query).distinct().count()
    pages = int(math.ceil(count * 1.0 / page_num))

    for page in range(pages):
        start = page_num * page
        end = start + page_num
        polymer_tabs = PolymerTab.objects.filter(polymer_tab_query).\
                           distinct().prefetch_related("polymer")[start:end]

        items = []
        for polymer_tab in polymer_tabs:
            tags = [tag["id"] for tag in polymer_tab.polymer.tag_list]
            item = {
                "id": polymer_tab.polymer.id,
                "tags": tags,
                "question_types": polymer_tab.polymer.get_question_classify,
            }
            items.append(item)

        try:
            res = rpc_invoker['qa/question/polymers_extra'](polymers=items).unwrap()
        except:
            logging_exception()
            continue

        for polymer_id, item in res.items():
            try:
                try:
                    polymer_extra = PolymerExtra.objects.get(polymer__id=int(polymer_id))
                except:
                    polymer_extra = PolymerExtra()
                polymer_extra.polymer_id = int(polymer_id)
                polymer_extra.new_question_cnt = item["new_question_cnt"]
                polymer_extra.new_answer_cnt = item["new_answer_cnt"]
                polymer_extra.new_reply_cnt = item["new_vote_cnt"]
                polymer_extra.new_vote_cnt = item["new_reply_cnt"]
                polymer_extra.total_cnt = polymer_extra.new_question_cnt + polymer_extra.new_answer_cnt + \
                                          polymer_extra.new_reply_cnt + polymer_extra.new_vote_cnt
                polymer_extra.save()
            except:
                continue


