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

# Form implementation generated from reading ui file '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 random
import sys
import time

import psutil
from PyQt5.QtCore import QTimer, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QSystemTrayIcon, QMenu, QAction, qApp
from PyQt5 import QtCore, QtGui, QtWidgets
from db import simpleToolSql


class TrayIcon(QtWidgets.QSystemTrayIcon):
    def __init__(self, MainWindow, parent=None):
        super(TrayIcon, self).__init__(parent)
        self.ui = MainWindow
        self.createMenu()

    def createMenu(self):
        self.menu = QtWidgets.QMenu()
        self.showAction1 = QtWidgets.QAction("启动", self, triggered=self.show_window)
        # self.showAction2 = QtWidgets.QAction("显示通知", self, triggered=self.showMsg)
        self.quitAction = QtWidgets.QAction("退出", self, triggered=self.quit)

        self.menu.addAction(self.showAction1)
        # self.menu.addAction(self.showAction2)
        self.menu.addAction(self.quitAction)
        self.setContextMenu(self.menu)

        # 设置图标
        self.setIcon(QtGui.QIcon("icon.png"))
        self.icon = self.MessageIcon()

        # 把鼠标点击图标的信号和槽连接
        self.activated.connect(self.onIconClicked)

    def showMsg(self):
        self.showMessage("Message", "skr at here", self.icon)

    def show_window(self):
        # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showNormal()
        self.ui.activateWindow()

    def quit(self):
        QtWidgets.qApp.quit()

    # 鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
    def onIconClicked(self, reason):
        if reason == 2 or reason == 3:
            # self.showMessage("Message", "skr at here", self.icon)
            if self.ui.isMinimized() or not self.ui.isVisible():
                # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
                MainWindow.show()
                MainWindow.activateWindow()
                # self.ui.showNormal()
                # self.ui.activateWindow()
                # self.ui.setWindowFlags(QtCore.Qt.Window)
                # self.ui.show()
            else:
                # 若不是最小化，则最小化
                MainWindow.showMinimized()
                MainWindow.show()

                # self.ui.setWindowFlags(QtCore.Qt.SplashScreen)
                # self.ui.show()



