# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MainWindow - untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

import threading
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from email.parser import Parser
from email.utils import parseaddr
from email.header import decode_header
from email.mime.text import MIMEText
import email, smtplib, poplib, pandas as pd,  time


poplib._MAXLINE=20480

class Ui_EmailApplication(object):


    def setupUi(self, EmailApplication):

        EmailApplication.setObjectName("EmailApplication")
        EmailApplication.resize(653, 966)
        EmailApplication.setMouseTracking(False)
        EmailApplication.setAccessibleDescription("")
        EmailApplication.setAutoFillBackground(False)
        EmailApplication.setIconSize(QtCore.QSize(36, 36))
        EmailApplication.setDocumentMode(False)
        self.now_time = time.localtime(time.time())
        self.centralwidget = QtWidgets.QWidget(EmailApplication)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 0, 151, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        self.label.setFont(font)
        self.label.setMouseTracking(False)
        self.label.setFocusPolicy(QtCore.Qt.NoFocus)
        self.label.setObjectName("label")
        self.user = QtWidgets.QLineEdit(self.centralwidget)
        self.user.setGeometry(QtCore.QRect(360, 30, 281, 41))
        self.user.setObjectName("user")
        self.paw = QtWidgets.QLineEdit(self.centralwidget)
        self.paw.setGeometry(QtCore.QRect(360, 90, 281, 41))
        self.paw.setObjectName("paw")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(20, 150, 151, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        self.label_5.setFont(font)
        self.label_5.setMouseTracking(False)
        self.label_5.setFocusPolicy(QtCore.Qt.NoFocus)
        self.label_5.setObjectName("label_5")
        self.set_header = QtWidgets.QLineEdit(self.centralwidget)
        self.set_header.setGeometry(QtCore.QRect(180, 200, 261, 41))
        self.set_header.setObjectName("set_header")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(30, 210, 144, 27))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(10, 250, 151, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        self.label_6.setFont(font)
        self.label_6.setMouseTracking(False)
        self.label_6.setFocusPolicy(QtCore.Qt.NoFocus)
        self.label_6.setObjectName("label_6")
        self.Start_time = QtWidgets.QDateTimeEdit(self.centralwidget)
        self.Start_time.setGeometry(QtCore.QRect(40, 310, 171, 61))
        self.Start_time.setDateTime(QtCore.QDateTime.currentDateTime())
        self.Start_time.setObjectName("Start_time")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(230, 320, 81, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(14)
        self.label_7.setFont(font)
        self.label_7.setObjectName("label_7")
        self.Over_time = QtWidgets.QDateTimeEdit(self.centralwidget)
        self.Over_time.setGeometry(QtCore.QRect(280, 310, 171, 61))
        self.Over_time.setDateTime(QtCore.QDateTime.currentDateTime())
        self.Over_time.setObjectName("Over_time")
        self.label_8 = QtWidgets.QLabel(self.centralwidget)
        self.label_8.setGeometry(QtCore.QRect(10, 410, 151, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        self.label_8.setFont(font)
        self.label_8.setMouseTracking(False)
        self.label_8.setFocusPolicy(QtCore.Qt.NoFocus)
        self.label_8.setObjectName("label_8")
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setGeometry(QtCore.QRect(40, 470, 111, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")
        self.subject = QtWidgets.QLineEdit(self.centralwidget)
        self.subject.setGeometry(QtCore.QRect(110, 470, 321, 41))
        self.subject.setObjectName("subject")
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setGeometry(QtCore.QRect(50, 530, 81, 18))
        self.label_10.setText("")
        self.label_10.setObjectName("label_10")
        self.label_11 = QtWidgets.QLabel(self.centralwidget)
        self.label_11.setGeometry(QtCore.QRect(40, 520, 111, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_11.setFont(font)
        self.label_11.setObjectName("label_11")
        self.page = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.page.setGeometry(QtCore.QRect(110, 530, 321, 151))
        self.page.setObjectName("page")
        self.label_12 = QtWidgets.QLabel(self.centralwidget)
        self.label_12.setGeometry(QtCore.QRect(10, 690, 151, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        self.label_12.setFont(font)
        self.label_12.setMouseTracking(False)
        self.label_12.setFocusPolicy(QtCore.Qt.NoFocus)
        self.label_12.setObjectName("label_12")
        self.label_13 = QtWidgets.QLabel(self.centralwidget)
        self.label_13.setGeometry(QtCore.QRect(30, 740, 161, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_13.setFont(font)
        self.label_13.setObjectName("label_13")
        self.label_14 = QtWidgets.QLabel(self.centralwidget)
        self.label_14.setGeometry(QtCore.QRect(30, 790, 161, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_14.setFont(font)
        self.label_14.setObjectName("label_14")
        self.label_15 = QtWidgets.QLabel(self.centralwidget)
        self.label_15.setGeometry(QtCore.QRect(30, 840, 161, 41))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_15.setFont(font)
        self.label_15.setObjectName("label_15")
        self.Down_file = QtWidgets.QLineEdit(self.centralwidget)
        self.Down_file.setGeometry(QtCore.QRect(190, 740, 321, 41))
        self.Down_file.setObjectName("Down_file")
        self.Write_file = QtWidgets.QLineEdit(self.centralwidget)
        self.Write_file.setGeometry(QtCore.QRect(190, 790, 321, 41))
        self.Write_file.setObjectName("Write_file")
        self.form_header = QtWidgets.QLineEdit(self.centralwidget)
        self.form_header.setGeometry(QtCore.QRect(190, 840, 321, 41))
        self.form_header.setObjectName("form_header")
        self.toolButton = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton.setGeometry(QtCore.QRect(530, 750, 51, 31))
        self.toolButton.setObjectName("toolButton")
        self.toolButton_2 = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton_2.setGeometry(QtCore.QRect(530, 800, 51, 31))
        self.toolButton_2.setObjectName("toolButton_2")
        self.label_16 = QtWidgets.QLabel(self.centralwidget)
        self.label_16.setGeometry(QtCore.QRect(510, 840, 131, 41))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(10)
        self.label_16.setFont(font)
        self.label_16.setObjectName("label_16")
        self.Start_button = QtWidgets.QPushButton(self.centralwidget)
        self.Start_button.setGeometry(QtCore.QRect(20, 50, 112, 31))
        self.Start_button.setObjectName("Start_button")
        self.Over_button = QtWidgets.QPushButton(self.centralwidget)
        self.Over_button.setGeometry(QtCore.QRect(20, 90, 112, 31))
        self.Over_button.setObjectName("Start_button")
        self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QtCore.QRect(300, 30, 71, 101))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label_2 = QtWidgets.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.verticalLayout.addWidget(self.label_2)
        self.label_3 = QtWidgets.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.verticalLayout.addWidget(self.label_3)
        self.layoutWidget1 = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget1.setGeometry(QtCore.QRect(150, 30, 111, 101))
        self.layoutWidget1.setObjectName("layoutWidget1")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget1)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.qq_pop = QtWidgets.QRadioButton(self.layoutWidget1)
        self.qq_pop.setObjectName("qq_pop")
        self.verticalLayout_2.addWidget(self.qq_pop)
        self.pop163 = QtWidgets.QRadioButton(self.layoutWidget1)
        self.pop163.setObjectName("pop163")
        self.verticalLayout_2.addWidget(self.pop163)
        self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox.setGeometry(QtCore.QRect(450, 480, 131, 21))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(11)
        self.checkBox.setFont(font)
        self.checkBox.setObjectName("checkBox")
        EmailApplication.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(EmailApplication)
        self.statusbar.setObjectName("statusbar")
        EmailApplication.setStatusBar(self.statusbar)

        self.retranslateUi(EmailApplication)
        QtCore.QMetaObject.connectSlotsByName(EmailApplication)

    def retranslateUi(self, EmailApplication):
        _translate = QtCore.QCoreApplication.translate
        EmailApplication.setWindowTitle(_translate("EmailApplication", "郵件處理軟件"))
        self.label.setText(_translate("EmailApplication", "账号登录"))
        self.label_5.setText(_translate("EmailApplication", "设置"))
        self.label_4.setText(_translate("EmailApplication", "设置邮箱前缀"))
        self.label_6.setText(_translate("EmailApplication", "时间设定"))
        self.label_7.setText(_translate("EmailApplication", "至"))
        self.label_8.setText(_translate("EmailApplication", "回复设置"))
        self.label_9.setText(_translate("EmailApplication", "主题:"))
        self.label_11.setText(_translate("EmailApplication", "正文:"))
        self.label_12.setText(_translate("EmailApplication", "记录设置"))
        self.label_13.setText(_translate("EmailApplication", "附件保存路径:"))
        self.label_14.setText(_translate("EmailApplication", "记录文件路径:"))
        self.label_15.setText(_translate("EmailApplication", "记录表格列名:"))
        self.toolButton.setText(_translate("EmailApplication", "..."))
        self.toolButton_2.setText(_translate("EmailApplication", "..."))
        self.label_16.setText(_translate("EmailApplication", "（以空格分隔）"))
        self.Start_button.setText(_translate("EmailApplication", "开始运行"))
        self.Over_button.setText(_translate("EmailApplication", "停止"))
        self.label_2.setText(_translate("EmailApplication", "账号:"))
        self.label_3.setText(_translate("EmailApplication", "密码:"))
        self.qq_pop.setText(_translate("EmailApplication", "QQ邮箱"))
        self.pop163.setText(_translate("EmailApplication", "163邮箱"))
        self.checkBox.setText(_translate("EmailApplication", "自動回復"))




class Query_Window(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_EmailApplication()
        self.ui.setupUi(self)
        #self.action()
        self.flag = 0
        self.ui.Start_button.clicked.connect(self.Run)
        self.ui.toolButton.clicked.connect(self.msg)
        self.ui.toolButton_2.clicked.connect(self.msg2)
        self.ui.Over_button.clicked.connect(self.off)
        # 给button 的 点击动作绑定一个事件处理函数

    def msg(self):
        Filepath = QtWidgets.QFileDialog.getExistingDirectory(None,"选取文件夹")  # 起始路径
        self.ui.Down_file.setText(Filepath)

    def msg2(self):
        Filepath = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹")  # 起始路径
        self.ui.Write_file.setText(Filepath)

    def Run(self):
        try:
            t = threading.Thread(target=self.query_formula, name='t')
            t.start()
        except Exception:
            print(2)

    def off(self):
        self.flag = 0
        QtWidgets.QMessageBox.critical(self, "提示", "停止成功")


    def query_formula(self):
        self.user = self.ui.user.text()
        self.pwd = self.ui.paw.text()
        self.set_header = self.ui.set_header.text()
        self.now_time = int(time.time())
        self.start_time = int(time.mktime(time.strptime(self.ui.Start_time.text(),"%Y/%m/%d %H:%M")))
        self.over_time = int(time.mktime(time.strptime(self.ui.Over_time.text(),"%Y/%m/%d %H:%M")))
        #print(self.over_time,self.now_time,self.ui.Over_time.text())
        self.page = self.ui.page.toPlainText()
        #print(self.page)
        self.email_header = self.ui.set_header.text()
        self.subject = self.ui.subject.text()
        self.save_file = self.ui.Down_file.text()
        self.write_file = self.ui.Write_file.text()
        self.select = self.ui.form_header.text().split(' ')
        self.pop_mail = ''
        self.index2 = []

        #self.students = [x for x in range(20210101, 20210150)]
        self.sudents_num = []
        self.messafe()

        #self.ui.qq_pop.setChecked(True)
        #self.ui.qq_pop.toggled.connect(lambda: self.btnstate(self.ui.qq_pop))

    def messafe(self):
        if self.ui.qq_pop.isChecked() or self.ui.pop163.isChecked():
            if self.ui.qq_pop.isChecked():
                self.pop_mail = 'imap.qq.com'
            elif self.ui.pop163.isChecked():
                self.pop_mail = 'imap.163.com'
            if self.save_file and self.write_file:
                self.login()
            else:
                QtWidgets.QMessageBox.critical(self, "错误", "請检查填写是否正确")
        else:
            QtWidgets.QMessageBox.critical(self, "错误", "請選擇登錄服務器")


    def login(self):
        #QtWidgets.QMessageBox.critical(self, "开始", "正在启动")
        self.server = poplib.POP3(self.pop_mail)
        self.server.user(self.user)
        self.server.pass_(self.pwd)

        self.get_email()



    def get_email(self):  # 获取最新邮件信息
            #print(00)
            while 1:

                if self.now_time >= self.start_time:
                    _, mails, _ = self.server.list()
                    self.index = len(mails)
                    _, lines, _ = self.server.retr(self.index)
                    #print(lines)
                    msg_content = b'\r\n'.join(lines).decode('gb2312')
                    self.msg = Parser().parsestr(msg_content)
                    self.chick_index()
                    time.sleep(30)
                    # Application(self.user_email)
                    #time.sleep(5)
                else:
                    self.now_time = time.time()


    def chick_index(self):  # 检测是否有新邮件
        #print(19)
        if self.index not in self.index2:
            self.index2.append(self.index)
            # print(self.index,self.index2)
            #print(2)
            self.msg_decode()

    def decode_str(self, s):
        value, charset = decode_header(s)[0]
        if charset:
            value = value.decode(charset)
        return value

    def msg_decode(self):  # 解析邮件内容
        i = 0
        for header in ['From', 'To', 'Subject']:
            value = self.msg.get(header, '')

            if value:
                if header == 'Subject':
                    value = self.decode_str(value)
                    self.i_subject = value.replace(' ','')
                    # print(self.subject)
                else:
                    hdr, addr = parseaddr(value)
                    if i == 0:
                        self.addr = addr
                        i += 1
        #print(3)
        self.check_subject()

    def check_subject(self):  # 检测新到邮件是否符合
        print(self.email_header,self.i_subject)

        if self.email_header in self.i_subject:

            #self.sudents_num.append(self.subject)
            # print(3)
            # msg = email.message_from_file(fp)
           # sender =
            # 邮件内容设置
            #print(1)
            #print(self.ui.checkBox.isChecked())
            if self.ui.checkBox.isChecked():
            #print(self.subject,self.user)
                message = MIMEText(self.page, 'plain', 'utf-8')
                # 邮件主题
                message['Subject'] = self.subject
                # 发送方信息
                message['From'] = self.user
                # 接受方信息
                message['To'] = self.addr
                # 登录并发送邮件
                try:
                    smtpObj = smtplib.SMTP()
                    # 连接到服务器
                    smtpObj.connect(self.pop_mail, 25)
                    # 登录到服务器
                    smtpObj.login(self.user, self.pwd)
                    # 发送
                    smtpObj.sendmail(
                        self.user, self.addr, message.as_string())
                    # 退出
                    #smtpObj.quit()
                    #tkinter.messagebox.showerror('提示', '收到一封邮件已自动回复')
                except smtplib.SMTPException as e:
                    print('error', e)  # 打印错误
            self.get_att()

    def get_att(self):  # 下载附件
        msg_in = self.msg
        attachment_files = []
        i = 1
        for part in msg_in.walk():
            # 获取附件名称类型
            file_name = part.get_filename()
            # contType = part.get_content_type()
            if file_name:
                h = email.header.Header(file_name)
                # 对附件名称进行解码
                dh = email.header.decode_header(h)
                filename = dh[0][0]
                if dh[0][1]:
                    # 将附件名称可读化
                    filename = self.decode_str(str(filename, dh[0][1]))

                data = part.get_payload(decode=True)
                #path = r"附件"  # 在指定目录下创建文件,如果不存在则创建目录
                #if not os.path.exists(path):
                    #os.makedirs(path)
                att_file = open(self.save_file + '\\' + filename, 'wb')  # 注意二进制文件需要用wb模式打开
                attachment_files.append(filename)
                att_file.write(data)  # 保存附件
                att_file.close()
                print(f'附件({i}): {filename}')
                i += 1

                self.df_excel()

        self.time_now = time.time()
        #print(self.over_tim,self.time_now)
        if self.over_time <= self.time_now:
            exit()



    def df_excel(self):
        # Application(self.user_email)
        self.sheet = pd.DataFrame(pd.read_excel('Save.xlsx'))
        #sheet = pd.DataFrame(pd.read_excel('Save.xlsx'))
        all_student = list(self.sheet['学号'])
        #print(all_student)
        for i in all_student:
            #print(i,self.i_subject)
            if str(i) in self.i_subject:
                #print(i)
                self.sudents_num.append(i)
        y2 = list(set(all_student) - set(self.sudents_num))
        #print(y2)
        for i in y2:
            self.sheet.loc[self.sheet['学号'] == i, '提交'] = '未提交'
        #print(self.write_file)
        #print(self.write_file+'标记后.xlsx')
        self.sheet.to_excel(excel_writer=self.write_file + '\\'+'标记后.xlsx')
        print('標註成功')









    # 此处编写具体的业务逻辑



if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = Query_Window()
    window.show()
    sys.exit(app.exec_())


