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

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# 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 requests
import pyttsx3.drivers
import pyttsx3.drivers.sapi5
import pyttsx3
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
import json
import requests
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, Translation):
        Translation.setObjectName("Translation")
        Translation.resize(500, 520)
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(12)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        Translation.setFont(font)
        self.centralwidget = QtWidgets.QWidget(Translation)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(150, 30, 200, 30))
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(50, 90, 260, 20))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(12)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(50, 130, 400, 30))
        self.lineEdit.setObjectName("lineEdit")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(50, 180, 100, 20))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(12)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser.setGeometry(QtCore.QRect(50, 220, 400, 200))
        self.textBrowser.setObjectName("textBrowser")

        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(100, 440, 100, 50))
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(300, 440, 100, 50))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(15)
        font.setBold(True)
        font.setItalic(True)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        font = QtGui.QFont()
        font.setFamily("ItalicT")
        font.setPointSize(15)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(50)
        Translation.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(Translation)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 555, 25))
        self.menubar.setObjectName("menubar")
        Translation.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(Translation)
        self.statusbar.setObjectName("statusbar")
        Translation.setStatusBar(self.statusbar)

        self.retranslateUi(Translation)
        # 点击功能

        self.pushButton.clicked.connect(self.slot)
        self.pushButton_2.clicked.connect(self.slot2)
        QtCore.QMetaObject.connectSlotsByName(Translation)

    def retranslateUi(self, Translation):
        _translate = QtCore.QCoreApplication.translate
        Translation.setWindowTitle(_translate("Translation", "Translation"))
        self.label.setText(_translate("Translation", "自制翻译软件"))
        self.label_2.setText(_translate("Translation", "请输入需要翻译的文字内容："))
        self.label_3.setText(_translate("Translation", "翻译结果："))
        self.textBrowser.setHtml(_translate("Translation",
                                            "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                                            "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                                            "p, li { white-space: pre-wrap; }\n"
                                            "</style></head><body style=\" font-family:\'黑体\'; font-size:12pt; font-weight:400; font-style:normal;\">\n"
                                            "</body></html>"))

        self.pushButton.setText(_translate("MainWindow", "翻译"))
        self.pushButton.setStyleSheet("color:red")
        self.pushButton_2.setText(_translate("MainWindow", "清空"))
        self.pushButton_2.setStyleSheet("color:gray")

    def fanyi(self):  # 无限循环
        # print(self.lineEdit.text())
        if self.lineEdit.text():
            print('ok')
            content = str(self.lineEdit.text())  # 获取输入·框的值self.lineEdit.text()
            print(content)
            url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'  # 选择要爬取的网页，上面找过了
            # 手动替换一下
            header = {
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'}

            # 伪装计算机提交翻译申请(下面的内容也在在上面有过，最好根据自己的进行修改)
            data = {}
            data['type'] = 'AUTO'
            data['i'] = content
            data['doctype'] = 'json'
            data['version'] = '2.1'
            data['keyfrom:'] = 'fanyi.web'
            data['ue'] = 'UTF-8'
            data['typoResult'] = 'true'
            # post请求
            response = requests.post(url, headers=header, data=data)
            # 解码
            html = response.content.decode('utf-8')
            # 转换为字典
            paper = json.loads(html)
            # 打印翻译结果
            print("翻译结果: %s" % (paper['translateResult'][0][0]['tgt']))
            return paper['translateResult'][0][0]['tgt']
        else:
            self.messageDialog()

    def slot(self):
        print('正在运行')
        self.updateUi(self.fanyi())

    def slot2(self):
        print('删除')
        self.textBrowser.clear()
        self.lineEdit.clear()

    def updateUi(self, text):
        try:
            # text = 'bfsdgfkh klshal onfsydb vero yubtsherklu bhsdoirhgh'
            self.textBrowser.append("<br >%s</br>" % text)  # 显示内容支撑html格式语法
        except:
            self.textBrowser.append("<font color=red>%s is invalid!</font>" % text)

    # 警告框
    def messageDialog(self):
        msg_box = QMessageBox(QMessageBox.Warning, '提示', '输入值为空')
        msg_box.exec_()


import sys  # 导入系统模块


def show_MainWindow():
    app = QtWidgets.QApplication(sys.argv)  # 实例化QApplication类，作为GUI主程序入口
    MainWindow = QtWidgets.QMainWindow()  # 创建MainWindow
    ui = Ui_MainWindow()  # 实例化ui类
    ui.setupUi(MainWindow)  # 设置窗口UI
    MainWindow.show()  # 显示窗口
    sys.exit(app.exec_())  # 当窗口创建完成时，需要结束主循环过程


if __name__ == "__main__":
    show_MainWindow()
