# -*- coding: UTF-8 -*-

import datetime
import tablib
from celery import shared_task
from django.db.models import Q
from api.models import Service, ServiceItem
from rpc.tool.queryset_tool import big_qs_iter

from hera.utils import get_mail_instance, attach_title


@shared_task
def export_sku_for_price_competition():
    dt = tablib.Dataset()
    dt.headers = [
        u'美购id', u'sku id', u'美购名称', u'sku名称', u'sku价格', u'医生名称',
        u'医院名称', u'预约数', u'关联商务',
    ]

    now_t = datetime.datetime.now()
    services = Service.objects.using('slave').filter(is_online=True, start_time__lt=now_t)\
        .filter(Q(end_time__isnull=True) | Q(end_time__gt=now_t))

    for service in big_qs_iter(services):
        print service.id, service.name
        flag_service_first_sku = True
        skus = service.items.filter(is_delete=False)
        if not skus.exists():
            continue

        service_name = service.name
        service_id = service.id
        try:
            d = service.doctor
        except:
            d = None
        doctor_name = d.name if d else ''
        try:
            h = d.hospital
        except:
            h = None
        hospital_name = h.name if h else ''
        service_sell_amount = service.sell_amount_display
        try:
            biz_name = d.business_partener.username
        except:
            biz_name = ''

        sku_ids = [sku.id for sku in skus]
        sku_names = ServiceItem.get_items_name(sku_ids)
        sku_prices = Service.get_current_price_info_by_service_item_ids(sku_ids)

        for sku in skus:
            sku_name = u'+'.join(sku_names.get(sku.id, []))
            sku_price = sku_prices.get(sku.id, {}).get('gengmei_price', '')
            row = [
                service_id, sku.id, service_name, sku_name, sku_price,
                doctor_name, hospital_name,
            ]
            if flag_service_first_sku:
                row.append(service_sell_amount)
                flag_service_first_sku = False
            else:
                row.append('')
            row.append(biz_name)

            dt.append(row)

    sub = u'更美平台所有商品sku信息_{}'.format(datetime.date.today().strftime('%Y%m%d'))
    mail = get_mail_instance(sub, '', ['gengmeijiage@igengmei.com'])
    mail.attach(attach_title(u'{}.xlsx'.format(sub)), dt.xlsx)
    mail.send()
