# coding=utf-8
from datetime import datetime
from django.core.management import BaseCommand
from django.db.models import Sum, Count, Min
from openpyxl import Workbook
from openpyxl.writer.excel import ExcelWriter

from api.models import ServiceReserve, ServiceItem, Order, Service


class Command(BaseCommand):
    """
    导出开团提醒的历史数据
    python manage.py export_serviceserve_data '2015-06-01'
    """

    def add_arguments(self, parser):

        parser.add_argument('date', type=str)

    def handle(self, *args, **options):
        if options['date'] is None:
            return
        wb_result = Workbook()  # 新建一个工作薄
        ew_result = ExcelWriter(workbook=wb_result)  # 新建一个ExcelWriter,用来写wb_result
        dest_filename = 'result.xlsx'  # wb_result的名字
        ws1 = wb_result.worksheets[0]  # 取得wb_result的第一个工作表ws1
        ws1.title = 'servicereserve_result'  # 指定ws1的名字
        ws1.cell(row=1, column=1).value = u'美购名称'
        ws1.cell(row=1, column=2).value = u'状态'
        ws1.cell(row=1, column=3).value = u'美购对应医生'
        ws1.cell(row=1, column=4).value = u'美购所在地区'
        ws1.cell(row=1, column=5).value = u'美购对应商务'
        ws1.cell(row=1, column=6).value = u'更美价'
        ws1.cell(row=1, column=7).value = u'预约用户ID'
        ws1.cell(row=1, column=8).value = u'该用户历史创建订单量'
        ws1.cell(row=1, column=9).value = u'该用户历史支付订单量'
        ws1.cell(row=1, column=10).value = u'该用户历史支付总额'
        ws1.cell(row=1, column=11).value = u'开团提醒预约日期'
        ws1.cell(row=1, column=12).value = u'开团提醒预约时间'

        ws2 = wb_result.create_sheet()  # 取得wb_result的第一个工作表
        ws2.title = 'service_result'  # 指定ws2的名字
        ws2.cell(row=1, column=1).value = u'美购ID'
        ws2.cell(row=1, column=2).value = u'美购名称'
        ws2.cell(row=1, column=3).value = u'开始时间'
        ws2.cell(row=1, column=4).value = u'结束时间'

        date_time = datetime.strptime(options['date'], '%Y-%m-%d')
        print date_time
        serviceserves = ServiceReserve.objects.filter(created_time__gte=date_time).order_by('-created_time')
        count = serviceserves.count()
        frequency = count / 1000 + 1
        begin = 0
        step = 1000
        while begin <= count:
            for item in serviceserves[begin:begin + step]:
                data = ProcessData.organizational_data(item)
                a = ws1.max_row
                print a
                ws1.cell(row=a + 1, column=1).value = data.get('name', '')
                ws1.cell(row=a + 1, column=2).value = data.get('status', '')
                ws1.cell(row=a + 1, column=3).value = data.get('doctor', '')
                ws1.cell(row=a + 1, column=4).value = data.get('city', '')
                ws1.cell(row=a + 1, column=5).value = data.get('business_partener', '')
                ws1.cell(row=a + 1, column=6).value = data.get('gengmei_price', '')
                ws1.cell(row=a + 1, column=7).value = data.get('user_id', '')
                ws1.cell(row=a + 1, column=8).value = data.get('order_count', '')
                ws1.cell(row=a + 1, column=9).value = data.get('order_count_pay', '')
                ws1.cell(row=a + 1, column=10).value = data.get('payments', '')
                ws1.cell(row=a + 1, column=11).value = data.get('date', '')
                ws1.cell(row=a + 1, column=12).value = data.get('time', '')
            begin += step
        print(u'开团提醒数据读取完毕!')
        print(u'开始读取美购数据!')
        services = ServiceReserve.objects.filter(created_time__gte=date_time).values('service__id').distinct()
        list_services = []
        for item in services:
            list_services.append(item['service__id'])
        services_result = Service.objects.filter(id__in=list_services)
        for service in range(0, services_result.count()):
            print service
            start_time = None
            end_time = None
            if services_result[service].start_time:
                start_time = datetime.strftime(
                    services_result[service].start_time, '%Y-%m-%d %I:%M:%S')
            if services_result[service].end_time:
                end_time = datetime.strftime(
                    services_result[service].end_time, '%Y-%m-%d %I:%M:%S')
            ws2.cell(row=service + 2, column=1).value = services_result[service].id
            ws2.cell(row=service + 2, column=2).value = services_result[service].name
            ws2.cell(row=service + 2, column=3).value = start_time
            ws2.cell(row=service + 2, column=4).value = end_time

        ew_result.save(filename=dest_filename)
        print 'sucess!'


class ProcessData(object):
    @classmethod
    def organizational_data(cls, serviceserve):
        data_dict = {}
        data_dict['id'] = serviceserve.id
        data_dict['name'] = serviceserve.service.name
        data_dict['status'] = u'未发送' if serviceserve.stat == '1' else u'已发送'
        data_dict['doctor'] = serviceserve.service.doctor.name
        data_dict['city'] = serviceserve.service.doctor.hospital.name
        data_dict['business_partener'] = serviceserve.service.doctor.business_partener.username \
            if serviceserve.service.doctor.business_partener is not None \
            else u''
        if serviceserve.service.is_multiattribute:
            data_dict['gengmei_price'] = ServiceItem.objects.filter(
                service_id=serviceserve.service.id
            ).aggregate(gengmei_price=Min('gengmei_price')).get('gengmei_price')
        else:
            data_dict['gengmei_price'] = serviceserve.service.gengmei_price
        data_dict['user_id'] = serviceserve.user_id
        data_dict['order_count'] = Order.objects.filter(user_id=serviceserve.user_id).count()
        payments = Order.objects.filter(user_id=serviceserve.user_id).filter(status__in=[
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9'
        ]).aggregate(
            paysum=Sum('payment'),
            payments=Count('payment')
        )
        data_dict['order_count_pay'] = payments.get('payments')
        data_dict['payments'] = payments.get('paysum')
        data_dict['date'] = datetime.strftime(serviceserve.created_time, '%Y-%m-%d')
        data_dict['time'] = datetime.strftime(serviceserve.created_time, '%I:%M:%S')
        return data_dict
