from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import Q

from talos.libs.execel import ExcelWriter
from talos.models.diary import Diary
from talos.models.topic import Problem, TopicImage


class Command(BaseCommand):
    def handle(self, *args, **options):
        print('START')
        excel_writer = ExcelWriter('topic_pre_image.xlsx')
        excel_writer.write_header(['日记帖术前图'])
        start = 0
        offset = 1000
        images_len = 1
        while images_len <= 50000:
            diaries = Diary.objects.using(settings.SLAVE_DB_NAME).filter(id__lte=start, id__gte=offset)
            for diary in diaries:
                diary_operation_time = diary.operation_time or diary.created_time
                query = Q(operation_date__lte=diary_operation_time, diary_id=diary.id)
                topic_ids = list(Problem.objects.using(
                    settings.SLAVE_DB_NAME).filter(query).values_list("id", flat=True))
                topic_images = list(TopicImage.objects.using(settings.SLAVE_DB_NAME).filter(
                    topic_id__in=topic_ids).values_list('image_url', flat=True))
                if not topic_images:
                    continue
                for image in topic_images:
                    img = str(image) + u'-w'
                    excel_writer.write_row(row_num=images_len+1, values=[img])
                    images_len += 1
                    if images_len >= 50000:
                        break
                if images_len >= 50000:
                    break
            start += offset
        excel_writer.save()
        print('DONE')
