# coding=utf-8
import json
import tablib

from datetime import datetime, timedelta
from celery import shared_task, current_task
from django.conf import settings
from django.db.models import Q
from gm_types.gaia import PAYMENT_CHANNEL, DOCTOR_SECKILL_APPLY_STATUS, DIARY_ORDER_TYPE, BUDAN_STATUS, BUDAN_TYPE
from gm_types.gaia import DIARY_CONTENT_LEVEL, ADVER_MANAGEMENT_POSITION_TYPE, OPERATION_LOCATION_TYPE, ORDER_SOURCE

from api.models import AlipayAccoutMaintenance, Special, SpecialItem, User, BDTransferSingleRecord, Merchant, \
    MerchantRelevance
from api.models.types import NEW_CASH_BACK_STATUS, REFUND_STATUS
from api.models.types import ORDER_STATUS
from api.models.doctor import Doctor
from api.models.hospital import Hospital
from api.models.special import DoctorSeckillApply
from api.models.coupon import CouponInfo
from api.models.order import Order
from api.models.budan import BuDan, BuDanRealtedOrder
from api.models.bd_transfer import BDTransferMonth
from hera.models import SendEmailTaskLog
from talos.models.diary import Diary
from themis.models import Team
from hippo.models.doctor import DoctorCard


from gaia.settings import HERA_PAY_EMAIL
from gaia.settings import HERA_EMAIL_NAME
from rpc.tool.queryset_tool import queryset_enc, big_qs_iter, big_id_iter
from rpc.tool.log_tool import info_logger, log_audit_hera, logging_exception
from rpc.all import get_rpc_remote_invoker
from rpc.context import get_gaia_local_invoker
from hera.queries.insurance import ServiceItemDQ
from hera.utils import get_mail_instance, attach_title, get_tag_chain
from search.utils.diary import filter_diary, _get_penalty_score

from pay.models.statement import Statement
from gm_types.trade import STATEMENT_STATUS

from maidan.models.statement import MaidanStatement
from gm_types.gaia import MAIDAN_STATEMENT_STATUS, TRANSFER_SOURCE
from gm_types.gaia import BUDAN_STATUS
from gm_types.gaia import OPERATION_LOCATION_TYPE
from gm_types.gaia import COUPON_TYPES
from gm_types.gaia import DOCTOR_TYPE

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


def real_partner(doctor, end_time):
    if doctor is None or end_time is None:
        return ''
    now_partner = doctor.business_partener
    change_record = doctor.docbusinessrecord_set.filter(action_time__lte=end_time).last()
    return change_record.to_business if change_record else now_partner


