
from PyQt6.QtCore import Qt , QSortFilterProxyModel
from PyQt6.QtWidgets import QCompleter , QWidget , QMessageBox

from UI.changeAuth import Ui_changeAuth
from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class changeAuth(Ui_changeAuth, QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.setupUi(self)
            self.ipinfo = None
            self.label_5.setText("")
            self.label_6.setText("")
            self.pushButton.clicked.connect(self.btn)
            self.user = None
            self.comboBox.addItems(['1', '2', '3',"4"])
            self.comboBox.setEditable(True)
            self.filterModel1 = QSortFilterProxyModel(self.comboBox)
            self.filterModel1.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
            self.filterModel1.setSourceModel(self.comboBox.model())
            self.completer1 = QCompleter(self.filterModel1, self.comboBox)
            self.completer1.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion)
            self.completer1.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
            self.comboBox.setCompleter(self.completer)
            self.comboBox.lineEdit().textEdited.connect(self.filterModel1.setFilterFixedString)
            self.completer1.activated.connect(self.on_completer_activated1)
        except Exception as e:
            app_logger.log_error(e)

    def start(self):
        self.show()
        try:
            # ip = "http://" + str(self.ipinfo) + "/static/loginDbget/" + str(self.user)
            # self.res = requests.get(url=ip, timeout=30).json()
            self.res = api_fc.request_post('/static/loginDbget', username=str(self.user))["data"]
        except Exception as e:
            # print('登录服务器失败')
            QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
            app_logger.log_error(e)
            self.res = {}
        if self.res != {}:
            namelist = []
            for i in self.res.keys():
                namelist.append(self.res[i]["登录名"])
            print(namelist)
            self.comboBox_2.addItems(namelist)
            self.comboBox_2.setEditable(True)
            self.comboBox_2.currentIndexChanged.connect(self.changed)
            self.filterModel = QSortFilterProxyModel(self.comboBox_2)
            self.filterModel.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
            self.filterModel.setSourceModel(self.comboBox_2.model())
            self.completer = QCompleter(self.filterModel, self.comboBox_2)
            self.completer.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion)
            self.completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
            self.comboBox_2.setCompleter(self.completer)
            self.comboBox_2.lineEdit().textEdited.connect(self.filterModel.setFilterFixedString)
            self.completer.activated.connect(self.on_completer_activated)
        else:
            QMessageBox.warning(self, "提示", "获取数据库为空，请检查数据库或联系管理员")

    def on_completer_activated1(self, text):
        try:
            if text:
                index = self.comboBox.findText(text)
                self.comboBox.setCurrentIndex(index)
        except Exception as e:
            app_logger.log_error(e)

    def on_completer_activated(self, text):
        try:
            if text:
                print(text)
                index = self.comboBox_2.findText(text)
                self.comboBox_2.setCurrentIndex(index)
        except Exception as e:
            app_logger.log_error(e)

    def changed(self):
        if self.res != {}:
            self.label_5.setText(self.res[self.comboBox_2.currentText()]["使用人"])
            self.label_6.setText(self.res[self.comboBox_2.currentText()]["权限"])

    def btn(self):
        data = {
            '登录名': "'%s'" % self.comboBox_2.currentText(),
            "权限": "'%s'" % self.comboBox.currentText()
        }
        try:
            ip = "http://" + str(self.ipinfo) + "/static/changeAuth"
            # data = json.dumps(data)
            # res = requests.post(url=ip, data=data, timeout=30).json()
            res = api_fc.request_post('/static/changeAuth', data=data)
            if res["返回值"] == "1":
                QMessageBox.warning(self, "提示", "权限变更成功！")
                self.close()
            else:
                QMessageBox.warning(self, "提示", "权限变更失败，请联系管理员检查服务器！")
        except Exception as e:
            QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
            app_logger.log_error(e)