# coding=utf-8
# create by oldman at 2017/11/4
import json

import tablib
from celery import shared_task

from gm_types.doctor import DOCTOR_BILL_TYPE, DOCTOR_BILL_CLASS, DOCTOR_EXPRESS_COMPANY

from api.models import BDTransferMonthToBudan, BDTransferMonth, BuDan
from hera.utils import get_mail_instance, attach_title
from hippo.models.bill import BillApplyRecord, BillToTransferBudan
from rpc.tool.log_tool import info_logger, log_audit_hera

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_bill_excel_task(bill_ids, excel_type, category, to_user_email):
    """
    导出发票信息
    :param to_user_email:
    :return:
    """
    info_logger.info(u'导出开始')
    bills = BillApplyRecord.objects.filter(id__in=bill_ids)
    dt = tablib.Dataset()
    if excel_type == 1:  # 导出对账表格
        """佣金发票导出对账单增加快递公司、快递单号"""
        if category == DOCTOR_BILL_CLASS.COMMISSION:
            dt.headers = (u'申请ID', u'申请时间', u'医院', u'医院ID', u'金额', u'发票抬头', u'税务登记号',
                          u'注册场所地址', u'注册固定电话', u'基本开户行名称', u'银行账号', u'收件人姓名', u'联系电话',
                          u'收件地址', u'发票金额', u'开票时间', u'开票编号', u'结算周期', u'发票类型', u'快递公司', u'快递单号')
            for bill in bills:
                info = json.loads(bill.snapshot)['finance_info']
                dt.append((
                    bill.id,
                    bill.created_time.strftime("%Y-%m-%d %H:%M:%S"),
                    bill.doctor.hospital.name if bill.doctor.hospital else '',
                    bill.doctor.hospital.id if bill.doctor.hospital else '',
                    bill.amount,
                    info['bill_header'],
                    u'{} '.format(info['tax_id']),
                    info['register_address'],
                    u'{} '.format(info['register_phone']),
                    info['account_name'],
                    u'{} '.format(info['bank_account']),
                    info['receiver_name'],
                    u'{} '.format(info['receiver_phone']),
                    info['receiver_address'],
                    bill.amount,
                    bill.bill_time.strftime("%Y-%m-%d %H:%M:%S") if bill.bill_time else u'',
                    u','.join([item.bill_id for item in bill.applytobillids.all()]),
                    u','.join([str(record.statementall.statement_date) for record in bill.recordtoperiods.all()]),
                    DOCTOR_BILL_TYPE.getDesc(bill.bill_type),
                    DOCTOR_EXPRESS_COMPANY.getDesc(bill.express_company),
                    bill.express_id

                ))
        elif category == DOCTOR_BILL_CLASS.RECHANGE:
            """商桥发票导出对账单"""
            dt.headers = (
            u'申请ID', u'申请时间', u'医院', u'医院ID', u'金额', u'发票抬头', u'税务登记号', u'注册固定电话', u'基本开户行名称', u'银行账号', u'收件人姓名',
            u'联系电话', u'收件地址', u'发票金额', u'开票时间', u'开票编号', u'结算周期', u'发票类型', u'快递公司', u'快递单号')
            for bill in bills:
                info = json.loads(bill.snapshot)['finance_info']
                dt.append((
                    bill.id,
                    bill.created_time.strftime("%Y-%m-%d %H:%M:%S"),
                    bill.doctor.hospital.name if bill.doctor.hospital else '',
                    bill.doctor.hospital.id if bill.doctor.hospital else '',
                    bill.amount,
                    info['bill_header'],
                    u'{} '.format(info['tax_id']),
                    u'{} '.format(info['register_phone']),
                    info['account_name'],
                    u'{} '.format(info['bank_account']),
                    info['receiver_name'],
                    u'{} '.format(info['receiver_phone']),
                    info['receiver_address'],
                    bill.amount,
                    bill.bill_time.strftime("%Y-%m-%d %H:%M:%S") if bill.bill_time else u'',
                    u','.join([item.bill_id for item in bill.applytobillids.all()]),
                    u','.join([str(record.statementall.statement_date) for record in bill.recordtoperiods.all()]),
                    DOCTOR_BILL_TYPE.getDesc(bill.bill_type),
                    DOCTOR_EXPRESS_COMPANY.getDesc(bill.express_company),
                    bill.express_id

                ))
        else:
            """转诊补单发票导出对账单"""
            dt.headers = (
                u'申请ID', u'转诊补单ID', u'是否补齐', u'申请时间', u'医院', u'医院ID', u'金额', u'发票抬头', u'税务登记号',
                u'注册场所地址', u'注册固定电话', u'基本开户行名称', u'银行账号', u'收件人姓名', u'联系电话',
                u'收件地址', u'发票金额', u'开票时间', u'开票编号', u'发票类型', u'快递公司', u'快递单号')
            for bill in bills:
                info = json.loads(bill.snapshot)['finance_info']
                budan_ids_list = list(BillToTransferBudan.objects.filter(billapplyrecord_id=bill.id).values_list('budan_id', flat=True))
                budan_ids = u','.join(budan_ids_list)
                has_paids = BDTransferMonthToBudan.objects.filter(budan_id__in=budan_ids_list).values_list("has_paid",flat=True)
                is_finished =  u'是' if all(has_paids) else u'否'
                fill_amount = 0
                for budan_id in budan_ids_list:
                    fill_amount += BuDan.objects.get(id=budan_id).payment

                dt.append((
                    bill.id,
                    budan_ids,
                    is_finished,
                    bill.created_time.strftime("%Y-%m-%d %H:%M:%S"),
                    bill.doctor.hospital.name if bill.doctor.hospital else '',
                    bill.doctor.hospital.id if bill.doctor.hospital else '',
                    fill_amount,
                    info['bill_header'],
                    u'{} '.format(info['tax_id']),
                    info['register_address'],
                    u'{} '.format(info['register_phone']),
                    info['account_name'],
                    u'{} '.format(info['bank_account']),
                    info['receiver_name'],
                    u'{} '.format(info['receiver_phone']),
                    info['receiver_address'],
                    bill.amount,
                    bill.bill_time.strftime("%Y-%m-%d %H:%M:%S") if bill.bill_time else u'',
                    u','.join([item.bill_id for item in bill.applytobillids.all()]),
                    DOCTOR_BILL_TYPE.getDesc(bill.bill_type),
                    DOCTOR_EXPRESS_COMPANY.getDesc(bill.express_company),
                    bill.express_id
                ))
        dt.title = u'发票对账表格'
        body = u'发票对账表格\n共计 %s 条' % bills.count()
    else:
        if category == DOCTOR_BILL_CLASS.COMMISSION:
            dt.headers = (u'申请ID', u'医院', u'医院ID', u'金额', u'发票抬头', u'税务登记号',
                          u'注册场所地址', u'注册固定电话', u'基本开户行名称', u'银行账号', u'收件人姓名', u'联系电话',
                          u'收件地址', u'电子邮箱', u'结算周期', u'发票金额', u'发票类型')
            for bill in bills:
                info = json.loads(bill.snapshot)['finance_info']
                dt.append((
                    bill.id,
                    bill.doctor.hospital.name if bill.doctor.hospital else '',
                    bill.doctor.hospital.id if bill.doctor.hospital else '',
                    bill.amount,
                    info['bill_header'],
                    u'{} '.format(info['tax_id']),
                    info['register_address'],
                    u'{} '.format(info['register_phone']),
                    info['account_name'],
                    u'{} '.format(info['bank_account']),
                    info['receiver_name'],
                    u'{} '.format(info['receiver_phone']),
                    info['receiver_address'],
                    info.get('email', u''),
                    u','.join([str(record.statementall.statement_date) for record in bill.recordtoperiods.all()]),
                    bill.amount,
                    DOCTOR_BILL_TYPE.getDesc(bill.bill_type)
                ))
        else:
            dt.headers = (u'申请ID', u'充值订单ID', u'医院', u'医院ID', u'金额', u'发票抬头', u'税务登记号',
                          u'注册场所地址', u'注册固定电话', u'基本开户行名称', u'银行账号', u'收件人姓名', u'联系电话',
                          u'收件地址', u'电子邮箱', u'发票金额', u'发票类型')
            for bill in bills:
                info = json.loads(bill.snapshot)['finance_info']
                rechange_ids = json.loads(bill.snapshot)['rechange_ids']
                dt.append((
                    bill.id,
                    u','.join(map(str, rechange_ids)),
                    bill.doctor.hospital.name if bill.doctor.hospital else '',
                    bill.doctor.hospital.id if bill.doctor.hospital else '',
                    bill.amount,
                    info['bill_header'],
                    u'{} '.format(info['tax_id']),
                    info['register_address'],
                    u'{} '.format(info['register_phone']),
                    info['account_name'],
                    u'{} '.format(info['bank_account']),
                    info['receiver_name'],
                    u'{} '.format(info['receiver_phone']),
                    info['receiver_address'],
                    info.get('email',u''),
                    bill.amount,
                    DOCTOR_BILL_TYPE.getDesc(bill.bill_type)
                ))

        dt.title = u'发票开票表格'
        body = u'发票开票表格\n共计 %s 条' % bills.count()
    info_logger.info(u'导出结束')
    send_export_mail(u'发票表格', body, to_user_email, dt)
