# coding=utf-8
# 帖子排序算分用任务
from talos.models.topic import Problem, TopicRankingScore
from utils.decorator import thread_local_router
from django.conf import settings
from celery import shared_task
from gm_types.gaia import TOPIC_TYPE


@shared_task
@thread_local_router(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def calc_topic_ranking():
    # 只对咨询帖和讨论帖计算分数
    all_topics = Problem.objects.filter(
        topic_type__in=(TOPIC_TYPE.ASK, TOPIC_TYPE.TOPIC)  # 只计算咨询帖和讨论帖
    ).order_by('pk')
    offset = 0
    size = 100
    while True:
        topics = all_topics[offset:offset+size]
        if len(topics) <= 0:
            break
        topic_ids = list(topics.values_list('id', flat=True))
        calc_topic_ranking_exec.delay(topic_ids=topic_ids)
        offset += size


@shared_task
@thread_local_router(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def calc_topic_ranking_exec(topic_ids):
    TopicRankingScore.update_pop(topic_ids=topic_ids)
