# coding=utf-8
from __future__ import print_function, unicode_literals, absolute_import

from django.core.management import BaseCommand

from answer.models import AnswerReply
from talos.models import ReplyCollect
from talos.models.topic import TopicReply


class Command(BaseCommand):
    bulk_num = 200

    def handle(self, *args, **kwargs):
        replys = TopicReply.objects.all()
        _replys = replys[0:self.bulk_num]
        while _replys:
            self.convert_topic_reply(_replys)
            last_id = _replys[len(_replys)-1].id
            print(last_id)
            _replys = TopicReply.objects.filter(id__gt=last_id)[0:self.bulk_num]

        answers = AnswerReply.objects.all()
        _answers = answers[0:self.bulk_num]
        while _answers:
            self.convert_answer_reply(_answers)
            last_id = _answers[len(_answers) - 1].id
            print(last_id)
            _answers = AnswerReply.objects.filter(id__gt=last_id)[0:self.bulk_num]

    def convert_answer_reply(self, items):
        try:
            answer_list = []
            for item in items:
                answer_list.append(ReplyCollect(created_time=item.create_time, user_id=item.user_id,
                                   topic_reply_id=None, answer_id=item.id, reply_user_id=item.answer.user_id))
            ReplyCollect.objects.bulk_create(answer_list)
        except:
            print('error: answer', items[0].id)

    def convert_topic_reply(self, items):
        try:
            topic_list = []
            for item in items:
                reply_user_id = None
                if item.replied_topic:
                    reply_user_id = item.replied_topic.user_id
                elif item.problem_id:
                    reply_user_id = item.problem.user_id
                elif item.diary_id:
                    reply_user_id = item.diary.user_id
                topic_list.append(ReplyCollect(created_time=item.reply_date, user_id=item.user_id,
                                               topic_reply_id=item.id, answer_id=None,
                                               reply_user_id=reply_user_id))
            ReplyCollect.objects.bulk_create(topic_list)
        except Exception as e:
            print(e)
            print('error: topic', items[0].id)
