# coding=utf-8
import tablib
from hera.utils import get_mail_instance, attach_title
from rpc.tool.log_tool import info_logger
from celery import shared_task, current_task
from api.models import Service, ServiceItem, ServiceTag, MerchantRelevance, Merchant
from django.db.models import Q
from gm_types.gaia import TAG_TYPE, MERCHANT_LEVEL_NEW
from django.conf import settings


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 = {
        'task_id': current_task.request.id,
        'audit_type': 'export_excel',
        'email_title': subject,
        'email_to': to_list,
        # 'excel_data': dt.xlsx,
        # 'excel_name': u'{}.xlsx'.format(subject),
    }
    info_logger.info(audit_data)
    return mail


@shared_task
def export_upgrade_service_excel():
    service_obj_list = Service.objects.filter(upgrade=True, is_delete=False)
    info_logger.info(u'export_upgrade_service_excel----导出开始')
    dt = tablib.Dataset()
    dt.headers = [
        u'序号',u'spu_id',u'sku_id',u'商品名称',u'运营分类1级id',u'运营分类1级名称',u'运营分类2级id',
        u'运营分类2级名称',u'叶子项目id',u'叶子项目名称',u'机构id',u'机构名称',u'商户等级',u'大区',u'商务',
        u'机构所在城市',u'商品最后更新时间',u'是否在线'
    ]
    i = 0
    for single_service in service_obj_list:
        i += 1
        project_type = single_service.project_type
        if project_type:
            if project_type.tag_type == TAG_TYPE.ITEM_WIKI:
                # 二级
                parent_relation = project_type.parents_relations.first()
                parent_project_type = parent_relation.parent if parent_relation else None
                # 一级
                grand_parent_relation = parent_project_type.parents_relations.first() if parent_project_type else None
                grand_parent_project_type = grand_parent_relation.parent if grand_parent_relation else None
            elif project_type.tag_type == TAG_TYPE.BODY_PART_SUB_ITEM:
                # 二级
                parent_project_type = project_type
                # 一级
                grand_parent_relation = parent_project_type.parents_relations.first() if parent_project_type else None
                grand_parent_project_type = grand_parent_relation.parent if grand_parent_relation else None
            elif project_type.tag_type == TAG_TYPE.BODY_PART:
                # 二级
                parent_project_type = None
                # 一级
                grand_parent_project_type = project_type
        else:
            parent_project_type = None
            grand_parent_project_type = None

        all_servicetag_obj_list = ServiceTag.objects.filter(Q(service_id=single_service.id)&~Q(tag__tag_type=TAG_TYPE.YUNYING))
        all_tag_obj_list = [item.tag for item in all_servicetag_obj_list]
        if not all_tag_obj_list:
            if project_type:
                all_tag_obj_list = [project_type]
        # 所属医生
        doctor = single_service.doctor
        # 医生所属医院
        hospital = doctor.hospital
        hospital_city = hospital.city if hospital else None

        # 所属商户
        merchant = doctor.merchant

        merchant_level = MERCHANT_LEVEL_NEW.getDesc(merchant.merchant_level) if merchant else ''
        x = (
            i,
            single_service.id,
            ','.join(str(item) for item in ServiceItem.objects.filter(service_id=single_service.id, is_delete=False).values_list('id', flat=True)),
            single_service.name,
            grand_parent_project_type.id if grand_parent_project_type else u'',
            grand_parent_project_type.name if grand_parent_project_type else u'',
            parent_project_type.id if parent_project_type else u'',
            parent_project_type.name if parent_project_type else u'',
            ','.join([str(item.id) for item in all_tag_obj_list]),
            ','.join([item.name for item in all_tag_obj_list]),
            doctor.hospital.id if hospital else u'',
            doctor.hospital.name if hospital else u'',
            merchant_level,
            hospital_city.province.region.name if hospital_city else u'',
            doctor.business_partener.username if doctor.business_partener else u'',
            hospital_city.name if hospital_city else '',
            single_service.update_time.strftime('%Y-%m-%d %H:%M:%S'),
            '是' if single_service.is_online else '否'
        )
        dt.append(x)
    body = u'截止当前时间线上标准化商品统计（不包括回收站中商品）'
    info_logger.info(u'export_upgrade_service_excel----导出结束')
    send_export_mail(u'标准化商品统计', body, settings.EXPORT_UPGRADE_SERVICE_EMAIL_LIST , dt)