class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowTitle("Info")
        MainWindow.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowCloseButtonHint)
        # MainWindow.setWindowFlag(Qt.FramelessWindowHint)
        MainWindow.resize(142, 145)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # self.left_close = QtWidgets.QPushButton(self.centralwidget)
        # self.left_close.setGeometry(QtCore.QRect(125, 3, 0, 20))
        # self.left_close.setFixedSize(18, 18)
        # self.left_close.setStyleSheet('''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}''')
        #
        # self.left_mini = QtWidgets.QPushButton(self.centralwidget)
        # self.left_mini.setGeometry(QtCore.QRect(100, 3, 0, 20))
        # self.left_mini.setFixedSize(18, 18)
        # self.left_mini.setStyleSheet(
        #     '''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')




        self.CpuTextBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.CpuTextBrowser.setEnabled(True)
        self.CpuTextBrowser.setGeometry(QtCore.QRect(10, 5, 156, 21))
        self.CpuTextBrowser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.CpuTextBrowser.setObjectName("CpuTextBrowser")
        self.CpuTextBrowser.setStyleSheet("QTextBrowser{border-width:0;border-style:outset}")

        self.MemTextBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.MemTextBrowser.setEnabled(True)
        self.MemTextBrowser.setGeometry(QtCore.QRect(10, 35, 156, 21))
        self.MemTextBrowser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.MemTextBrowser.setObjectName("MemTextBrowser")
        self.MemTextBrowser.setStyleSheet("QTextBrowser{border-width:0;border-style:outset}")


        self.SpeedTextBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.SpeedTextBrowser.setEnabled(True)
        self.SpeedTextBrowser.setGeometry(QtCore.QRect(10, 65, 156, 21))
        self.SpeedTextBrowser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.SpeedTextBrowser.setObjectName("SpeedTextBrowser")
        self.SpeedTextBrowser.setStyleSheet("QTextBrowser{border-width:0;border-style:outset}")


        self.WordTextBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.WordTextBrowser.setEnabled(True)
        self.WordTextBrowser.setGeometry(QtCore.QRect(10, 95, 156, 21))
        self.WordTextBrowser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.WordTextBrowser.setObjectName("WordTextBrowser")
        self.WordTextBrowser.setStyleSheet("QTextBrowser{border-width:0;border-style:outset}")


        self.NextBtn = QtWidgets.QPushButton(self.centralwidget)
        self.NextBtn.setGeometry(QtCore.QRect(10, 95, 156, 21))
        self.NextBtn.setObjectName("TbBtn")
        self.NextBtn.setFixedSize(131, 23)
        op = QtWidgets.QGraphicsOpacityEffect()
        op.setOpacity(0)
        self.NextBtn.setGraphicsEffect(op)


        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        # self.left_close.clicked['bool'].connect(MainWindow.close)
        # self.left_mini.clicked['bool'].connect(MainWindow.hide)
        self.NextBtn.clicked['bool'].connect(self.nextWord)

        self.NextBtn.setContextMenuPolicy(Qt.CustomContextMenu)
        self.NextBtn.customContextMenuRequested.connect(self.wordPassed)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)


    def nextWord(self):
        _translate = QtCore.QCoreApplication.translate
        self.WordsShow()

    def wordPassed(self):
        updateSql = f"""update EnglishDic set PASS = '1' where WORD = '{WORD}';"""
        sql = simpleToolSql("data")
        result = sql.execute(updateSql)
        self.WordsShow()


    def getNet(self):
        sent_before = psutil.net_io_counters().bytes_sent  # 已发送的流量
        recv_before = psutil.net_io_counters().bytes_recv  # 已接收的流量
        time.sleep(1)
        sent_now = psutil.net_io_counters().bytes_sent
        recv_now = psutil.net_io_counters().bytes_recv
        sent = (sent_now - sent_before) / 1024  # 算出1秒后的差值
        recv = (recv_now - recv_before) / 1024
        net = "{0}KB".format("%.2f" % recv)
        return net

    def otherInfoShow(self):
        mem = psutil.virtual_memory().percent
        mem = str(mem) + "%"
        cpu = psutil.cpu_percent(interval=1)
        cpu = str(cpu) + "%"
        net = self.getNet()
        self.MemTextBrowser.setText(f"  内存 :   {mem}")
        self.CpuTextBrowser.setText(f"  CPU  :   {cpu}")
        self.SpeedTextBrowser.setText(f"  网速 :   {net}")

    def WordsShow(self):
        selectSql = """select ID, WORD, ZNNAME, SOUNDMARK, ENEXAMPLE, ZNEXAMPLE from EnglishDic where IELTS = '1' order by random() limit 1;"""
        sql = simpleToolSql("data")
        result = sql.query(selectSql,dict_mark=True)
        global WORD
        WORD = result[0]['WORD'] if result else ''
        ZNNAME = result[0]['ZNNAME'] + ' | ' + result[0]['SOUNDMARK'] if result else ''
        ENEXAMPLE = result[0]['ENEXAMPLE'] if result else ''
        ZNEXAMPLE = result[0]['ZNEXAMPLE'] if result else ''
        TIPS = ZNNAME + '\n' + ENEXAMPLE + '\n' + ZNEXAMPLE
        self.WordTextBrowser.setText("  "+WORD)
        self.WordTextBrowser.setToolTip(TIPS)
        self.NextBtn.setToolTip(TIPS)

    def retranslateUi(self, MainWindow):
        self.otherInfoShow()
        self.timer = QTimer(MainWindow)
        self.timer.timeout.connect(self.otherInfoShow)
        self.timer.start(10000)
        self.WordsShow()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    font = app.font()
    font.setPointSize(7)
    app.setFont(font)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    ti = TrayIcon(MainWindow)
    ti.show()
    sys.exit(app.exec_())

