# coding=utf-8

import xlrd
import tablib
from datetime import datetime, timedelta
from django.core.management import BaseCommand
from api.models import Service, ServiceTag
from statistic.models import StatisticServiceSmartRankV3


class Command(BaseCommand):
    """
    python manage.py dump_20180813_export_ctr
    """

    def handle(self, *args, **options):
        data = xlrd.open_workbook('insert_personal_tab.xlsx'.decode('utf-8'))
        table = data.sheets()[0]

        start = datetime(2018, 7, 22)
        date_list = [start + timedelta(days=day) for day in range(24)]
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'医院id', u'医院名', u'美购名', u'日期', u'ctr得分', u'咨询因子得分'
        ]
        for row in range(1, table.nrows):
            row_data = table.row_values(row)
            hospital_id = row_data[1]
            hospital_name = row_data[0]
            print hospital_name, hospital_id
            service_ids = Service.objects.filter(
                doctor__hospital_id=hospital_id).values_list('id', flat=True)
            for service_id in service_ids:
                for date in date_list:
                    try:
                        smt_rk = StatisticServiceSmartRankV3.objects.get(
                            service_id=service_id,
                            stat_date=date
                        )
                        x = (
                            hospital_id,
                            hospital_name,
                            service_id,
                            date,
                            smt_rk.get_ctr_value(),
                            smt_rk.get_consult_value(),
                        )
                        dt_result.append(x)
                    except:
                        print('date:', date, 'service_id:', service_id)
                        continue
        open(u'service_score_export.xlsx', 'wb').write(dt_result.xlsx)
        print 'Done!'