# coding: utf-8


import json

from django.core.management import BaseCommand
from api.models import Diary


class Command(BaseCommand):
    """ 将日记本的现有评价转换成新的星级评价
    """
    def handle_comment(self, diary):
        if not diary.comment:
            return
        if diary.comment == 'null':
            return
        comment = json.loads(diary.comment)
        bad_comment = comment['bad']
        operation_effect_rating = 5
        doctor_attitude_rating = 5
        hospital_env_rating = 5
        for comment in bad_comment:
            if comment['select']:
                if comment['name'] == u'还挺一般的':
                    operation_effect_rating -= 1
                    doctor_attitude_rating -= 1
                    hospital_env_rating -= 1
                if comment['name'] == u'医院老推销':
                    doctor_attitude_rating -= 2
                if comment['name'] == u'效果不理想':
                    operation_effect_rating -= 2
        if operation_effect_rating < 1:
            operation_effect_rating = 1
        if doctor_attitude_rating < 1:
            doctor_attitude_rating = 1
        if hospital_env_rating < 1:
            hospital_env_rating = 1
        diary.operation_effect_rating = operation_effect_rating
        diary.doctor_attitude_rating = doctor_attitude_rating
        diary.hospital_env_rating = hospital_env_rating
        if not diary.rating:
            avg = (operation_effect_rating + doctor_attitude_rating + hospital_env_rating) / 3
            diary.rating = int(round(avg))
        diary.save()

    def handle(self, *args, **kwargs):
        diaries = Diary.objects.exclude(comment='')
        total_amount = diaries.count()
        i = 1
        for diary in diaries:
            self.handle_comment(diary)
            print '--------------------------------'
            print 'ID:{} {}/{}'.format(diary.id, i, total_amount)
            print '    operation_effect:', diary.operation_effect_rating
            print '    doctor_attitude:', diary.doctor_attitude_rating
            print '    hospital_env:', diary.hospital_env_rating
            print '--------------------------------\n'
            i += 1
