from talos.models.topic.column import Article
from talos.models.topic.recommendsocre import ArticleRelatedRecommendScore
import logging
from utils.rpc import get_rpc_invoker
from talos.models.topic.topic import Problem
from qa.models.toutiao import by_contentz_type_id_get_keywords, get_content_star_keywords, get_content_title_keywords, get_content_star_first_keyword

rpc = get_rpc_invoker()


def get_articles(pks):
    articles = Article.objects.filter(id__in=pks)
    rs = ArticleRelatedRecommendScore.objects.filter(id__in=pks).values('id', 'score')
    rs_dict = {item['id']: item['score'] for item in list(rs)}

    data = []
    for article in articles:
        item = {}
        item['id'] = article.id
        item['article_id'] = article.article_id
        item['smart_rank'] = article.smart_rank()
        item["is_online"] = Problem.objects.filter(id=article.article_id).values_list("is_online", flat=True).first()
        item['recommend_score'] = rs_dict.get(article.id, 0)
        item["content_keyword"] = by_contentz_type_id_get_keywords(id=article.id, content_type="article")
        item["content_star_keyword"] = get_content_star_keywords(id=article.id, content_type="article")
        item["content_star_first_keyword"] = get_content_star_first_keyword(id=article.id, content_type="article")
        # item["title_keyword"] = get_content_title_keywords(id=article.id, content_type="article")

        topic = article.topic()
        if topic:
            item['title'] = topic.title
            item['content'] = topic.answer_richtext
            tags = topic.tags
            tags_id_list = [tag.id for tag in tags]
            item['tag_ids'] = tags_id_list
            item['tags'] = [tag.name for tag in tags]

            # 新标签
            fresh_tag_result = rpc["api/agile_tag/tuple_new_tags"](old_tag_ids=tags_id_list)
            fresh_tag_id_list = list()
            fresh_tag_name_list = list()
            for fresh_tag_id, fresh_tag_name in fresh_tag_result.unwrap():
                fresh_tag_id_list.append(fresh_tag_id)
                fresh_tag_name_list.append(fresh_tag_name)
            item["fresh_tag_ids"] = fresh_tag_id_list
            item["fresh_tags"] = fresh_tag_name_list
            item["ask"] = topic.ask
            item['user'] = {
                "id": topic.user.id
            }
            item["content_pre"] = topic.answer_richtext
            item['title_pre'] = topic.title
        logging.info("get data:%s" % data)

        data.append(item)
    return data
