# coding=utf-8

import tablib
from celery import shared_task
from django.conf import settings
from django.core.mail import EmailMessage, get_connection

from api.models.types import ORDER_STATUS
from rpc.tool.log_tool import info_logger
from rpc.tool.queryset_tool import queryset_enc

connection = get_connection(
    username=settings.HERA_EMAIL_USER,
    password=settings.HERA_EMAIL_PSWD,
)

DATETIME_FMT = '%Y-%m-%d %H:%M:%S'


def get_mail(sub, body, to_user_email, dt):
    mail = EmailMessage(connection=connection)
    mail.from_email = settings.HERA_EMAIL_USER
    mail.subject = sub
    mail.to = [to_user_email]
    mail.body = body
    mail.attach(u'{}.xlsx'.format(sub), dt.xlsx)
    return mail


@shared_task
def export_orders_excel(orders, to_user_email):
    """
     导出订单Excel
    """
    if isinstance(orders, dict):
        orders = queryset_enc(orders)
    if not to_user_email:
        return
    dt = tablib.Dataset()
    dt.headers = [
        u'订单号', u'买单名称', u'金额', u'实际支付金额', u'优惠方式', u'商务', u'结算状态', u'当前状态', u'城市'
    ]
    for order in orders:
        x = (
            order.id,
            order.name,
            order.maidan_price_cent / 100.00,
            order.payment_cent / 100.00,
            u'{}折'.format(order.maidansnapshot.doctor_discount_rate),
            order.doctor.business_partener.username,
            u'是' if order.is_settled else u'否',
            ORDER_STATUS.getDesc(order.status),
            order.doctor.hospital.city.name,
        )

        dt.append(x)

    body = u'订单导出'
    info_logger.info(u'导出结束')
    get_mail(u'订单结算', body, to_user_email, dt).send()
