# coding=utf-8

from __future__ import absolute_import, unicode_literals, print_function
from celery import shared_task
# TODO zhangyuyun 确认直接改会不会有问题
from talos.models.topic import Problem
from search.utils.task_chunk import get_task_chunk_field
from rpc.cache import topic_sug_cache
import json

@shared_task
def calc_topic_chunk(task_id, chunk_id, node, ext_params, offset, chunk_size):
    SHOW_SIZE = 100

    topics = Problem.objects.order_by('pk').filter(pk__gt=offset).select_related('user__doctor')
    topics = topics[:chunk_size]
    result = []
    for t in topics:
        if (not t.is_online) or hasattr(t.user, 'doctor'): # 过滤掉下线帖子和医生发帖
            continue
        topic_score = {
            'topic_id':t.id,
            'total':node.calc_score(t, ext_params),
        }
        for ch in node.children:
            ch_info = ch.get_info()
            topic_score[ch_info['node_name']] = {
                'weight':ch_info['weight'],
                'score':ch_info['score'],
            }
        result.append(topic_score)
    result = sorted(result, key=lambda x:x['total'], reverse=True)[:SHOW_SIZE]
    topic_sug_cache.hset(task_id, get_task_chunk_field(chunk_id), json.dumps(result))


