
from PyQt6.QtWidgets import QWidget , QMessageBox

from UI.changePassword import Ui_FormChangePssword
from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class changePassword(Ui_FormChangePssword, QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.setupUi(self)
            self.ipinfo = None
            self.pushButton.clicked.connect(self.btn)
            self.user = 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)
            # res = requests.get(url=ip, timeout=30).json()
            res = api_fc.request_post('/static/{}'.format(postname), **kwargs)
            return res
        except Exception as e:
            # print('登录服务器失败')
            QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
            app_logger.log_error(e)
            return ''

    def severpost_data(self, postname, data: dict):
        try:
            # ip = "http://" + str(self.ipinfo) + "/static/" + str(postname)
            # data = json.dumps(data)
            # res = requests.post(url=ip, data=data, timeout=30).json()
            res = api_fc.request_post('/static/{}'.format(postname), data=data)
            return res
        except Exception as e:
            QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
            app_logger.log_error(e)

            return 'fail'

    def btn(self):
        try:
            oldpassword = self.lineEditold.text()
            newpassword = self.lineEditnew.text()
            newpassword2 = self.lineEditnew2.text()
            #res = self.severpost_meassge("loginTable",username="/%s" % self.user,password="/%s" % oldpassword)["data"]["返回值"]
            res =api_fc.request_post_without_token("/loginTable",username=self.user,password=oldpassword)["data"]["返回值"]
            # print(res)
            if res != "":
                if newpassword == newpassword2:
                    dataDic = {'登录名': self.user, '新密码': newpassword, "旧密码": oldpassword}
                    res = self.severpost_data("changePassword", dataDic)
                    if res["返回值"] == "ok":
                        self.close()
                        QMessageBox.warning(self, "提示", "密码修改成功！！！")
                    else:
                        QMessageBox.warning(self, "提示", "密码修改失败，请检查服务器连接状态或联系管理员！！！")
                else:
                    QMessageBox.warning(self, "警告", "两次密码输入不同！！！")
            else:
                QMessageBox.warning(self, "警告", "原密码错误！！！")
        except Exception as e:
            app_logger.log_error(e)