# -*- coding: utf-8 -*-
"""
Created on Wed Jun  5 10:20:25 2019

@author: zhouyujiang
客服部发送Infosys加密文件
"""

import os
import datetime
import time
import shutil
import configparser
from func_send_email_with_file import send_file_email


def func_mk_send_file_name(date, folder):
    datestr = str(date).replace('-', '')[2:8]
    AUfile = folder + '\\' + 'AU' + datestr + '.ZIP'
    PIfile = folder + '\\' + 'PI' + datestr + '.ZIP'

    return [AUfile, PIfile]


def func_find_recent_folder(aims_path):
    folder_dict = {}
    folder_list = []

    #    for root, dirs, file in os.walk(aims_path):
    #        folder_list = dirs
    #    for i in folder_list:
    folder_list = [i for i in os.listdir(aims_path) if not os.path.isdir(i)]
    new_folder_List = sorted(folder_list, reverse=True)
    # for one in folder_list:
    #     file_path = aims_path + '\\' + one
    #     update_time = os.path.getmtime(file_path)
    #     folder_dict.update({file_path:update_time})
    # new_file = sorted(folder_dict.items(), key=lambda x:x[1], reverse=True)
    return aims_path + '\\' + new_folder_List[0]


def func_rm_sendfile_to_dir(file_path=r'D:',
                            send_file_list=[]):
    tmp_name = 'send_email_file'
    tmp_path = file_path + '\\' + tmp_name
    #    os.mkdir(tmp_path)
    if os.listdir(tmp_path) != []:
        for j in os.listdir(tmp_path):
            os.remove(tmp_path + '\\' + j)
    if os.path.exists(tmp_path):
        pass
    else:
        os.mkdir(tmp_path)
    if send_file_list == []:
        print('no file will rm, send_eamil_list = []')
    else:
        for one in send_file_list:
            shutil.copy(one, tmp_path)
    data_str = str(now)[0:10]
    send_file_email(tmp_path, data_str, email_group, email_msg_body_str,
                    title_str, cc_group)


if __name__ == '__main__':
    # 配置文件地址
    config_path = r'Y:\send_email.ini'
    # 配置文件地址 测试
    # config_path = r'D:\code\maintenance\config\send_email.ini'
    # 临时存放要发送的邮件地址
    temp_file_path = r'D:'
    # 要发送的数据地址
    log_file = r'D:\\log\\send_email_log_' + str(datetime.datetime.now())[0:10]
    f = open(log_file, 'w')
    aims_path = r'Z:\\'
    CONFIG = configparser.ConfigParser()
    CONFIG.read(config_path, encoding='utf-8')
    print(CONFIG, file=f)

    send_time = CONFIG['send_time']['start_time']
    send_time_hour = int(send_time[0:2])
    send_time_minute = int(send_time[3:5])
    email_group = CONFIG['send_to']['email_group'].split(',')
    cc_group = CONFIG['Cc_to']['Cc_group'].split(',')
    email_msg_body_str = CONFIG['send_body']['body']
    print(send_time, file=f)
    print(email_group, file=f)
    print(cc_group, file=f)
    now = datetime.datetime.now()
    weekday = now.weekday()
    title_str = '[自动发送邮件]'
    while True:
        if now.hour == send_time_hour and now.minute == send_time_minute:
            print('开始发送邮件：', file=f)

            if weekday in (1, 2, 3, 4):
                email_msg_body_str = email_msg_body_str
                send_day = now - datetime.timedelta(1)

                recent_folder = func_find_recent_folder(aims_path)

                send_list = func_mk_send_file_name(send_day, recent_folder)
                func_rm_sendfile_to_dir(file_path=temp_file_path,
                                        send_file_list=send_list)
                print('邮件发送成功', datetime.datetime.now(), file=f)

            if weekday in (0,):
                email_msg_body_str = email_msg_body_str
                send_list = []
                recent_folder = func_find_recent_folder(aims_path)
                for i in range(1, 4):
                    send_day = now - datetime.timedelta(i)
                    recent_folder = func_find_recent_folder(aims_path)
                    send_list += func_mk_send_file_name(send_day, recent_folder)
                func_rm_sendfile_to_dir(send_file_list=send_list)
                print('邮件发送成功', datetime.datetime.now(), file=f)
            break
        if (now.hour > send_time_hour) or (now.hour == send_time_hour and now.minute > send_time_minute):
            print('超过发送时间', file=f)
            break
        else:
            print('等待邮件发送时间发送：', file=f)
            time.sleep(20)
            now = datetime.datetime.now()
    f.close()

