#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2018/10/31

from __future__ import absolute_import

from api.models.service import Soyoung_ServiceItem, ServiceItem, Third_Platform_ServiceItem
import tablib
from celery import shared_task
from hera.utils import get_mail_instance, attach_title
from rpc.tool.log_tool import log_audit_hera
from ..tool.log_tool import info_logger
from django.conf import settings
from gm_types.gaia import SERVICE_PLATFORM_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,
    }
    log_audit_hera(audit_data)
    return mail


# def _compare(desc, platform_type):
#     """
#         新氧与更美sku比价处理逻辑
#         :return:
#         """
#     info_logger.info(u'导出开始')
#     compare_skuprice_queryset = Third_Platform_ServiceItem.objects.filter(
#         is_online=True, platform_type=platform_type
#     )
#     dt = tablib.Dataset()
#     dt.headers = (u'ID', u'平台', u'美购ID', u'SkuID', u'美购名称', u'Sku名称', u'医院名称',
#                   u'医生名称', u'sku价格', u'预约数')
#     i = 0
#     for obj in compare_skuprice_queryset:
#         # 只导出新氧价格比更美价格低的数据
#         try:
#             ser = ServiceItem.objects.get(id=obj.serviceitem_id)
#             if ser.gengmei_price > obj.sku_price:
#                 dt.append((
#                     i,
#                     u'更美',
#                     ser.service_id,
#                     ser.id,
#                     ser.service.name,
#                     ser.get_items_name([obj.serviceitem_id]).get(obj.serviceitem_id, '')[0],
#                     ser.service.doctor.hospital.name if ser.service.doctor.hospital else '',
#                     ser.service.doctor.name if ser.service.doctor else '',
#                     ser.gengmei_price,
#                     ''
#                 ))
#                 dt.append((
#                     '',
#                     desc,
#                     '',
#                     obj.third_platform_serviceitem_id,
#                     '',
#                     obj.sku_name,
#                     obj.hospital_name,
#                     obj.doctor_name,
#                     obj.sku_price,
#                     obj.reservation_nums
#                 ))
#                 i += 1
#         except:
#             continue
#     dt.title = u'sku比价表格'
#     body = u'sku比价表格\n共计 %s 条' % i
#     info_logger.info(u'导出结束')
#     if dt:
#         send_export_mail(u'sku比价结果表', body, settings.SEND_TO_EMAIL, dt)


@shared_task
def compare_sku_price():
    """
    新氧与更美sku比价处理逻辑
    :return:
    """
    info_logger.info(u'导出开始')
    compare_skuprice_queryset = Soyoung_ServiceItem.objects.filter(is_online=True)
    dt = tablib.Dataset()
    dt.headers = (u'ID', u'平台', u'美购ID', u'SkuID', u'美购名称', u'Sku名称', u'医院名称',
                  u'医生名称', u'sku价格', u'预约数')
    i = 0
    for obj in compare_skuprice_queryset:
        # 只导出新氧价格比更美价格低的数据
        try:
            ser = ServiceItem.objects.get(id=obj.serviceitem_id)
            if ser.gengmei_price > obj.sku_price:
                dt.append((
                    i,
                    u'更美',
                    ser.service_id,
                    ser.id,
                    ser.service.name,
                    ser.get_items_name([obj.serviceitem_id]).get(obj.serviceitem_id, '')[0],
                    ser.service.doctor.hospital.name if ser.service.doctor.hospital else '',
                    ser.service.doctor.name if ser.service.doctor else '',
                    ser.gengmei_price,
                    ''
                ))
                dt.append((
                    '',
                    u'新氧',
                    '',
                    obj.soyoung_serviceitem_id,
                    '',
                    obj.sku_name,
                    obj.hospital_name,
                    obj.doctor_name,
                    obj.sku_price,
                    obj.reservation_nums
                ))
                i += 1
        except:
            continue
    dt.title = u'新氧与更美sku比价表格'
    body = u'新氧与更美sku比价表格\n共计 %s 条' % i
    info_logger.info(u'导出结束')
    if dt:
        send_export_mail(u'sku比价结果表', body, settings.SEND_TO_EMAIL, dt)


# @shared_task
# def compare_sku_price_for_third_platform():
#     task_dict = {
#         '点评': SERVICE_PLATFORM_TYPE.DIANPING,
#         '河狸家': SERVICE_PLATFORM_TYPE.HELIJIA,
#         '悦美': SERVICE_PLATFORM_TYPE.YUEMEI,
#         '天猫': SERVICE_PLATFORM_TYPE.TMALL
#     }
#
#     for key, value in task_dict.iteritems():
#         _compare(key, value)