from PyQt6 import QtCore
from PyQt6.QtWidgets import QWidget , QMessageBox

from UI.login import Ui_login
from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class LoginWidget(Ui_login, QWidget):
    login_signal = QtCore.pyqtSignal(bool)
    login_user = QtCore.pyqtSignal(list)

    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.setupUi(self)
            # print('login widget')
            self.pushButton.clicked.connect(self.btn)
            # self.setipinfo()
            self.ipinfo = None
        except Exception as e:
            app_logger.log_error(e)

    def severpost_meassge(self, postname, **kwargs):
        try:
            # ip = "http://" + str(self.ipinfo) + "/static/" + str(postname) + str(postdata) + str(postdata2)
            try:
                # res = requests.get(url=ip, timeout=30).json()
                res = api_fc.request_post('/static/{}'.format(postname), **kwargs)
                # print(res)

            except Exception as e:
                # print('登录服务器失败')
                app_logger.log_error('登录服务器失败')
                res = ""
                QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
                app_logger.log_error(e)

            return res
        except Exception as e:
            app_logger.log_error(e)

    def btn(self):
        try:
            username = self.lineEditUser.text()
            password = self.lineEditPassword.text()
            try:
                res = api_fc.get_access_token(username, password)["返回值"]
                # print(res)
            except Exception as e:
                res = ""
                app_logger.log_error(e)

            # print(res)
            if res != "" and int(res[3]) <= 4:
                self.login_signal.emit(True)
                self.login_user.emit(res)
            else:
                self.show_message()
        except Exception as e:
            app_logger.log_error(e)

    def show_message(self):
        try:
            QMessageBox.warning(self, "警告", "无此用户或密码错误或账号无权限访问办公平台")
        except Exception as e:
            app_logger.log_error(e)