import os
from PyQt6 import QtCore
from PyQt6.QtCore import QThreadPool
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QColor , QFont
from PyQt6.QtWidgets import QWidget , QAbstractItemView , QMessageBox , QTableWidgetItem
from Functions.apiFunction import api_fc
from Functions import serverFind
from UI.findserver import Ui_FormLink
from UI.mapWeb import Ui_FormMapWeb
from .LogerinTxt import app_logger
from .Worker2 import Worker2


class mapWebWidget(Ui_FormMapWeb, QWidget):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # self.webEngineView.load(QUrl('http://192.168.2.22:6010/'))


class findServerWidget(Ui_FormLink, QWidget):
    selectServer_signal = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.threadpool = QThreadPool()
            self.setupUi(self)
            self.serverList = []
            self.tableWidget.setColumnCount(2)
            self.tableWidget.setHorizontalHeaderLabels(['服务器地址', '备注'])
            self.threadWork_findServer()
            self.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
            self.tableWidget.cellDoubleClicked.connect(self.selectServer)
            self.pushButton_manset.clicked.connect(self.setipinfo)
        except Exception as e:
            app_logger.log_error(e)

    def setipinfo(self):
        try:
            self.ipinfo = ""
            if os.path.exists("server.code") is True:
                read_path = os.getcwd() + "\\server.code"
                with open(read_path, "r", encoding="utf-8") as f2:
                    rember_2 = f2.read()
                    if ';' in rember_2:
                        self.ipinfo = rember_2.split(';')[0]
                        self.ipinfo1 = rember_2.split(':')[0]
                        #ip = "http://" + str(self.ipinfo) + "/static/linktest"
                        try:
                            #res = requests.get(url=ip, timeout=30).json()
                            res=api_fc.request_get_without_token("/static/linktest")
                            self.selectServer_signal.emit(self.ipinfo1)
                            if res['status'] == "ok":
                                QMessageBox.warning(self, "提示", "服务器人工配置成功！")
                            else:
                                QMessageBox.warning(self, "提示", "服务器人工配置失败，请检查配置文件或联系管理员检查服务器！")
                        except Exception as e:
                            QMessageBox.warning(self, "提示", "服务器人工配置失败，请联系管理员检查服务器！")
                            app_logger.log_error(e)
                    else:
                        QMessageBox.warning(self, "提示", "服务器人工配置失败，请检查配置文件或联系管理员检查服务器！")
            else:
                QMessageBox.warning(self, "提示", "服务器人工配置失败，系统缺少配置文件！")
        except Exception as e:
            app_logger.log_error(e)
    def setipinfo2(self):
        try:
            self.ipinfo = ""
            if os.path.exists("server.code") is True:
                read_path = os.getcwd() + "\\server.code"
                with open(read_path, "r", encoding="utf-8") as f2:
                    rember_2 = f2.read()
                    if ';' in rember_2:
                        self.ipinfo = rember_2.split(';')[0]
                        self.ipinfo1 = rember_2.split(':')[0]
                        #ip = "http://" + str(self.ipinfo) + "/static/linktest"
                        try:
                            #res = requests.get(url=ip, timeout=30).json()
                            res=api_fc.request_get_without_token("/static/linktest")
                            self.selectServer_signal.emit(self.ipinfo1)
                            if res['status'] == "ok":
                                QMessageBox.warning(self, "提示", "服务器搜索失败，自动检索配置文件配置成功！")
                            else:
                                QMessageBox.warning(self, "提示", "服务器搜索失败，自动检索配置文件配置成功，服务器连接失败，请检查配置文件或联系管理员检查服务器！")
                        except Exception as e:
                            QMessageBox.warning(self, "提示", "服务器搜索失败，自动检索配置文件配置成功，服务器连接失败，请检查配置文件或联系管理员检查服务器！")
                            app_logger.log_error(e)
                    else:
                        QMessageBox.warning(self, "提示", "服务器搜索失败，自动检索配置文件配置失败，请检查配置文件或联系管理员检查服务器！")
            else:
                QMessageBox.warning(self, "提示", "服务器搜索失败，自动检索配置文件配置失败，系统缺少配置文件！")
        except Exception as e:
            app_logger.log_error(e)

    def selectServer(self, row, col):
        #print('selectServer')
        #print(self.tableWidget.item(row, 0).text())
        try:
            self.selectServer_signal.emit(self.tableWidget.item(row, 0).text())
        except Exception as e:
            app_logger.log_error(e)

    def threadWork_findServer(self):
        try:
            worker = Worker2(self.fn)
            worker.signals.result.connect(self.print_out_result)
            self.threadpool.start(worker)
        except Exception as e:
            app_logger.log_error(e)

    def fn(self):
        try:
            serverList = serverFind.findServer()
            return serverList
        except Exception as e:
            app_logger.log_error(e)

    def print_out_result(self, dlist):
        try:
            unique_tuples = list(set(tuple(sublist) for sublist in dlist))
            self.serverList = [list(t) for t in unique_tuples]
            # print(self.serverList)
            if self.serverList == [] or self.serverList ==None:
                self.setipinfo2()
            else:
                self.tableWidget.setRowCount(len(self.serverList))
                rowNum = 0
                for row in self.serverList:
                    colNum = 0
                    for col in row:
                        self.tableWidget.setItem(rowNum, colNum, QTableWidgetItem(col))
                        self.tableWidget.item(rowNum, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        if "测试服务器" in row[1]:
                            self.tableWidget.item(rowNum, colNum).setForeground(QColor('pink'))
                        elif row[1] == "主服务器":
                            self.tableWidget.item(rowNum, colNum).setForeground(QColor('green'))
                            font = QFont()
                            font.setFamily("Microsoft YaHei")
                            font.setBold(True)
                            self.tableWidget.item(rowNum, colNum).setFont(font)
                        else:
                            self.tableWidget.item(rowNum, colNum).setForeground(QColor('blue'))
                            font = QFont()
                            font.setFamily("Microsoft YaHei")
                            font.setBold(True)
                            self.tableWidget.item(rowNum , colNum).setFont(font)
                        colNum += 1
                    rowNum += 1
                self.tableWidget.resizeColumnsToContents()
        except Exception as e:
            app_logger.log_error(e)