# -*- coding: UTF-8 -*-

import datetime
import time
import tablib
import traceback

from django.contrib.auth.models import User
from django.core.mail import EmailMessage, EmailMultiAlternatives, get_connection
from django.db.models import Sum, Q, Count
from django.conf import settings

from api.models import Doctor
from statistic.models import DoctorView
from rpc.tool.log_tool import exception_logger


connection = get_connection(
    username=settings.STATIS_EMAIL_USER,
    password=settings.STATIS_EMAIL_PSWD,
)


def catch_exception(fn):
    def wrap(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except:
            exception_logger.info(traceback.format_exc())
    return wrap


def add_extra_reciever(fn):
    def wrap(*args, **kwargs):
        extra_recievers = ['zhongchengyang@wanmeizhensuo.com']
        m = fn(*args, **kwargs)
        m.to.extend(extra_recievers)
        return m
    return wrap


def add_html_border(content):
    return content.replace('<table>', '<table border="1">')


@catch_exception
def get_conversation_noreply_mail(date):
    # 医生未回复新用户私信统计
    day_yester = date - datetime.timedelta(days=1)
    day_yester_str = day_yester.strftime('%Y-%m-%d')
    dvs = DoctorView.objects.exclude(noreply_pm_user_num=0)\
        .filter(stat_date=day_yester)\
        .order_by('-noreply_pm_user_num')
    d_t = tablib.Dataset()  # daily data table
    d_t.headers = [u'新用户私信', u'未回复新用户私信', u'医生名']
    for dv in dvs:
        d_t.append((dv.new_pm_user_num, dv.noreply_pm_user_num, dv.doctor.name))

    html = u'%s 新用户私信统计：\n' % day_yester_str
    html += u'\t'.join(d_t.headers)
    html += u'\n'
    html += u'\n'.join([u'{}\t{}\t{}'.format(*row) for row in d_t[:]])

    mail = EmailMessage(connection=connection)
    mail.from_email = settings.STATIS_EMAIL_USER
    mail.subject = u'今日医生未回复私信（24小时）统计 {}'.format(day_yester)
    mail.to = [settings.STATIS_MAILS['sixin']]
    mail.body = html
    mail.attach(u'{}.xls'.format(day_yester), d_t.xls)
    return mail


@catch_exception
def get_conversation_noreply_mail_weekly(date):
    # 医生未回复新用户私信统计, 按周
    day_yester = date - datetime.timedelta(days=1)
    week_begin = day_yester - datetime.timedelta(day_yester.weekday())
    week_end = week_begin + datetime.timedelta(6)
    dvs = DoctorView.objects.filter(stat_date__range=(week_begin, week_end))\
        .values('doctor')\
        .annotate(total_num=Sum('new_pm_user_num'),
                  noreply_num=Sum('noreply_pm_user_num'))\
        .exclude(noreply_num=0)\
        .order_by('-noreply_num')
    d_t = tablib.Dataset()  # week data table
    d_t.headers = [u'新用户私信', u'未回复新用户私信', u'医生名']
    for dv in dvs:
        doctor = Doctor.objects.get(id=dv['doctor'])
        d_t.append((dv['total_num'], dv['noreply_num'], doctor.name))
    html = u'%s - %s 新用户私信统计：\n' % (week_begin, week_end)
    html += u'\t'.join(d_t.headers)
    html += u'\n'
    html += u'\n'.join([u'{}\t{}\t{}'.format(*row) for row in d_t[:]])

    mail = EmailMessage(connection=connection)
    mail.from_email = settings.STATIS_EMAIL_USER
    mail.subject = u'本周医生未回复私信（24小时）统计 ({}~{})'.format(week_begin, week_end)
    mail.to = [settings.STATIS_MAILS['sixin']]
    mail.body = html
    mail.attach(u'{}~{}.xls'.format(week_begin, week_end), d_t.xls)
    return mail