@shared_task
def export_orders_excel(orders, user):
    """
     导出订单Excel
    """
    task_id = current_task.request.id
    now = str(datetime.now())
    if isinstance(orders, dict):
        orders = queryset_enc(orders)
    orders = orders.order_by('created_time')
    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id,
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'导出订单',
        total=orders.count(),
    )

    if not user.email:
        return
    info_logger.info(u'导出开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'订单号', u'userID', u'userID关联医生姓名', u'userID关联医生医院',
        u'美购ID', u'美购名', u'属性ID', u'多属性', u'美购当期医生', u'美购当期医院',
        u'售出医生ID', u'售出医生姓名', u'售出医院ID', u'售出医院', u'售出商务',
        u'验证医生ID', u'验证医生', u'验证医院ID', u'验证医院', u'验证商务',
        u'订单总价', u'预约金', u'抽成', u'自营成本', u'返款金额', u'使用预付款券id',
        u'预付款券抵扣金额', u'预付款券更美承担抵扣金额', u'预付款券医生承担抵扣金额', u'使用尾款券id', u'尾款券抵扣金额', u'美分抵扣金额', u'创建时间', u'验证时间', u'当前状态',
        u'关联专场', u'是否转服务', u'商务', u'商务组', u'结算单id', u'支付方式', u'订单来源'
    ]

    total_settle_price = 0
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for order_id in big_id_iter(orders):
        try:
            order = Order.objects.get(id=order_id)
        except:
            continue
        service_snapshot_json = json.loads(order.service_snapshot)
        try:
            coupon_id = CouponInfo.objects.get(id=service_snapshot_json.get('coupon_id')).coupon_id
        except:
            coupon_id = ''
        try:
            user_doctor = getattr(order.user, 'doctor', None)
        except:
            user_doctor = ''

        try:
            user_hospital = user_doctor.hospital
        except:
            user_hospital = None

        service_snapshot = order.servicesnapshot
        op_doc = getattr(order.operate_user, 'doctor', None)
        try:
            op_hospital = op_doc.hospital
        except:
            op_hospital = None

        doctor = order.service.doctor
        if doctor.business_group:
            team = Team.objects.filter(id=doctor.business_group).first()
            group = team.name if team else ''
        else:
            group = ''

        service_snapshot_hospital = getattr(service_snapshot.doctor, 'hospital', None)
        return_fee = order.settle_data()['settle_payment']
        order_cost = getattr(order, 'ordercost', None)

        coupon_info = {x['coupon_type']: x for x in order.get_order_coupon_infos()}
        x = (
            order.id,
            order.user.id,
            user_doctor.name if user_doctor else '',
            user_hospital.name if user_hospital else '',
            order.service_id,
            service_snapshot.name,
            u'',  # sku后得到
            order.order_multiattribute,
            order.service.doctor.name,
            order.service.doctor.hospital.name,
            service_snapshot.doctor_id,
            service_snapshot.doctor.name,
            service_snapshot_hospital.id if service_snapshot_hospital else '',
            service_snapshot_hospital.name if service_snapshot_hospital else '',
            getattr(real_partner(service_snapshot.doctor, order.pay_time), 'username', ''),
            op_doc.id if op_doc else '',
            op_doc.name if op_doc else '',
            op_hospital.id if op_hospital else '',
            op_hospital.name if op_hospital else '',
            getattr(real_partner(op_doc, order.validate_time), 'username', ''),
            order.service_price,
            service_snapshot.pre_payment_price,
            order.discount,
            order_cost.cost_price if order_cost else u'无',
            return_fee,
            coupon_info.get(COUPON_TYPES.PLATFORM, {}).get('coupon_id', ''),
            coupon_info.get(COUPON_TYPES.PLATFORM, {}).get('platform_coupon_deduction', ''),
            coupon_info.get(COUPON_TYPES.PLATFORM, {}).get('coupon_gengmei_value', 0),
            coupon_info.get(COUPON_TYPES.PLATFORM, {}).get('coupon_doctor_value', 0),
            coupon_info.get(COUPON_TYPES.DOCTOR, {}).get('coupon_id', ''),
            coupon_info.get(COUPON_TYPES.DOCTOR, {}).get('doctor_coupon_deduction', 0),
            order.points_deduction or 0,
            order.created_time,
            order.validate_time or '',
            ORDER_STATUS.getDesc(order.status),
            order.activity_id if order.activity_id else '',
            order.is_ordertoservice,
            getattr(doctor.business_partener, 'username', ''),
            group,
            order.settlement_id,
            PAYMENT_CHANNEL.getDesc(order.payment_channel),
            ORDER_SOURCE.getDesc(order.source),
        )

        dt.append(x)
        total_settle_price += return_fee

    body = u'订单导出\n结算金额共计 %s' % total_settle_price
    info_logger.info(u'导出结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'订单导出', body, user.email, dt)


@shared_task
def export_channel_urls_excel(wanghongs, to_user_email):
    """
        导出一级分销商ID列表excel
    """
    if isinstance(wanghongs, dict):
        wanghongs = queryset_enc(wanghongs)
    dt = tablib.Dataset()
    dt.headers = [
        u'渠道名', u'一级分销商id', u'一级分销商url'
    ]
    channel_name = u''
    if wanghongs.exists():
        channel_name = wanghongs[0].company.name
        for wanghong in wanghongs:
            x = (
                wanghong.company.name,
                wanghong.code,
                u'm.gmei.com/fenxiao/register/{}/'.format(wanghong.code)
            )
            dt.append(x)
    body = u'{}对应的一级分销商数量共{}条'.format(channel_name, len(wanghongs))
    send_export_mail(u'{}对应的一级分销商id、url'.format(channel_name), body, to_user_email, dt)


@shared_task
def export_fenxiao_order_excel(fenxiaoorders, to_user_email):
    """
        导出分销已付款信息excel
    """
    if isinstance(fenxiaoorders, dict):
        fenxiaoorders = queryset_enc(fenxiaoorders)
    if not to_user_email:
        return
    dt = tablib.Dataset()
    dt.headers = [
        u'渠道', u'一级分销ID', u'订单号', u'美购名', u'当前状态', u'商务',
    ]
    if fenxiaoorders.exists():
        for fenxiaoorder in fenxiaoorders:
            x = (
                fenxiaoorder.wanghong.company.name,
                fenxiaoorder.wanghong.code,
                fenxiaoorder.order.id,
                fenxiaoorder.order.service.name,
                ORDER_STATUS.getDesc(fenxiaoorder.order.status),
                getattr(fenxiaoorder.order.service.doctor.business_partener, 'username', '')
            )
            dt.append(x)
    body = u'分销已付款订单信息{}条'.format(len(fenxiaoorders))
    send_export_mail(u'分销已付款信息', body, to_user_email, dt)


@shared_task
def export_diary_rank_top1000(to_user_email):
    """
        导出首页日记本top1000
    """
    # todo 可删，英才已确认 180314
    dt = tablib.Dataset()
    diary_ids = []
    doctor_ids = []
    for i in range(10):
        data = filter_diary(offset=i * 100, size=100, sort_type=DIARY_ORDER_TYPE.INDEX)
        diary_ids += data['diary_ids']
    dt.headers = [
        u'日记本ID', u'排序得分', u'标题', u'用户名', u'内容质量', u'医生', u'医院', u'医生所在城市',
        u'创建时间', u'更新时间', u'日记帖', u'点赞数', u'回复数', u'收入贡献分', u'项目标签', u'加权操作',
        u'医生医院重复扣分', u'最终得分',
    ]
    for diary_id in diary_ids:
        try:
            diary = Diary.objects.get(id=diary_id)
            heat_score, audit_score, choucheng_score = diary.get_index_rank()
            diary_score = heat_score * settings.DIARY_SCORE_WEIGHT['HEAT_SCORE_WEIGHT'] + \
                          audit_score * settings.DIARY_SCORE_WEIGHT['AUDIT_SCORE_WEIGHT'] + \
                          choucheng_score * settings.DIARY_SCORE_WEIGHT['CHOUCHENG_SCORE_WEIGHT']

            additional_score = diary.diary_rank.additional_score if getattr(diary, 'diary_rank', False) else 0

            if diary.doctor_id:
                doctor_ids.append(diary.doctor_id)
                doctor_times = doctor_ids.count(diary.doctor_id)
                penalty_score = _get_penalty_score(doctor_times, diary_score + additional_score)
            else:
                penalty_score = 0.0

            try:
                doctor_city = diary.doctor.hospital.city.name
            except:
                doctor_city = u''
            x = (
                diary.id,
                diary_score,
                diary.title,
                diary.user.last_name,
                DIARY_CONTENT_LEVEL.getDesc(diary.content_level),
                getattr(diary.doctor, 'name', ''),
                getattr(diary.hospital, 'name', ''),
                doctor_city,
                diary.created_time,
                diary.last_modified,
                diary.topic_num,
                diary.like_num,
                diary.reply_num,
                choucheng_score,
                u'、'.join(diary.tags.values_list('name', flat=True)),
                additional_score,
                penalty_score,
                diary_score + additional_score - penalty_score,
            )
            dt.append(x)
        except:
            continue
    body = u'首页日记本排序top1000'
    send_export_mail(u'首页日记本排序top1000', body, to_user_email, dt)


@shared_task
def insurance_serviceitem_excel_task(options, select_all_page, email):
    if select_all_page:
        options.pop('paging')
        options.pop('columns')
        paging = None
    else:
        options.pop('columns')
        paging = options.pop('paging')

    dqobj = ServiceItemDQ(init_q=~Q(service__insurance=0))
    objs = dqobj.build_queryset(**options)

    pay_time_query = dqobj.kwargs.get('pay_time_query', Q(pay_time__isnull=False))
    orders = Order.objects.using(dqobj.using).filter(pay_time_query)
    item_keys = orders.values_list('service_item_key', flat=True)
    objs = objs.filter(key__in=item_keys).exclude(key='')
    if paging:
        # 限制每页数据的最大值
        length = paging['length'] if paging['length'] < settings.COUNT_LIMIT else settings.COUNT_LIMIT
        objs = objs[paging['start']: paging['start'] + length]
    item_key2orders = {}
    for order in orders:
        if item_key2orders.get(order.service_item_key, None):
            item_key2orders.get(order.service_item_key).append(order.id)
        else:
            item_key2orders[order.service_item_key] = [order.id]

    itemkey2insurancenum = get_rpc_remote_invoker()['plutus/insurance/order/count_batch'](
        order_id_map=item_key2orders).unwrap()
    dt = tablib.Dataset()
    dt.headers = [
        u'保险ID', u'tag', u'美购名', u'多属性名', u'更美价', u'已付款订单数', u'已付款订单数(买了保险)'
    ]
    for item in objs:
        x = (
            item.service.insurance,
            item.service.tag_name,
            item.service.name,
            ','.join(item.items_name),
            item.gengmei_price,
            len(item_key2orders.get(item.key, [])),
            itemkey2insurancenum.get(item.key, 0),
        )
        dt.append(x)
    body = u'保险分流数据{}条'.format(len(objs))
    send_export_mail(u'保险分流数据', body, email, dt)


@shared_task
def export_not_settle_statement(email):
    statements = Statement.history_objects.filter(status__in=[STATEMENT_STATUS.CHECKED, STATEMENT_STATUS.DEFEAT])
    dt = tablib.Dataset()
    dt.headers = [
        u'结算对象', u'结算周期', u'结算金额', u'结算状态', u'省', u'市', u'开户银行', u'支行/分行', u'户名', u'帐号', u'商户确认时间', u'财务结算时间'
    ]
    for statement in statements:
        account = statement.get_account()

        x = (
            statement.doctor.name,
            statement.statement_date,
            statement.settle_amount,
            STATEMENT_STATUS.getDesc(statement.status),
            getattr(account.province, 'name', ''),
            getattr(account.city, 'name', ''),
            account.bank,
            account.subbranch,
            account.account_name,
            u' {}'.format(account.account_number),
            str(statement.merchant_confirm_time),
            str(statement.settle_time),
        )
        dt.append(x)
    body = u'未结算对账单(财务)共{}条'.format(statements.count())
    send_export_mail(u'未结算对账单(财务)', body, email, dt)


@shared_task
def export_not_settle_maidan_statement(email):
    statements = MaidanStatement.history_objects.filter(status=MAIDAN_STATEMENT_STATUS.CREATED)
    dt = tablib.Dataset()
    dt.headers = [
        u'结算对象', u'结算周期', u'结算金额', u'结算状态', u'省', u'市', u'开户银行', u'户名', u'帐号'
    ]
    for statement in statements:
        account = getattr(statement.doctor.merchant, 'account', None)
        x = (
            statement.doctor.name,
            statement.statement_date,
            statement.settle_amount_cent * 0.01,
            MAIDAN_STATEMENT_STATUS.getDesc(statement.status),
            statement.doctor.merchant.account.province.name if account and account.province else '',
            statement.doctor.merchant.account.city.name if account and account.city else '',
            statement.doctor.merchant.account.bank if account else '',
            statement.doctor.merchant.account.account_name if account else '',
            u' {}'.format(statement.doctor.merchant.account.account_number) if account else '',
        )
        dt.append(x)
    body = u'未结算买单对账单(财务)共{}条'.format(statements.count())
    send_export_mail(u'未结算买单对账单(财务)', body, email, dt)


@shared_task
def export_advertisemanagement_excel(advertise_management, to_user_email, adver_type):
    """
        导出广告位信息excel
    """
    if isinstance(advertise_management, dict):
        advertise_management = queryset_enc(advertise_management)
    if not to_user_email:
        return
    dt = tablib.Dataset()
    if adver_type == '0':
        dt.headers = [
            u'广告位ID', u'美购ID', u'美购名称', u'展示城市', u'关联医生', u'关联机构',
            u'关联商务', u'展示顺序', u'展示位置', u'广告位关联tag', u'搜索词', u'开始日期',
            u'结束日期', u'上线', u'推广tips',
        ]
        for ad_management in big_qs_iter(advertise_management):
            search_words = ad_management.get_search_words
            position = ad_management.get_show_position
            position_name = []
            for pos in position:
                position_name.append(ADVER_MANAGEMENT_POSITION_TYPE.getDesc(pos))
            tags = list(ad_management.tags.values_list('name', flat=True))
            x = (
                ad_management.id,
                ad_management.service.id if ad_management.service else '',
                ad_management.service.name if ad_management.service else '',
                ad_management.service.doctor.hospital.city.name if ad_management.service and ad_management.service.doctor.hospital else '',
                ad_management.service.doctor.name if ad_management.service and ad_management.service.doctor else '',
                ad_management.service.doctor.hospital.name if ad_management.service and ad_management.service.doctor.hospital else '',
                ad_management.service.doctor.business_partener.username if ad_management.service and ad_management.service.doctor.business_partener else '',
                ad_management.ordering,
                '/'.join(position_name),
                '/'.join(tags),
                ';'.join(search_words),
                ad_management.start_time if ad_management.start_time else '',
                ad_management.end_time if ad_management.end_time else '',
                ad_management.is_online,
                ad_management.extend_tip.tip_name if ad_management.extend_tip else '',
            )
            dt.append(x)
        body = u'广告位美购信息{}条'.format(len(advertise_management))
        send_export_mail(u'广告位美购', body, to_user_email, dt)
    else:
        dt.headers = [
            u'广告位ID', u'医生ID', u'医生名称', u'关联机构', u'关联商务', u'展示城市',
            u'展示顺序', u'展示位置', u'搜索词', u'开始日期', u'结束日期', u'上线',
            u'推广tips',
        ]
        for ad_management in big_qs_iter(advertise_management):
            search_words = ad_management.get_search_words
            position = ad_management.get_show_position
            position_name = []
            for pos in position:
                position_name.append(ADVER_MANAGEMENT_POSITION_TYPE.getDesc(pos))
            x = (
                ad_management.id,
                ad_management.doctor.id if ad_management.doctor else '',
                ad_management.doctor.name if ad_management.doctor else '',
                ad_management.doctor.hospital.name if ad_management.doctor else '',
                ad_management.doctor.business_partener.username if ad_management.doctor.business_partener and ad_management.doctor else '',
                ad_management.doctor.hospital.city.name if ad_management.doctor else '',
                ad_management.ordering,
                '/'.join(position_name),
                ';'.join(search_words),
                ad_management.start_time if ad_management.start_time else '',
                ad_management.end_time if ad_management.end_time else '',
                ad_management.is_online,
                ad_management.extend_tip.tip_name if ad_management.extend_tip else '',
            )
            dt.append(x)
        body = u'广告位专家信息{}条'.format(len(advertise_management))
        send_export_mail(u'广告位专家', body, to_user_email, dt)


@shared_task
def export_self_support_excel(orders, user):
    """
        导出自营订单Excel
    """
    task_id = current_task.request.id
    now = str(datetime.now())
    if isinstance(orders, dict):
        orders = queryset_enc(orders)

    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id,
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'导出自营订单',
        total=orders.count(),
    )

    if not user.email:
        return
    info_logger.info(u'导出自营订单Excel开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'订单号', u'userID', u'美购ID', u'美购名', u'属性ID', u'多属性',
        u'美购当期医生', u'美购当期医院',
        u'售出医生ID', u'售出医生姓名', u'售出医院ID', u'售出医院', u'售出商务',
        u'验证医生ID', u'验证医生', u'验证医院ID', u'验证医院', u'验证商务',
        u'是否自营', u'手术地点', u'是否手术',
        u'订单总价', u'预约金', u'抽成', u'返款金额',
        u'使用美券ID', u'美券抵扣金额', u'更美承担美券抵扣金额', u'医生发的美券金额',
        u'大促活动', u'成本', u'抽成比例', u'实际抽成', u'更美->医生最终返款额', u'更美->机构最终返款额',
        u'医生承担美券抵扣金额', u'美分抵扣金额', u'创建时间', u'验证时间', u'当前状态', u'关联专场', u'手术地点类型'
    ]
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for order_id in big_id_iter(orders):
        try:
            order = Order.objects.get(id=order_id)
        except:
            continue
        service_snapshot = order.servicesnapshot
        op_doc = getattr(order.operate_user, 'doctor', None)
        try:
            op_hospital = op_doc.hospital
        except:
            op_hospital = None

        service_snapshot_hospital = getattr(service_snapshot.doctor, 'hospital', None)
        return_fee = order.settle_data()['settle_payment']

        operation_location = OPERATION_LOCATION_TYPE.getDesc(order.operation_location_type)
        if order.operation_location_type == OPERATION_LOCATION_TYPE.WHITE_LIST:
            try:
                operation_location = Hospital.objects.get(id=order.operation_hospital_id).name
            except:
                operation_location = order.operation_hospital_id
        try:
            activity_name = Special.objects.get(id=order.activity_id).title
        except:
            activity_name = ''

        coupon_info = order.order_coupon_data() or {}
        doctor_coupon_value = coupon_info.get('doctor_coupon_deduction', 0) if service_snapshot.coupon_type == COUPON_TYPES.DOCTOR else 0
        discount_rate = int(order.discount * 100.0/order.service_price)
        if order.operation_location_type == OPERATION_LOCATION_TYPE.WHITE_LIST:
            real_discount = int((order.service_price - service_snapshot.cost_price) * discount_rate * 0.01)
            gengmei_to_doctor = real_discount - coupon_info.get('coupon_doctor_value', 0) - doctor_coupon_value
            gengmei_to_hospital = service_snapshot.pre_payment_price - 2 * real_discount + coupon_info.get('coupon_doctor_value', 0) + doctor_coupon_value
            try:
                operation_location = Hospital.objects.get(id=order.operation_hospital_id)
            except:
                operation_location = order.operation_hospital_id
        else:
            operation_location = OPERATION_LOCATION_TYPE.getDesc(order.operation_location_type)
            real_discount = order.discount
            gengmei_to_doctor = service_snapshot.pre_payment_price - real_discount - coupon_info.get('coupon_doctor_value', 0) - doctor_coupon_value
            gengmei_to_hospital = 0

        x = (
            order.id,
            order.user.id,
            order.service_id,
            service_snapshot.name,
            service_snapshot.item_key,
            order.order_multiattribute,
            order.service.doctor.name,
            order.service.doctor.hospital.name,
            service_snapshot.doctor_id,
            service_snapshot.doctor.name,
            service_snapshot_hospital.id if service_snapshot_hospital else '',
            service_snapshot_hospital.name if service_snapshot_hospital else '',
            getattr(service_snapshot.business_partener_at_paid, 'username', ''),
            op_doc.id if op_doc else '',
            op_doc.name if op_doc else '',
            op_hospital.id if op_hospital else '',
            op_hospital.name if op_hospital else '',
            getattr(service_snapshot.business_partener_at_validate, 'username', ''),
            u'是' if order.is_self_support else u'否',
            operation_location,
            service_snapshot.is_operation,
            order.service_price,
            service_snapshot.pre_payment_price,
            order.discount,
            return_fee,
            service_snapshot.coupon_id,
            order.coupon_deduction or 0,
            coupon_info.get('coupon_gengmei_value', 0),
            doctor_coupon_value,
            activity_name,
            service_snapshot.cost_price,
            u'{}%'.format(discount_rate),
            real_discount,
            gengmei_to_doctor,
            gengmei_to_hospital,
            coupon_info.get('coupon_doctor_value', 0),
            order.points_deduction or 0,
            order.created_time,
            order.validate_time or '',
            ORDER_STATUS.getDesc(order.status),
            order.activity_id if order.activity_id else '',
            OPERATION_LOCATION_TYPE.getDesc(order.operation_location_type),
        )

        dt.append(x)

    info_logger.info(u'导出自营订单Excel结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'导出自营订单Excel', u'导出自营订单Excel', user.email, dt)


@shared_task
def export_budan_support_excel(datas, user):
    """
        导出补单列表
    """
    task_id = current_task.request.id
    now = str(datetime.now())
    if isinstance(datas, dict):
        datas = queryset_enc(datas)

    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id,
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'补单列表',
        total=datas.count(),
    )

    if not user.email:
        return
    info_logger.info(u'导出补单列表开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'补单ID', u'用户名', u'商务', u'城市', u'医院', u'备注开发项目', u'创建时间',
        u'项目总额', u'需补佣金', u'备注', u'创建人', u'状态', u'补单类型', u'关联订单信息'
    ]
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for budan_id in big_id_iter(datas):
        try:
            budan = BuDan.objects.get(id=budan_id)
        except:
            continue

        related_order_ids = BuDanRealtedOrder.get_order_ids_by_budan_id(budan.id)
        if related_order_ids:
            related_order_data = BuDanRealtedOrder.batch_get_to_dict_data_by_order_ids(related_order_ids)
            desc_related_order_data = ''
            for i, _data in enumerate(related_order_data):
                _data['num'] = i + 1
                desc_related_order_data += '订单{num}: {order_id} {commission_rate} {gengmei_price} ' \
                                           '{commission_amount} {additional_amount}\n'.format(**_data)
        else:
            desc_related_order_data = ''


        if budan.dev_projects_json:
            dev_projects_json = "\n".join([u"项目%d: %s %s" % (i + 1, item['name'], item['money'])
                           for i, item in enumerate(budan.dev_projects_json)])
        else:
            dev_projects_json = ''
        doctor = None
        try:
            doctor = budan.doctor
            x = (
                budan.id,
                budan.user.last_name if budan.user else '',
                doctor.business_partener.username if getattr(doctor,'business_partener',None) else '',
                doctor.hospital.city.name if getattr(doctor,'hospital',None) else '',
                doctor.hospital.name if getattr(doctor,'hospital',None) else '',
                dev_projects_json,
                budan.create_time,
                budan.extra_consume,
                budan.payment,
                budan.comment,
                budan.create_user.username if budan.create_user else '',
                BUDAN_STATUS.getDesc(budan.status),
                BUDAN_TYPE.getDesc(budan.budan_type),
                desc_related_order_data
            )
            dt.append(x)
        except:
            x = (
                budan.id,
                budan.user.last_name if budan.user else '',
                '',
                '',
                '',
                dev_projects_json,
                budan.create_time,
                budan.extra_consume,
                budan.payment,
                budan.comment,
                budan.create_user.username if budan.create_user else '',
                BUDAN_STATUS.getDesc(budan.status),
                BUDAN_TYPE.getDesc(budan.budan_type),
                desc_related_order_data
            )
            dt.append(x)

    info_logger.info(u'导出补单列表结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'补单列表', u'补单列表', user.email, dt)


@shared_task
def export_bdtransfermonth_support_excel(datas, user):
    """
        导出转诊补单管理
    """
    task_id = current_task.request.id
    now = str(datetime.now())
    if isinstance(datas, dict):
        datas = queryset_enc(datas)

    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id,
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'转诊补单管理列表',
        total=datas.count(),
    )

    if not user.email:
        return
    info_logger.info(u'导出转诊补单管理列表开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'ID', u'商户ID', u'商户名称', u'省份', u'城市', u'医生名称', u'医生ID', u'商务',
        u'转诊补单数量', u'时间', u'当月佣金补交状态', u'转诊项目总金额', u'应补佣金总额', u'已补佣金总额'
    ]
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for bdtransfermonth_id in big_id_iter(datas):
        try:
            bdtransfermonth = BDTransferMonth.objects.get(id=bdtransfermonth_id)
        except:
            continue
        is_finished = u'是' if bdtransfermonth.is_finished else u'否'

        x = (
            bdtransfermonth.id,
            bdtransfermonth.doctor.d_merchant.id if getattr(bdtransfermonth.doctor,'d_merchant',None) else '',
            bdtransfermonth.doctor.name,
            bdtransfermonth.doctor.hospital.city.province if bdtransfermonth.doctor.hospital else '',
            bdtransfermonth.doctor.hospital.city if bdtransfermonth.doctor.hospital else '',
            bdtransfermonth.doctor.name,
            bdtransfermonth.doctor.id,
            bdtransfermonth.doctor.business_partener.username if bdtransfermonth.doctor.business_partener else '',
            bdtransfermonth.month_budans.count(),
            bdtransfermonth.month_at,
            is_finished,
            bdtransfermonth.total_amount,
            bdtransfermonth.should_pay,
            bdtransfermonth.already_pay
        )
        dt.append(x)

    info_logger.info(u'导出转诊补单管理列表结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'转诊补单管理列表', u'转诊补单管理列表', user.email, dt)

@shared_task
def export_bdtransfermonthlywithdrawal_support_excel(datas, user):
    """
        导出转诊补单管理
    """
    task_id = current_task.request.id
    now = str(datetime.now())
    if isinstance(datas, dict):
        datas = queryset_enc(datas)

    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id,
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'转诊跨月撤销列表',
        total=datas.count(),
    )

    if not user.email:
        return
    info_logger.info(u'导出转诊跨月撤销列表开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'ID', u'商户ID', u'商户名称',  u'商务', u'省份', u'城市', u'时间', u'本月转诊数量',
        u'转诊项目总金额', u'本月应补佣金总金额', u'跨月撤销转诊数量', u'跨月撤销转诊项目总金额',
        u'跨月撤销转诊应补金额', u'本月实际转诊项目总额', u'本月实际应补佣金总金额'
    ]
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for bdtransfermonth_id in big_id_iter(datas):
        try:
            bdtransfermonth = BDTransferMonth.objects.get(id=bdtransfermonth_id)
        except:
            continue
        monthly_total_amount = bdtransfermonth.monthly_total_amount
        monthly_should_pay = bdtransfermonth.monthly_should_pay
        total_amount = bdtransfermonth.total_amount
        should_pay = bdtransfermonth.should_pay
        all_total_amount = monthly_total_amount + total_amount
        all_should_pay = monthly_should_pay + should_pay

        x = (
            bdtransfermonth.id,
            bdtransfermonth.doctor.d_merchant.id,
            bdtransfermonth.doctor.name,
            bdtransfermonth.doctor.business_partener.username,
            bdtransfermonth.doctor.hospital.city.province,
            bdtransfermonth.doctor.hospital.city,
            bdtransfermonth.month_at,
            bdtransfermonth.month_budans.count(),
            all_total_amount,
            all_should_pay,
            bdtransfermonth.monthlywithdrawal_budans.count(),
            monthly_total_amount,
            monthly_should_pay,
            total_amount,
            should_pay,
        )
        dt.append(x)

    info_logger.info(u'导出转诊跨月撤销列表结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'转诊跨月撤销列表', u'转诊跨月撤销列表', user.email, dt)


@shared_task
def export_market_excel(user_ids, tag_name, user):
    """
        导出营销标签用户信息
    """
    task_id = current_task.request.id
    now = str(datetime.now())

    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id if task_id else "local_host_task",
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'导出营销标签用户信息',
        total=len(user_ids),
    )

    if not user.email:
        return
    info_logger.info(u'导出营销标签用户信息Excel开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'营销标签', u'userID'
    ]
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for user_id in user_ids:
        x = (
            tag_name,
            user_id,
        )

        dt.append(x)

    info_logger.info(u'导出营销标签用户信息Excel结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'导出营销标签用户信息Excel', u'导出营销标签用户信息Excel', user.email, dt)


@shared_task
def export_bdtransfer_dispatch_excel(objs, user):
    """
     导出派单Excel
    """
    task_id = current_task.request.id
    now = str(datetime.now())
    if isinstance(objs, dict):
        objs = queryset_enc(objs)
    log_obj = SendEmailTaskLog.objects.create(
        task_id=task_id,
        user_id=user.id,
        user_name=user.last_name,
        send_email=user.email,
        status=u'STARTED',
        start_time=now,
        title=u'转诊线索派单导出',
        total=objs.count(),
    )
    if not user.email:
        return
    info_logger.info(u'导出开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'派单ID', u'线索ID', u'用户来源', u'创建人', u'创建时间', u'派单商户', u'客户姓名',
        u'用户手机号', u'派单项目', u'派单时间', u'派单人', u'是否提交消费信息',
        u'成单人', u'成单时间', u'成单金额', u'成单佣金金额',
    ]
    log_obj.status = u'PROGRESS'
    log_obj.save()
    for obj_id in big_id_iter(objs):
        try:
            obj = BDTransferSingleRecord.objects.get(id=obj_id)
        except:
            continue
        try:
            merchant_name = MerchantRelevance.objects.get(doctor=obj.doctor).merchant.name
        except:
            merchant_name = ''
        x = (
            obj.id,
            obj.dbtransfer.id,
            TRANSFER_SOURCE.getDesc(obj.dbtransfer.source),
            User.objects.filter(id=obj.dbtransfer.creator).first().username,
            obj.dbtransfer.create_time and obj.dbtransfer.create_time.strftime('%Y-%m-%d %H:%M:%S') or '',
            merchant_name,
            obj.dbtransfer.user,
            obj.dbtransfer.user_phone,
            '; '.join(obj.project.all().values_list('name', flat=True)),
            obj.single_time,
            obj.user.username,
            '是' if obj.is_consume else '否',
            obj.budan and obj.budan.create_user.username or '',
            obj.budan and obj.budan.happen_time and obj.budan.happen_time.strftime('%Y-%m-%d %H:%M:%S') or '',
            obj.budan and obj.budan.extra_consume or '',
            obj.budan and obj.budan.payment or '',
        )
        dt.append(x)
    body = u'转诊线索派单导出'
    info_logger.info(u'导出结束')
    log_obj.current = len(dt)
    log_obj.status = u'SUCCESS'
    now = str(datetime.now())
    log_obj.end_time = now
    log_obj.save()
    send_export_mail(u'转诊派单导出', body, user.email, dt)


#@shared_task
#def card_generate_stat():

#    dt = tablib.Dataset()
#    dt.headers = [u"生成时间", u"医生/医院名称", u"医生账号类型", u"机构所在城市", u"省份", u"大区", u"关联bd名称", u"bd对应组织架构"]

#    for card in DoctorCard.objects.all().order_by("-gen_time"):
#        gen_time = card.gen_time
#        doctor_name = card.doctor.name
#        doctor_type = card.doctor.doctor_type
#        if doctor_type == DOCTOR_TYPE.OFFICER:
#            doctor_type = "机构管理者"
#        else:
#            doctor_type = "普通医生"
#        city = card.doctor.hospital.city.name
#        province = card.doctor.hospital.city.province.name
#        region = card.doctor.hospital.city.province.region.name
#        bd = card.doctor.business_partener.username
#        if card.doctor.get_business_group():
#            bd_group = card.doctor.get_business_group()["name"]
#        else:
#            bd_group = ""

#        dt.append([gen_time, doctor_name, doctor_type, city, province, region, bd, bd_group])
#    info_logger.info(u'导出补单列表结束')
#    body = u'名片生成记录导出'

#    email_list = ["jiaweijie@igengmei.com", "yupengbo@igengmei.com", "songzhenqi@igengmei.com", "zhaochen@igengmei.com", "zhangyanzhao@igengmei.com", "zhongqingyu@igengmei.com"]
#    send_export_mail(u'名片生成记录导出', body, email_list, dt)

