# coding=utf-8
import tablib
import traceback
from django.core.management import BaseCommand
from gm_types.gaia import ORDER_STATUS
from openpyxl import load_workbook

from api.models import Service
from api.models import Order


class Command(BaseCommand):
    """
    导出核心医生美购数据 12-15
    python manage.py export_doctor_service
    """

    def handle(self, *args, **options):
        wb = load_workbook(filename='/data/service/doctors.xlsx')
        # sheetnames = wb.get_sheet_names()
        # ws = wb.get_sheet_by_name(sheetnames[0])
        ws = wb.active

        dt_service_item = tablib.Dataset()
        dt_service_item.headers = [u'负责商务', u'美购名称', u'美购ID', u'属性名称', u'属性ID', u'医生', u'医生id', u'医院',
                                   u'医院ID', u'是否在线', u'是否自营', u'库存数量', u'是否多属性', u'是否手术类', u'更美价',
                                   u'预付款', u'抽成', u'自营抽成']
        dt_service = tablib.Dataset()
        dt_service.headers = [u'美购ID', u'累计已销售数量(包括所有订单状态)', u'付过款数量(已付款，已使用，已退款，等待退款)',
                              u'已付款', u'已验证', u'已退款']
        print ws.max_row
        for row in ws.rows[1:]:
            try:
                doctor_id = row[1].value
                print doctor_id
                services = Service.objects.filter(doctor_id=doctor_id)
                for service in services:
                    try:
                        row_service = [
                            service.id,
                            Order.objects.filter(service_id=service.id).count(),
                            Order.objects.filter(
                                service_id=service.id,
                                status__in=[
                                    ORDER_STATUS.PAID,
                                    ORDER_STATUS.USED,
                                    ORDER_STATUS.REFUNDED,
                                    ORDER_STATUS.WAIT_REFUNDED,
                                ]
                            ).count(),
                            Order.objects.filter(service_id=service.id, status=ORDER_STATUS.PAID).count(),
                            Order.objects.filter(service_id=service.id, status=ORDER_STATUS.USED).count(),
                            Order.objects.filter(service_id=service.id, status=ORDER_STATUS.REFUNDED).count(),
                        ]

                        dt_service.append(row_service)
                    except Exception as e:
                        print e.message
                        traceback.print_exc()
                        continue

                for service in services:
                    for serviceitem in service.items.all().filter(is_delete=False):
                        try:
                            price_info = serviceitem.get_default_price_info()
                            row_service_item = [
                                service.doctor.business_partener.username if service.doctor.business_partener else u'',
                                service.name,
                                service.id,
                                ''.join(serviceitem.items_name),
                                serviceitem.id,
                                service.doctor.name,
                                service.doctor.id,
                                service.doctor.hospital.name,
                                service.doctor.hospital.id,
                                service.is_online,
                                service.is_self_support,
                                price_info.get('sale_limit', 0),
                                service.items.all().filter(is_delete=False) > 1,
                                service.is_operation,
                                price_info.get('gengmei_price'),
                                price_info.get('pre_payment_price'),
                                price_info.get('discount'),
                                price_info.get('self_support_discount'),
                            ]
                            dt_service_item.append(row_service_item)
                        except Exception as e:
                            print e.message
                            traceback.print_exc()
                            continue

            except Exception as e:
                traceback.print_exc()
                print e.message
                continue
        open(u'/data/service/service.xlsx', 'wb').write(dt_service.xlsx)
        open(u'/data/service/serviceitem.xlsx', 'wb').write(dt_service_item.xlsx)
        print (u'Done')
