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

from UI.adduser import Ui_FormAdduser
from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class addUserWidget(Ui_FormAdduser, QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.setupUi(self)
            self.pushButton.clicked.connect(self.btn)
            self.comboBox.addItems(['1', '2', '3',"4"])
            self.comboBox.setEditable(True)
            self.filterModel = QSortFilterProxyModel(self.comboBox)
            self.filterModel.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
            self.filterModel.setSourceModel(self.comboBox.model())
            self.completer = QCompleter(self.filterModel, self.comboBox)
            self.completer.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion)
            self.completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
            self.comboBox.setCompleter(self.completer)

            self.comboBox.lineEdit().textEdited.connect(self.filterModel.setFilterFixedString)
            self.completer.activated.connect(self.on_completer_activated)
            self.ipinfo = None
            self.user = None
            self.authority=None
        except Exception as e:
            app_logger.log_error(e)



    def severpost_meassge(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 on_completer_activated(self, text):
        try:
            if text:
                index = self.comboBox.findText(text)
                self.comboBox.setCurrentIndex(index)
        except Exception as e:
            app_logger.log_error(e)

    def btn(self):
        try:
            if int(self.authority) <= 1:
                username = self.lineEditUser.text()
                password = self.lineEditPWD.text()
                authority = self.comboBox.currentText()
                people = self.lineEditPeople.text()
                if username != "" and password != "":
                    # print('用户名：{}，密码：{}，权限：{}，使用人：{}'.format(username,password,authority,people))
                    dataDic = {
                        '登录名': username,
                        '密码': password,
                        '权限': authority,
                        '使用人': people
                    }

                    res = self.severpost_meassge("addUserWidget", dataDic)
                    if res["返回值"] == "1":
                        self.close()
                        self.show_message("提示", "用户创建成功！！！")
                    elif res["返回值"] == "2":
                        self.show_message("警告", "此用户已存在")
                    elif res["返回值"] == "0":
                        self.show_message("警告", "创建失败，请联系管理员！")
                else:
                    self.show_message("警告", "用户名或密码不能为空！！！")
            else:
                self.close()
                self.show_message("警告", "权限不够，请联系管理员！！！")
        except Exception as e:
            app_logger.log_error(e)

    def show_message(self, type, str):
        try:
            QMessageBox.warning(self, "%s" % type, "%s" % str)
        except Exception as e:
            app_logger.log_error(e)
