# coding=utf-8
# create by oldman at 2017/11/2
import tablib
from celery import shared_task
from gm_types.trade import STATEMENT_STATUS

from hera.utils import attach_title
from hera.utils import get_mail_instance
from pay.models.statementall import StatementAll
from rpc.tool.log_tool import log_audit_hera, info_logger

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


def send_export_mail(subject, body, to_list, dt, send=True):
    if not isinstance(to_list, (list, tuple)):
        to_list = [to_list]
    mail = get_mail_instance(subject, body, to_list)
    mail.attach(attach_title(u'{}.xlsx'.format(subject)), dt.xlsx)
    if send:
        mail.send()

    # audit log
    audit_data = {
        'audit_type': 'export_excel',
        'email_title': subject,
        'email_to': to_list,
        # 'excel_data': dt.xlsx,
        # 'excel_name': u'{}.xlsx'.format(subject),
    }
    log_audit_hera(audit_data)
    return mail


@shared_task
def export_all_unchecked_excel_task(to_user_email):
    """
    导出所有为结算的对账单
    :param to_user_email:
    :return:
    """
    info_logger.info(u'导出开始')
    statementalls = StatementAll.objects.filter(status__in=[STATEMENT_STATUS.CHECKED,
                                                            STATEMENT_STATUS.DEFEAT
                                                            ])
    dt_service = tablib.Dataset()
    dt_maidan = tablib.Dataset()
    dt_service.headers = (u'结算对象', u'结算周期', u'结算金额', u'结算状态', u'省', u'市', u'开户银行',
                          u'支行/分行', u'户名', u'账号', u'商户确认时间')
    dt_maidan.headers = (u'结算对象', u'结算周期', u'结算金额', u'结算状态', u'省', u'市', u'开户银行',
                         u'支行/分行', u'户名', u'账号', u'商户确认时间')

    for statementall in statementalls:
        dt_service.append((
            statementall.doctor.name,
            statementall.statement_date,
            statementall.service_statement.new_total_settle_amount,
            STATEMENT_STATUS.getDesc(statementall.status),
            statementall.get_account().province.name if statementall.get_account().province else '',
            statementall.get_account().city.name if statementall.get_account().city else '',
            statementall.get_account().bank,
            statementall.get_account().subbranch,
            statementall.get_account().account_name,
            u'{} '.format(statementall.get_account().account_number or ''),
            statementall.merchant_confirm_time.strftime("%Y-%m-%d %H:%M:%S") if statementall.merchant_confirm_time
            else '',
        ))

        dt_maidan.append((
            statementall.doctor.name,
            statementall.statement_date,
            statementall.maidan_statement.settle_amount_cent / 100,
            STATEMENT_STATUS.getDesc(statementall.status),
            statementall.get_account().province.name if statementall.get_account().province else '',
            statementall.get_account().city.name if statementall.get_account().city else '',
            statementall.get_account().bank,
            statementall.get_account().subbranch,
            statementall.get_account().account_name,
            u'{} '.format(statementall.get_account().account_number or ''),
            statementall.merchant_confirm_time.strftime("%Y-%m-%d %H:%M:%S") if statementall.merchant_confirm_time
            else '',
        ))
    dt_service.title = u'美购对账单'
    dt_maidan.title = u'买单对账单'
    book = tablib.Databook((dt_service, dt_maidan))
    body = u'未结算对账单\n结算金额共计 %s' % statementalls.count()
    info_logger.info(u'导出结束')
    send_export_mail(u'导出未结算对账单', body, to_user_email, book)
