import datetime

from PyQt6 import QtCore
from PyQt6.QtCore import QObject

from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class sortdisplaySever(QObject):
    sortupdate = QtCore.pyqtSignal(str, dict, list, str, str)

    def __init__(self, name, ip, selectedtime, text, displayMode, selectedbc, displayselect, thread):
        super().__init__()
        self.funcName = name
        self.ipinfo = ip
        self.selectedtime = selectedtime
        self.text = text
        self.displayMode = displayMode
        self.selectedbc = selectedbc
        self.displayselect_mode = displayselect
        self.thread = thread
        nowDay = datetime.datetime.now().strftime("%Y%m%d")
        tomorr =(datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y%m%d")
        yester =(datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d")
        if self.selectedtime == nowDay:
            self.date = "2"
        elif self.selectedtime == tomorr:
            self.date = "3"
        elif self.selectedtime == yester:
            self.date = "1"
        else:
            self.date = "4"

    def run(self):
        try:
            list = []
            if self.funcName == "sortTableWidgetDispaly":
                #print("1")
                self.sortTableWidgetDispaly()
                self.sortupdate.emit("sortTableWidgetDispaly", self.sorttableWidgetDispalydata, list, self.seversts,self.displayMode)
                self.sortupdate.emit("sortTableWidgetDispalyALL", self.DispalydataAll, list, self.seversts,self.displayMode)
            if self.funcName == "sortTableWidgetDispalyALL":
                #print("2")
                self.sortTableWidgetDispalyALL()
                self.sortupdate.emit("sortTableWidgetDispalyALL", self.sorttableWidgetDispalydata, list, self.seversts,self.displayMode)
            elif self.funcName == "SearchsortTableWidgetDispaly":
                #print("3")
                self.SearchsortTableWidgetDispaly()
                self.sortupdate.emit("SearchsortTableWidgetDispaly", self.sorttableWidgetDispalydata, list,self.seversts,self.displayMode)
            elif self.funcName == "sorttableWidgetDisplayChange":
                #print("4")
                self.sorttableWidgetDisplayChange()
                self.sortupdate.emit("sorttableWidgetDisplayChange", self.sortlogchange, list, self.seversts,self.displayMode)
            elif self.funcName == "sorttableWidgetPeopleDisplay":
                self.sorttableWidgetPeopleDisplay()
                self.sortupdate.emit("sorttableWidgetPeopleDisplay", self.sortdiplaylist, self.peopleOnJob,self.seversts, self.displayMode)
            elif self.funcName == "sorttableWidgetLOGDispaly":
                self.sorttableWidgetLOGDispaly()
                self.sortupdate.emit("sorttableWidgetLOGDispaly", self.sortlog, list, self.seversts, self.displayMode)
            elif self.funcName == "sorttableWidgetPHONEDispaly":
                self.sorttableWidgetPHONEDispaly()
                self.sortupdate.emit("sorttableWidgetPHONEDispaly", self.sorttableWidgetPHONEDispalydata, list,self.seversts, "")
            self.thread.quit()
        except Exception as e:
            app_logger.log_error(e)
            self.thread.quit()

    def severpost_nomeassge(self, postname, **kwargs):
        try:
            # ip = "http://" + str(self.ipinfo) + "/static/" + str(postname) + str(postdata) + str(postdata2) + str(postdata3)
            try:
                # res = requests.get(url=ip, timeout=30).json()
                res = api_fc.request_post('/static/{}'.format(postname), **kwargs)
                self.seversts = "1"
                return res
            except Exception as e:
                app_logger.log_error(e)
                app_logger.log_error("重大bug")
                app_logger.log_error('/static/{}  '.format(postname), **kwargs)
                self.seversts = "0"
                return {}
        except Exception as e:
            app_logger.log_error(e)

    def severget_nomeassge(self, postname, **kwargs):
        try:
            # ip = "http://" + str(self.ipinfo) + "/static/" + str(postname) + str(postdata) + str(postdata2) + str(postdata3)
            try:
                # res = requests.get(url=ip, timeout=30).json()
                res = api_fc.request_get('/static/{}'.format(postname))
                self.seversts = "1"
                return res
            except Exception as e:
                app_logger.log_error(e)
                app_logger.log_error("重大bug")
                app_logger.log_error('/static/{}  '.format(postname), **kwargs)
                self.seversts = "0"
                return []
        except Exception as e:
            app_logger.log_error(e)

    def sorttableWidgetPHONEDispaly(self):
        try:
            # sorttableWidgetPHONEDispalydataall = self.severpost_nomeassge("getphonelist", "", "", "")
            sorttableWidgetPHONEDispalydataall = self.severget_nomeassge('getphonelist')['data']
            self.sorttableWidgetPHONEDispalydata = {}
            num = 0
            if sorttableWidgetPHONEDispalydataall != None:
                if self.text != "":
                    for i in sorttableWidgetPHONEDispalydataall.keys():
                        if str.lower(str(self.text)) in str(sorttableWidgetPHONEDispalydataall[i]):
                            self.sorttableWidgetPHONEDispalydata[str(num)] = sorttableWidgetPHONEDispalydataall[i]
                            num += 1
                else:
                    self.sorttableWidgetPHONEDispalydata = sorttableWidgetPHONEDispalydataall
        except Exception as e:
            app_logger.log_error(e)

    def checkall(self, datas, text):
        res = {}
        try:
            num = 0
            for i in datas.keys():
                if datas[i]["109"] != text:
                    res[str(num)] = datas[i]
                    num += 1
        except Exception as e:
            app_logger.log_error(e)
        return res

    def checkStrsingle(self,datas, text, text2): #单一条件筛选
        res = {}
        try:
            num = 0
            for i in datas.keys():
                if str(text) in str(datas[i]) and datas[i]["109"] != text2:
                    res[str(num)] = datas[i]
                    num += 1
        except Exception as e:
            app_logger.log_error(e)
        return res
    def checkStrTerminalAll(self,datas, text1,text2,text3,text4): #筛选航站且显示全部
        res = {}
        try:
            num = 0
            for i in datas.keys():
                if str(datas[i]["8"]) != "" and datas[i]["109"] != text1:
                    if str(datas[i]["8"])[0] == text2 and str(datas[i]["8"])[0] == text3:
                        res[str(num)] = datas[i]
                        num += 1
                elif str(datas[i]["8"]) == "" and str(datas[i]["109"]) == text4:
                    res[str(num)] = datas[i]
                    num += 1
        except Exception as e:
            app_logger.log_error(e)
        return res
    def checkStrTerminalAll2(self,datas, text1,text2,text3,text4): #筛选航站且显示全部
        res = {}
        try:
            num = 0
            for i in datas.keys():
                if str(datas[i]["8"]) != "" and datas[i]["109"] != text1:
                    if str(datas[i]["8"])[0] != text2 and str(datas[i]["8"])[0] != text3:
                        res[str(num)] = datas[i]
                        num += 1
                elif str(datas[i]["8"]) == "" and str(datas[i]["109"]) == text4:
                    res[str(num)] = datas[i]
                    num += 1
        except Exception as e:
            app_logger.log_error(e)
        return res
    def checkStrTerminalAll3(self,datas, text1,text2,text3,text4): #筛选航站且显示全部
        res = {}
        try:
            num = 0
            for i in datas.keys():
                if str(datas[i]["8"]) != "" and datas[i]["109"] == text1:
                    if str(datas[i]["8"])[0] == text2 and str(datas[i]["8"])[0] == text3:
                        res[str(num)] = datas[i]
                        num += 1
                elif str(datas[i]["8"]) == "" and str(datas[i]["109"]) == text4:
                    res[str(num)] = datas[i]
                    num += 1
        except Exception as e:
            app_logger.log_error(e)
        return res
    def checkStrTerminalAll4(self,datas, text1,text2,text3,text4): #筛选航站且显示全部
        res = {}
        try:
            num = 0
            for i in datas.keys():
                if str(datas[i]["8"]) != "" and datas[i]["109"] == text1:
                    if str(datas[i]["8"])[0] != text2 and str(datas[i]["8"])[0] != text3:
                        res[str(num)] = datas[i]
                        num += 1
                elif str(datas[i]["8"]) == "" and str(datas[i]["109"]) == text4:
                    res[str(num)] = datas[i]
                    num += 1
        except Exception as e:
            app_logger.log_error(e)
        return res

    def sortTableWidgetDispaly(self):
        try:
            text = self.text
            Partdisplay = self.displayselect_mode  # 不显示起飞航班
            # print(Partdisplay)
            tableWidgetDispalydataAll = {}
            if self.displayMode == "A" and (self.selectedbc == "0" or self.date=="4"):
                tableWidgetDispalydataAll = self.severpost_nomeassge("tableWidgetDispaly",selectedtime="%s" % self.selectedtime,date="%s"%self.date)['data']
            elif self.displayMode == "B"and (self.selectedbc == "0" or self.date=="4"):
                tableWidgetDispalydataAll = self.severpost_nomeassge("tableWidgetDispaly2",selectedtime="%s" % self.selectedtime,date="%s"%self.date)['data']
            elif self.displayMode == "A" and self.selectedbc == "1":
                tableWidgetDispalydataAll = self.severpost_nomeassge("tableWidgetDispalyRead",date="%s"%self.date)['data']
            elif self.displayMode == "B"and self.selectedbc == "1":
                tableWidgetDispalydataAll = self.severpost_nomeassge("tableWidgetDispalyRead2", date="%s"%self.date)['data']
            #print("tableWidgetDispalydataAll")
            self.DispalydataAll=tableWidgetDispalydataAll
            self.sorttableWidgetDispalydata = {}
            num = 0
            if tableWidgetDispalydataAll != None:
                if text != "" and text != "T1" and text != "T2" and text != "T6" and text != "T2T6" and text != "T1T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata=self.checkStrsingle(tableWidgetDispalydataAll, text, "")
                elif text == "T1" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "", "1", "1", "1")
                elif text == "T2" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "", "2", "2", "2")
                elif text == "T2T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "", "1", "1", "1")
                elif text == "T1T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "", "2", "2", "1")
                elif text == "T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "", "1", "2", "1")
                elif text != "" and text != "T1" and text != "T2" and text != "T6" and text != "T2T6"  and text != "T1T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrsingle(tableWidgetDispalydataAll, text, "4")
                elif text == "T1" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "4", "1", "1", "1")
                elif text == "T2" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "4", "2", "2", "1")
                elif text == "T2T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "4", "1", "1", "1")
                elif text == "T1T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "4", "2", "2", "1")
                elif text == "T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "4", "1", "2", "1")
                elif text == "" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkall(tableWidgetDispalydataAll, "4")
                elif text != "" and text != "T1" and text != "T2" and text != "T6" and text != "T2T6" and text != "T1T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrsingle(tableWidgetDispalydataAll, text, "1")
                elif text == "T1" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll3(tableWidgetDispalydataAll, "1", "1", "1", "1")
                elif text == "T2" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll3(tableWidgetDispalydataAll, "1", "2", "2", "1")
                elif text == "T2T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll4(tableWidgetDispalydataAll, "1", "1", "1", "1")
                elif text == "T1T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll4(tableWidgetDispalydataAll, "1", "2", "2", "1")
                elif text == "T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll4(tableWidgetDispalydataAll, "1", "1", "2", "1")
                elif text == "" and Partdisplay == "3":
                    for i in tableWidgetDispalydataAll.keys():
                        if tableWidgetDispalydataAll[i]["109"] == '1':
                            self.sorttableWidgetDispalydata[str(num)] = tableWidgetDispalydataAll[i]
                            num += 1
                else:
                    self.sorttableWidgetDispalydata = tableWidgetDispalydataAll

        except Exception as e:
            app_logger.log_error(e)

    def sortTableWidgetDispalyALL(self):
        try:
            if self.displayMode == "A" and (self.selectedbc == "0" or self.date=="4"):
                self.sorttableWidgetDispalydata = self.severpost_nomeassge("tableWidgetDispaly",selectedtime="%s" % self.selectedtime,date="%s"%self.date)['data']
            elif self.displayMode == "B"and (self.selectedbc == "0" or self.date=="4"):
                self.sorttableWidgetDispalydata = self.severpost_nomeassge("tableWidgetDispaly2",selectedtime="%s" % self.selectedtime,date="%s"%self.date)['data']
            elif self.displayMode == "A" and self.selectedbc == "1":
                self.sorttableWidgetDispalydata = self.severpost_nomeassge("tableWidgetDispalyRead",date="%s"%self.date)['data']
            elif self.displayMode == "B"and self.selectedbc == "1":
                self.sorttableWidgetDispalydata = self.severpost_nomeassge("tableWidgetDispalyRead2",date="%s"%self.date)['data']
        except Exception as e:
            app_logger.log_error(e)



    def SearchsortTableWidgetDispaly(self):
        try:
            text = self.text
            self.seversts = "1"
            Partdisplay = self.displayselect_mode  # 不显示起飞航班
            # print(Partdisplay)
            tableWidgetDispalydataAll = self.selectedbc

            self.sorttableWidgetDispalydata = {}
            num = 0
            if tableWidgetDispalydataAll != None:
                if text != "" and text != "T1" and text != "T2" and text != "T6" and text != "T2T6" and text != "T1T6"and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrsingle(tableWidgetDispalydataAll, text, "")
                elif text == "T1" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "", "1", "1", "1")
                elif text == "T2" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "", "2", "2", "1")
                elif text == "T2T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "", "1", "1", "1")
                elif text == "T1T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "", "2", "2", "1")
                elif text == "T6" and Partdisplay == "0":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "", "1", "2", "1")
                elif text != "" and text != "T1" and text != "T2" and text != "T6" and text != "T2T6" and text != "T1T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrsingle(tableWidgetDispalydataAll, text, "4")
                elif text == "T1" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "4", "1", "1", "1")
                elif text == "T2" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll(tableWidgetDispalydataAll, "4", "2", "2", "1")
                elif text == "T2T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "4", "1", "1", "1")
                elif text == "T1T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "4", "2", "2", "1")
                elif text == "T6" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll2(tableWidgetDispalydataAll, "4", "1", "2", "1")
                elif text == "" and Partdisplay == "1":
                    self.sorttableWidgetDispalydata = self.checkall(tableWidgetDispalydataAll,  "4")

                elif text != "" and text != "T1" and text != "T2" and text != "T6" and text != "T2T6" and text != "T1T6" and Partdisplay == "3":
                    for i in tableWidgetDispalydataAll.keys():
                        if str(text) in str(tableWidgetDispalydataAll[i]) and tableWidgetDispalydataAll[i]["109"] == '1':
                            self.sorttableWidgetDispalydata[str(num)] = tableWidgetDispalydataAll[i]
                            num += 1
                elif text == "T1" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll3(tableWidgetDispalydataAll, "1", "1", "1", "1")
                elif text == "T2" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll3(tableWidgetDispalydataAll, "1", "2", "2", "1")
                elif text == "T2T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll4(tableWidgetDispalydataAll, "1", "1", "1", "1")
                elif text == "T1T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll4(tableWidgetDispalydataAll, "1", "2", "2", "1")
                elif text == "T6" and Partdisplay == "3":
                    self.sorttableWidgetDispalydata = self.checkStrTerminalAll4(tableWidgetDispalydataAll, "1", "1", "2", "1")
                elif text == "" and Partdisplay == "3":
                    for i in tableWidgetDispalydataAll.keys():
                        if tableWidgetDispalydataAll[i]["109"] == '1':
                            self.sorttableWidgetDispalydata[str(num)] = tableWidgetDispalydataAll[i]
                            num += 1
                else:
                    self.sorttableWidgetDispalydata = tableWidgetDispalydataAll
        except Exception as e:
            app_logger.log_error(e)


    def sorttableWidgetDisplayChange(self):
        try:
            text = self.text
            logall = self.severpost_nomeassge("tableWidgetDisplayChange",
                                              selectedtime="%s" % self.selectedtime)['data']
            self.sortlogchange = {}
            num = 0
            if text != "":
                for i in logall.keys():
                    if str(text) in str(logall[i]):
                        self.sortlogchange[str(num)] = logall[i]
                        num += 1
            else:
                self.sortlogchange = logall
        except Exception as e:
            app_logger.log_error(e)

    def sorttableWidgetPeopleDisplay(self):
        try:
            if self.displayselect_mode == "" or self.displayselect_mode == []:
                text = self.text
                self.peopleOnJob = [""]
                bc = self.selectedbc
                nowDaystr = self.selectedtime  # 选择的日期
                diplaylistall = self.severpost_nomeassge("qtPeopleLoad",
                                                         selectedtime="%s" % nowDaystr,
                                                         bc="%s" % bc)['data']
                self.sortdiplaylist = {}
                num = 0
                if text != "":
                    for i in diplaylistall.keys():
                        if str(text) in str(diplaylistall[i]):
                            self.sortdiplaylist[str(num)] = diplaylistall[i]
                            num += 1
                else:
                    self.sortdiplaylist = diplaylistall
                for i in self.sortdiplaylist.keys():
                    self.peopleOnJob.append(self.sortdiplaylist[i]["姓名"])
            else:
                names = self.displayselect_mode
                text = self.text
                self.peopleOnJob = [""]
                bc = self.selectedbc
                nowDaystr = self.selectedtime  # 选择的日期
                diplaylistall = self.severpost_nomeassge("qtPeopleLoad",
                                                         selectedtime="%s" % nowDaystr,
                                                         bc="%s" % bc)['data']
                self.sortdiplaylist = {}
                num = 0
                if text != "":
                    for i in diplaylistall.keys():
                        if str(text) in str(diplaylistall[i]):
                            for name in names:
                                if str(name) in str(diplaylistall[i]):
                                    self.sortdiplaylist[str(num)] = diplaylistall[i]
                                    num += 1
                else:
                    for i in diplaylistall.keys():
                        for name in names:
                            if str(name) in str(diplaylistall[i]):
                                self.sortdiplaylist[str(num)] = diplaylistall[i]
                                num += 1
                for i in self.sortdiplaylist.keys():
                    self.peopleOnJob.append(self.sortdiplaylist[i]["姓名"])
        except Exception as e:
            app_logger.log_error(e)

    def sorttableWidgetLOGDispaly(self):
        try:
            text = self.text
            logall = self.severpost_nomeassge("tableWidgetLOGDispaly",
                                              selectedtime="%s" % self.selectedtime)['data']
            self.sortlog = {}
            num = 0
            if text != "":
                for i in logall.keys():
                    if str(text) in str(logall[i]):
                        self.sortlog[str(num)] = logall[i]
                        num += 1
            else:
                self.sortlog = logall
        except Exception as e:
            app_logger.log_error(e)