
from PyQt6 import QtCore
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QColor
from PyQt6.QtWidgets import QWidget , QMessageBox , QTableWidgetItem

from UI.handoverFlight import Ui_handoverFlight
from .LogerinTxt import app_logger
from Functions.apiFunction import api_fc


class handoverFlightWidget(Ui_handoverFlight, QWidget):
    handoverFlight_signal = QtCore.pyqtSignal(str)
    def __init__(self, parent=None):
        super().__init__(parent)
        try:
            self.setupUi(self)
            self.pushButton.clicked.connect(self.btn)
            self.user = None
            self.ipinfo = None
            self.selectedtime=None
            self.Allflight = {}
        except Exception as e:
            app_logger.log_error(e)
    def severpostData_nomeassge(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)
    def btn(self):
        try:
            list = []
            sts=[]
            list_cz = []
            sts_cz = []
            rows=[]
            for row in range(self.tableWidgetFlight.rowCount()):
                item = self.tableWidgetFlight.item(row, 0)
                if item and item.checkState() == Qt.CheckState.Checked and self.tableWidgetFlight.item(row, 8).text() != "":
                    name = self.tableWidgetFlight.item(row, 10).text()
                    rows.append(row)
                    list.append(name)
                    sts.append("1")
            data = {"taskid": ','.join(list),
                    "sts": ','.join(sts)}

            if list !=[]:
                res = self.severpostData_nomeassge("handoverflightAMRO", data=data)["返回值"]
                if res == "ok" :
                    QMessageBox.warning(self, "提示", f"交班提交成功！请核对附加消息交班航班！")
                    for ii in rows:
                        try:
                            if "【交班航班】" not in self.tableWidgetFlight.item(ii, 11).text() and self.tableWidgetFlight.item(ii, 8).text() != "":
                                flightid = self.tableWidgetFlight.item(ii, 12).text()
                                flighttype = self.tableWidgetFlight.item(ii, 7).text()
                                fjxx = "【交班航班】" + self.tableWidgetFlight.item(ii, 11).text()
                                # ip = "http://" + str(self.ipinfo) + "/static/updateEidteItem/" + "%s/" % str(fjxx) + "%s/" % str(flightid) + "A/%s/" % str(flighttype) + "%s" % str(self.selectedtime)
                                try:
                                    # requests.get(url=ip, timeout=30).json()
                                    api_fc.request_post('/static/updateEidteItem',
                                                        text="%s" % str(fjxx),
                                                        flightid="%s" % str(flightid),
                                                        displayMode="A",
                                                        flighttype="%s" % str(flighttype),
                                                        selectedtime="%s" % str(self.selectedtime))
                                    self.handoverFlight_signal.emit("1")
                                except Exception as e:
                                    QMessageBox.warning(self, "提示", "服务器连接超时，请联系管理员检查服务器！")
                                    app_logger.log_error(e)
                        except Exception as e:
                            app_logger.log_error(e)

                    self.close()
                else:
                    QMessageBox.warning(self, "警告", "航班交接失败，请重新尝试")

            else:
                QMessageBox.warning(self, "警告", "请选择要交接的航班！未进行派工的航班无法进行交接班")
        except Exception as e:
            app_logger.log_error(e)

    def start(self):
        try:
            self.show()
            peopleLabel = ["选择","序号", "机号","航班号", "预达", "计飞", "机位", "类型", "维修人员","放行", "任务编号","附加消息","航班编号" ]
            #tableWidgetDispalydata = self.Allflight
            tableWidgetDispalydata={}
            for key, values in self.Allflight.items():
                # 检查所有字段是否包含关键词
                if(('3U' in values["9"] or "CSC" in values["9"]) and values["49"] != "" and "【交班航班】" not in values["30"]):
                    tableWidgetDispalydata[key] = values
            self.tableWidgetFlight.setColumnCount(len(peopleLabel))
            self.tableWidgetFlight.setHorizontalHeaderLabels(peopleLabel)
            self.tableWidgetFlight.verticalHeader().setVisible(False)
            self.tableWidgetFlight.setRowCount(len(tableWidgetDispalydata))
            i = 0
            for row in tableWidgetDispalydata.keys():
                if ("3U" in tableWidgetDispalydata[row][str(9)] or "CSC" in tableWidgetDispalydata[row][str(9)]) and \
                        tableWidgetDispalydata[row][str(49)] != "" and "【交班航班】" not in tableWidgetDispalydata[row][str(30)]:
                    for colNum in range(0, 13):
                        if colNum == 0:
                            checkbox = QTableWidgetItem()
                            checkbox.setCheckState(Qt.CheckState.Unchecked)
                            self.tableWidgetFlight.setItem(i, colNum, checkbox)
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 1:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(i+1)))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 2:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(3)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 3:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(9)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 4:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(13)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 5:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(15)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)

                        elif colNum == 6:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(8)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 7:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(19)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 8:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(49)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)

                        elif colNum == 9:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(51)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 10:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(53)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 12:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(53)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        elif colNum == 11:
                            self.tableWidgetFlight.setItem(i, colNum, QTableWidgetItem(str(tableWidgetDispalydata[row][str(61)])))
                            self.tableWidgetFlight.item(i, colNum).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                        if (i+1)%2 ==0 and str(tableWidgetDispalydata[row][str(109)]) =="1":
                            self.tableWidgetFlight.item(i, colNum).setBackground(QColor('#DDE2E3'))
                        elif str(tableWidgetDispalydata[row][str(109)]) !="1":
                            self.tableWidgetFlight.item(i, colNum).setBackground(QColor('#00FFFF'))
                    i += 1


            self.tableWidgetFlight.resizeColumnsToContents()
            self.tableWidgetFlight.setColumnHidden(12, True)
            self.tableWidgetFlight.setColumnHidden(10, True)
        except Exception as e:
            app_logger.log_error(e)