"""获取每天失败的列表--返回给数据组"""
import datetime
import time

import pandas as pd
import smtplib

from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import pymysql

from base.BaseCore import BaseCore

baseCore = BaseCore()
log = baseCore.getLogger()
# cnx = baseCore.cnx
# cursor = baseCore.cursor


def sendEmail(file_name, receiver, filename):
    file = open(file_name, 'rb').read()
    # 发送邮箱地址
    sender = '1195236739@qq.com'
    # 发送邮箱登录 账户 密码
    username = '1195236739@qq.com'
    password = 'gatvszshadvpgjci'
    smtpserver = 'smtp.qq.com'

    # # 接收邮箱地址
    # receiver = 'fujunxue@ciglobal.cn'

    maile_title = filename

    message = MIMEMultipart()
    message['From'] = sender
    message['To'] = receiver
    message['Subject'] = Header(maile_title, 'utf-8')

    message.attach(MIMEText(filename, 'plain', 'utf-8'))

    xlsxApart = MIMEApplication(file)
    xlsxApart.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(xlsxApart)
    smtpObj = smtplib.SMTP_SSL(smtpserver)  # 注意：如果遇到发送失败的情况（提示远程主机拒接连接），这里要使用SMTP_SSL方法
    smtpObj.connect(smtpserver, port=465)
    smtpObj.login(username, password)
    smtpObj.sendmail(sender, receiver, message.as_string())
    print("邮件发送成功！！！")
    smtpObj.quit()


# 解析失败
def get_failed_list(today_time):
    cnx = pymysql.connect(host='114.115.159.144', user='caiji', password='zzsn9988', db='caiji',
                          charset='utf8mb4')
    cursor = cnx.cursor()
    sql = f"select * from wx_link where (state = '300' or state = '600' and state = '200') and create_time >= '{today_time}' "
    # sql = f"select * from wx_link where state='800' "
    print(sql)
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()
    cnx.close()
    return result


# 发布内容不存在
def get_null_list(today_time):
    cnx = pymysql.connect(host='114.115.159.144', user='caiji', password='zzsn9988', db='caiji',
                          charset='utf8mb4')
    cursor = cnx.cursor()
    sql = f"select * from wx_link where (state='800' or state='500') and create_time >= '{today_time}' "
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()
    cnx.close()
    return result


def get_info(result):
    fail_list = []
    for info in result:
        site_name = info[3]  # 公众号
        info_source_code = info[4]
        title = info[5]
        publish_time = info[6]
        link = info[7]
        # 写入detaframe
        # 创建一个字典，其中包含当前行的数据
        row = {
            '公众号': site_name,
            '公众号编码': info_source_code,
            '标题': title,
            '发布时间': publish_time,
            '链接': link
        }
        fail_list.append(row)
    return fail_list

if __name__ == "__main__":
    # 创建一个空的DataFrame，其中包含你需要的列名

    while True:
        # 计算今天的时间
        now = datetime.datetime.now()
        print(now)
        time.sleep(1)
        print(datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=0))
        if now >= datetime.datetime.now().replace(hour=23, minute=59, second=59, microsecond=0):
            pass
        else:
            continue
        today_time = str(now.strftime("%Y-%m-%d 00:00:00"))
        print(today_time)
        result = get_failed_list(today_time)
        result_null = get_null_list(today_time)
        if result:
            fail_list = get_info(result)
            result_df = pd.DataFrame(fail_list)
            result_df.to_excel(f"./database/{today_time[:10]}_微信公众号采集失败列表.xlsx", index=False)
            sendEmail(f"./database/{today_time[:10]}_微信公众号采集失败列表.xlsx", "fujunxue@ciglobal.cn", "微信公众号采集失败列表")
            sendEmail(f"./database/{today_time[:10]}_微信公众号采集失败列表.xlsx", "mr@ciglobal.cn", "微信公众号采集失败列表")
        else:
            log.info(f'{today_time} 没有采集失败的文章')
        if result_null:
            fail_list = get_info(result)
            null_list = get_info(result_null)
            null_df = pd.DataFrame(fail_list)
            null_df.to_excel(f"./database/{today_time[:10]}_微信公众号文章内容为空列表.xlsx", index=False)
            sendEmail(f"./database/{today_time[:10]}_微信公众号文章内容为空列表.xlsx", "fujunxue@ciglobal.cn", "微信公众号文章内容为空列表")
            sendEmail(f"./database/{today_time[:10]}_微信公众号文章内容为空列表.xlsx", "mr@ciglobal.cn", "微信公众号文章内容为空列表")
        else:
            log.info(f'{today_time} 没有采集到空的文章')

