# 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 rpc.tool.log_tool import logging_exception


def rating_star(rating):
    if rating in [0, None]:
        return 5
    else:
        return rating


def bulk_create_comment(diaries_data, diary_ids, start_num):
    objects_list = []
    for diary_id in diary_ids:
        diary_data = diaries_data[diary_id]
        create_kwargs = {
            'order_id': diary_data['order_id'],
            'service_id': diary_data['service_id'],
            'rating': rating_star(diary_data['rating']),
            'operation_effect': rating_star(diary_data['operation_effect_rating']),
            'doctor_attitude': rating_star(diary_data['doctor_attitude_rating']),
            'hospital_env': rating_star(diary_data['hospital_env_rating']),
            'content': diary_data.get('content', ''),
            'create_time': diary_data.get('topic_created_time') or diary_data.get('created_time') or None,
        }
        objects_list.append(ServiceComment(**create_kwargs))

    try:
        print('start_num: {}'.format(start_num))
        ServiceComment.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)


class Command(BaseCommand):
    """
    将日记本中的评价转换成美购评价
    产品确认 没有的按默认好评处理
    http://hera.s.gmei.com/2017/04/06/081c806f8d
    """
    bulk_num = 200

    def create_comment(self, diaries, start_num):
        diaries_data = diaries.values(
            'order_id', 'service_id', 'rating', 'operation_effect_rating', 'doctor_attitude_rating',
            'hospital_env_rating', 'id', 'created_time'
        )
        diaries = list(diaries)
        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]

        diaries_dict = {diary['id']: diary for diary in diaries_data}
        topic_answers = Problem.objects.filter(id__in=topic_ids).values('diary_id', 'answer', 'created_time')

        for topic_answer in topic_answers:
            diaries_dict[topic_answer['diary_id']]['content'] = topic_answer['answer']
            diaries_dict[topic_answer['diary_id']]['topic_created_time'] = topic_answer['created_time']

        diary_ids_list = diaries_dict.keys()
        bulk_create_comment(diaries_dict, diary_ids_list, start_num)

    def handle(self, *args, **kwargs):
        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(_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))
