# encoding: utf-8
'''
@author: zhangjian
@time: 2019/1/8 11:08
'''
import sys
import smtplib
import datetime
import elasticsearch
from email.message import EmailMessage


def releaser_video_alert_weekly(f_log=None):
    hosts = '192.168.17.11'
    port = 80
    user = 'zhouyujiang'
    passwd = '8tM9JDN2LVxM'
    http_auth = (user, passwd)
    es = elasticsearch.Elasticsearch(hosts=hosts, port=port, http_auth=http_auth)

    today = datetime.datetime.now()
    # if f_log == None:
    #     path = '/home/zhouyujiang/email_log/'
    #     log_fn = 'releaser_video_num_alert_for_%s_log' % datetime.datetime.strftime(today, '%b-%Y')
    #     f_log = open(path + log_fn, 'a')
    #     # pass
    # else:
    #     f_log = sys.stdout
    #
    # print('*' * 80, file=f_log)
    # print('log timestamp ', datetime.datetime.now(), file=f_log)
    # print('Checking task for fetch_date', today.isoformat()[:10], file=f_log)

    # 计算周数和时间
    week_canlendar = datetime.datetime.now().isocalendar()
    # week_canlendar = datetime.datetime(year=2018, month=12, day=25).isocalendar()
    year = week_canlendar[0]
    this_week = week_canlendar[1] - 1
    last_week = this_week - 1
    today = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day)
    # today = datetime.datetime(year=2018, month=12, day=25)
    first_day_in_week = today - datetime.timedelta(days=week_canlendar[2] + 7)
    fisrt_day_ts = int(first_day_in_week.timestamp() * 1e3)
    last_day_in_week = first_day_in_week + datetime.timedelta(days=7)
    last_day_ts = int(last_day_in_week.timestamp() * 1e3)

    this_week_index = 'short-video-weekly'
    this_week_doc = 'daily-url-' + str(year) + '_w' + format(this_week, '>02d') + '_s1'
    last_week_index = 'releaser-weekly-short-video'
    last_week_doc = 'doc'

    result = {'below': [], 'above': []}
    # error_count=0
    count = 0

    with open('/home/zhouyujiang/pycode/alert_releaser.csv', 'r', encoding='gb18030') as f:
        header_Lst = f.readline().strip().split(',')
        for line in f:
            count += 1
            one_line = {}
            line_Lst = line.strip().split(',')
            line_dict = dict(zip(header_Lst, line_Lst))
            releaser = line_dict['releaser']
            platform = line_dict['platform']

            # 计算本周video_num
            search_body1 = {
                "query": {
                    "bool": {
                        "filter": [
                            {"term": {"platform.keyword": platform}},
                            {"term": {"releaser.keyword": releaser}},
                            {"range": {"release_time": {"gte": fisrt_day_ts, "lt": last_day_ts}}},
                            {"range": {"duration": {"lte": 600}}},
                        ]
                    }
                }
            }
            resp1 = es.search(index=this_week_index, doc_type=this_week_doc, body=search_body1)
            this_week_videonum = resp1['hits']['total']

            # 计算上周video_num
            search_body2 = {
                "query": {
                    "bool": {
                        "filter": [
                            {"term": {"platform.keyword": platform}},
                            {"term": {"releaser.keyword": releaser}},
                            {"term": {"data_week_year": year}},
                            {"term": {"data_week_num": last_week}},
                            {"term": {"stats_type": "new_released"}}
                        ]
                    }
                }
            }
            resp2 = es.search(index=last_week_index, doc_type=last_week_doc, body=search_body2)
            try:
                last_week_videonum = resp2['hits']['hits'][0]['_source']['video_num']
            except:
                print('last_week_releaser_error:', releaser, platform, resp2['hits'], file=f_log)
                last_week_videonum = 0

            # 计算百分比  本周/上一周
            videonum_per = round(this_week_videonum / last_week_videonum * 100, 1) if last_week_videonum != 0 else -1
            one_line.update({"releaser": releaser,
                             "platform": platform,
                             str(last_week) + "周_videonum": last_week_videonum,
                             str(this_week) + '周_videonum': this_week_videonum,
                             "百分比": videonum_per,
                             })

            if videonum_per > 50 or videonum_per == -1:
                result['above'].append(one_line)
            else:
                result['below'].append(one_line)
    result['above'] = sorted(result['above'], key=lambda x: x['百分比'])
    result['below'] = sorted(result['below'], key=lambda x: x['百分比'])
    email_group = ['zhouyujiang@csm.com.cn',
                   'hanye@csm.com.cn',
                   'zhangtianli@csm.com.cn',
                   'zhangminghui@csm.com.cn',
                   'litao@csm.com.cn'
    ]
    email_msg_suffix = ('\n\n\n'
                        + '-' * 80 + '\n'
                        + '这是自动发送的邮件，可以不用回复。\n'
                        + 'This is an automatically sent message. You do NOT need to reply.\n')

    # # send the alert email
    csm_mail_service = 'mail.csm.com.cn'
    sender = 'zhouyujiang@csm.com.cn'
    email_subj = 'w' + str(this_week) + '_w' + str(last_week) + '_releaser_video_num预警 %s' % (today.isoformat()[:10])
    email_msg_body = ''
    email_msg_body += str(this_week) + '周和' + str(last_week) + '周 发布者video_num对比\n\n'
    email_msg_body += '低于/高于/总共 预警值（50%%）：%s/%s/%d\n\n' % (len(result['below']), len(result['above']), count)
    for key in result.keys():
        if key == 'below':
            email_msg_body += '低于预警值：\n'
            email_msg_body += '\t发布者                        平台         上周    本周    百分比\n'
            for one in result[key]:
                for name in one.keys():
                    if name == 'releaser':
                        email_msg_body += '\t%s' % (one[name])
                        c = (len(one[name].encode('utf-8')) - len(one[name])) / 2 + len(one[name])
                        while c < 30:
                            email_msg_body += ' '
                            c += 1
                    elif name == 'platform':
                        email_msg_body += '%s' % (one[name])
                        c = (len(one[name].encode('utf-8')) - len(one[name])) / 2 + len(one[name])
                        while c < 15:
                            email_msg_body += ' '
                            c += 1
                    elif 'videonum' in name:
                        email_msg_body += '%s' % (one[name])
                        c = len(str(one[name]))
                        while c < 8:
                            email_msg_body += ' '
                            c += 1
                    elif name == '百分比':
                        email_msg_body += '%s%%' % (one[name])
                email_msg_body += '\n'
        else:
            email_msg_body += '高于预警值：\n'
            email_msg_body += '\t发布者                        平台         上周    本周    百分比\n'
            for one in result[key]:
                for name in one.keys():
                    # if name == '百分比':
                    #     email_msg_body += '\t\t%s:%s%%' % (name, one[name])
                    # else:
                    #     email_msg_body += '\t\t%s:%s' % (name, one[name])
                    if name == 'releaser':
                        email_msg_body += '\t%s' % (one[name])
                        c = (len(one[name].encode('utf-8')) - len(one[name])) / 2 + len(one[name])
                        while c < 30:
                            email_msg_body += ' '
                            c += 1
                    elif name == 'platform':
                        email_msg_body += '%s' % (one[name])
                        c = (len(one[name].encode('utf-8')) - len(one[name])) / 2 + len(one[name])
                        while c < 15:
                            email_msg_body += ' '
                            c += 1
                    elif 'videonum' in name:
                        email_msg_body += '%s' % (one[name])
                        c = len(str(one[name]))
                        while c < 8:
                            email_msg_body += ' '
                            c += 1
                    elif name == '百分比':
                        email_msg_body += '%s%%' % (one[name])
                email_msg_body += '\n'
    if email_msg_body != '':
        email_msg_body += email_msg_suffix
        print('email_msg_body:\n', email_msg_body, file=f_log)

    email_msg = EmailMessage()
    email_msg.set_content(email_msg_body)
    email_msg['Subject'] = email_subj
    email_msg['From'] = sender
    email_msg['to'] = email_group

    try:
        server = smtplib.SMTP(host=csm_mail_service)
        server.send_message(email_msg)
        server.quit()
        print('Successfully sent email to %s' % (email_group),
              datetime.datetime.now(), file=f_log)
        print('email_msg:\n', email_msg, file=f_log)
    except:
        print('Failed to connect email server.', datetime.datetime.now(), file=f_log)

    print('\n\n', file=f_log)
    f_log.close()


if __name__ == '__main__':
    releaser_video_alert_weekly()
