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

import time

from django.core.management import BaseCommand
from django.db.models import Min

from api.models import Diary
from api.models import Problem
from api.models import ServiceComment
from api.models import ServiceCommentImage
from api.models import TopicImage
from rpc.tool.log_tool import logging_exception


def split_list_v2(l, x):
    return [l[m:m + x] for m in range(0, len(l), x)]


class Command(BaseCommand):
    bulk_num = 200

    def create_images(self, diaries, diary_comment_map, start_num):
        diary_to_topic_set = list(Problem.objects.filter(diary__in=diaries).values('diary_id').annotate(Min('id')))
        topic_ids = [topic['id__min'] for topic in diary_to_topic_set]
        topic_list = Problem.objects.filter(id__in=topic_ids).values('id', 'diary_id')

        # topic_id -> comment_id
        topic_comment_map = {}
        for topic_info in topic_list:
            topic_comment_map[topic_info['id']] = {
                'comment_id': diary_comment_map[topic_info['diary_id']],
                'images': []
            }

        topic_image_list = TopicImage.objects.filter(topic_id__in=topic_ids).values('topic_id', 'image_url')
        objects_list = []
        for _topic_image in topic_image_list:
            kwargs = {
                'service_comment_id': topic_comment_map[_topic_image['topic_id']]['comment_id'],
                'image': _topic_image['image_url'],
            }
            objects_list.append(ServiceCommentImage(**kwargs))

        if objects_list != []:
            try:
                print('----------------------------------------------------')
                print('start_num: {}'.format(start_num))
                ServiceCommentImage.objects.bulk_create(objects_list)
                print('start_num finish!')
            except Exception as e:
                logging_exception()
                pe = 'exception message: {}, start_num: {}'.format(e.message, start_num)
                print(pe)

            print('----------------------------------------------------\n')

    def create_comment_images(self, diaries, index):
        # diary_id -> order_id
        diary_id_order_id_list = diaries.values('id', 'order_id')
        diary_id_order_id_dict = {_a['id']: _a['order_id'] for _a in diary_id_order_id_list}

        # order_id -> comment_id
        comment_id_order_id_list = ServiceComment.objects.all().values('id', 'order_id')
        comment_id_order_id_dict = {_a['order_id']: _a['id'] for _a in comment_id_order_id_list}

        # diary_id -> comment_id
        diary_comment_map = {}
        for k, v in diary_id_order_id_dict.iteritems():
            diary_comment_map[k] = comment_id_order_id_dict[v]

        del diary_id_order_id_list, diary_id_order_id_dict, comment_id_order_id_list, comment_id_order_id_dict

        self.create_images(list(diaries), diary_comment_map, index * self.bulk_num)

    def handle(self, *args, **options):
        start_time = time.time()
        diaries = Diary.objects.filter(is_online=True, order__isnull=False, service__isnull=False).order_by('id').prefetch_related('topics')

        _diaries, index = diaries[0:self.bulk_num], 0
        while _diaries:
            _ = self.create_comment_images(_diaries, index)
            index += 1
            _diaries = diaries[index * self.bulk_num: (index + 1) * self.bulk_num]

        end_time = time.time()
        print('Total time: {}'.format(end_time - start_time))
