import json

from api.views.base_view import BaseView
from api.utils.sensitive import Sensitive

from libs.user import get_user_by_ids
from alpha_types.venus import ERROR as CODES

class CreateTopicForBatch(BaseView):
    """
    内部使用，批量建帖
    """
    def post(self, request):

        user_id = request.POST.get("user_id", 0)
        topic_list = json.loads(request.POST.get("topic_list", '[]'))

        if not user_id:
            return self.parameter_invalid_response()

        user_info = get_user_by_ids([user_id])
        if not user_info:
            return self.error(self.get_ErrorInfo(CODES.USER_NOT_FOUND))

        if not topic_list:
            return self.ok()

        topics = []
        # 敏感词检测，获取可用的帖子
        check_info = Sensitive.check([topic["content"] for topic in topic_list if topic.get("content")])
        for topic in topic_list:
            if topic.get('content'):
                succ = check_info.get(topic.get("content"))
                if not succ:
                    topics.append(topic)
            else:
                if topic.get('images') or topic.get('video'):
                    topics.append(topic)

        if not topics:
            return self.ok()

        tag_names = []
        for item in topics:
            tags = item.get("tags") or []
            tag_names.extend([tag.replace("#", '').strip() for tag in tags])
            item["user_id"] = user_id

        check_info = Sensitive.check(tag_names)
        tags  = [tag_name for tag_name, succ in check_info.items() if not succ]

        # 先创建标签
        _tag_error, _tag_data = self.call_rpc(
            "venus/community/tag/batch_create_tag_by_name",
            tag_names=tags
        )
        if _tag_error:
            return self.error(_tag_error)

        # 更新发帖
        # 处理标签，将文本中的标签处理成现有标签
        for item in topics:
            tags = item.get("tags") or []
            tags = [tag.replace("#", '').strip() for tag in tags]
            content = item["content"]
            for tag_name, tag_id  in _tag_data.items():
                if tag_name in tags:
                    alpha_tag = '<topic>{' + '"id":{},"name":"{}"'.format(tag_id, tag_name) + '}</topic>'
                    content = content.replace('#' + tag_name, alpha_tag)
            item["content"] = content.replace('#', '')

            item["tag_ids"] = [
                _tag_data[tag_name]
                for tag_name in tags if _tag_data.get(tag_name)
            ]

        create_err, result = self.call_rpc(
            "venus/community/topic/batch_create_for_inner",
            topic_list=topics
        )
        if create_err:
            return self.error(create_err)

        return self.ok(data=result)
