import sys
from itertools import product

from PyQt5 import sip
from PyQt5.QtWidgets import QApplication, QSizePolicy, QLabel, QWidget

import json
import threading
import time
from functools import partial
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QCursor, QFont
from PyQt5.QtWidgets import QPushButton, QMainWindow, QMenu, QMessageBox

import message.message_pb2 as message
import google.protobuf.text_format as tf
import re
import ui.spaceUi as sui
import spaceManage as spmng
import async_communication as cmt
import mcpu_communication as mcn
from led import Led

# db参数
db_ip = "192.168.1.233"
# db_ip = "127.0.0.1"
db_port = 3306
db_name = "ct_project"
db_user = "zx"
db_password = "zx123456"
# db_user = "root"
# db_password = "123456"
# mq参数
mq_ip = "192.168.1.233"
# mq_ip = "127.0.0.1"
mq_port = 5672
mq_user = "zx"
mq_password = "zx123456"
# mq_user = "wk"
# mq_password = "123456"

statu_ex_keys = [
    ["statu_ex", "in_mcpu_1_statu_port"],
    ["statu_ex", "in_mcpu_2_statu_port"],
    ["statu_ex", "in_mcpu_3_statu_port"],
    ["statu_ex", "in_mcpu_4_statu_port"],
    ["statu_ex", "in_mcpu_5_statu_port"],
    ["statu_ex", "in_mcpu_6_statu_port"],
    ["statu_ex", "out_mcpu_1_statu_port"],
    ["statu_ex", "out_mcpu_2_statu_port"],
    ["statu_ex", "out_mcpu_3_statu_port"],
    ["statu_ex", "out_mcpu_4_statu_port"],
    ["statu_ex", "out_mcpu_5_statu_port"],
    ["statu_ex", "out_mcpu_6_statu_port"]
]

mcpu_keys = [
    ["in", 1, "192.168.1.120", 40005],
    ["in", 2, "192.168.1.121", 40005],
    ["in", 3, "192.168.1.122", 40005],
    ["in", 4, "192.168.1.123", 40005],
    ["in", 5, "192.168.1.124", 40005],
    ["in", 6, "192.168.1.125", 40005],
    ["out", 1, "192.168.1.130", 40005],
    ["out", 2, "192.168.1.131", 40005],
    ["out", 3, "192.168.1.132", 40005],
    ["out", 4, "192.168.1.133", 40005],
    ["out", 5, "192.168.1.134", 40005],
    ["out", 6, "192.168.1.135", 40005]
]


class QPBtn(QPushButton):
    clickedSignal = pyqtSignal(bool)  # 定义带参信号

    def __init__(self, parent=None):
        super(QPBtn, self).__init__(parent)

    def mousePressEvent(self, event):  # 重定义该函数，对不同的操作释放不同的信号参数
        if event.buttons() == Qt.LeftButton:
            self.clickedSignal.emit(True)
        elif event.buttons() == Qt.RightButton:
            self.clickedSignal.emit(False)


class MainWindow(QMainWindow, threading.Thread):
    drawSpaceBtnSignal = pyqtSignal(dict, int)
    drawMcpuBtnSignal = pyqtSignal(str)
    drawRmqBtnSignal = pyqtSignal(list)
    drawLedSignal = pyqtSignal()
    drawUnitProcessSignal = pyqtSignal()

    def __init__(self):
        threading.Thread.__init__(self)
        QMainWindow.__init__(self)
        self.rmq_statu = {}
        self.rmq_timeout = {}
        self.command_queue_dict = {}

        self.ui = sui.Ui_MainWindow()
        self.ui.setupUi(self)
        self.isClose = False
        self.drawSpaceBtnSignal.connect(self.drawSpaceBtn)
        self.drawRmqBtnSignal.connect(self.drawRmqBtn)
        self.drawLedSignal.connect(self.drawLed)
        self.drawUnitProcessSignal.connect(self.drawUnitProcess)
        self.drawMcpuBtnSignal.connect(self.drawMcpuBtn)

        self.btn_positions = [(i, j) for i in range(13, -1, -1) for j in range(6)]

        # self.ui.in_mcpu_1_statu_btn = QPBtn(self.ui.in_mcpu_1_statu_btn)
        self.ui.in_mcpu_1_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.in_mcpu_2_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.in_mcpu_3_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.in_mcpu_4_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.in_mcpu_5_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.in_mcpu_6_statu_btn.clicked.connect(self.mcpu_btn_click)

        self.ui.out_mcpu_1_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.out_mcpu_2_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.out_mcpu_3_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.out_mcpu_4_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.out_mcpu_5_statu_btn.clicked.connect(self.mcpu_btn_click)
        self.ui.out_mcpu_6_statu_btn.clicked.connect(self.mcpu_btn_click)

    def getBackGroundColor(self, color):
        if color == "red":
            return "background-color:rgb(255,70,70)"
        elif color == "gray":
            return "background-color:rgb(168,168,168)"
        elif color == "green":
            return "background-color:rgb(0,180,0)"
        elif color == "yellow":
            return "background-color:rgb(248,239,71)"
        elif color == "pastel":
            return "background-color:rgb(241,158,194)"

    def drawMcpuBtn(self, key):
        mouth = key.split(':')[0]
        id = key.split(':')[1]
        btn_name = mouth + '_' + id + '_statu_btn'
        btn = self.findChild(QPushButton, btn_name)
        iomsg = g_mcpu.GetMcpuIoMsg(key)
        if g_mcpu.GetMcpuConnectStatus(key) is True or iomsg.timeout() is False:
            btn.setText(btn.text()[:10] + "正常")
            btn.setStyleSheet(self.getBackGroundColor("green"))

            btn.setToolTip(str(iomsg.statu))
        else:
            btn.setText(btn.text()[:10] + "断连")
            btn.setToolTip("None")
            btn.setStyleSheet(self.getBackGroundColor("gray"))

    def drawMcpuBtn(self, key):
        mouth = key.split(':')[0]
        id = key.split(':')[1]
        btn_name = mouth + '_' + id + '_statu_btn'
        btn = self.findChild(QPushButton, btn_name)
        iomsg = g_mcpu.GetMcpuIoMsg(key)
        if g_mcpu.GetMcpuConnectStatus(key) is True or iomsg.timeout() is False:
            btn.setText(btn.text()[:10] + "正常")
            btn.setStyleSheet(self.getBackGroundColor("green"))

            btn.setToolTip(str(iomsg.statu))
        else:
            btn.setText(btn.text()[:10] + "断连")
            btn.setToolTip("None")
            btn.setStyleSheet(self.getBackGroundColor("gray"))

    def drawUnitProcess(self):
        return
        if g_space.command_queue_dict is not False and g_space.command_queue_dict is not None:
            # if self.command_queue_dict != g_space.command_queue_dict

            for Aindex in range(self.ui.A_verticalLayout.count()):
                item = self.ui.A_verticalLayout.itemAt(Aindex)
                if item is not None:
                    self.ui.A_verticalLayout.removeItem(item)
                    sip.delete(item.widget())

            for Bindex in range(self.ui.B_verticalLayout.count()):
                wid = self.ui.B_verticalLayout.itemAt(Bindex).widget()
                if item is not None:
                    self.ui.B_verticalLayout.removeWidget(wid)
                    sip.delete(wid)

            for Cindex in range(self.ui.C_verticalLayout.count()):
                wid = self.ui.C_verticalLayout.itemAt(Cindex).widget()
                if item is not None:
                    self.ui.C_verticalLayout.removeWidget(wid)
                    sip.delete(wid)

            for dict in g_space.command_queue_dict:
                btn = QPBtn()
                measure = message.measure_info()
                # tf.Parse(dict["measure_info"],measure)
                a = 1.50
                str = "%s任务-------车牌号:%s 车高:%f" % (
                    "存车" if dict["type"] == 1 else "取车", dict["car_number"], a)
                color = ""
                if dict["statu"] == 1:
                    color = self.getBackGroundColor("yellow")
                elif dict["statu"] == 2:
                    color = self.getBackGroundColor("green")
                elif dict["statu"] == 0:
                    color = self.getBackGroundColor("pastel")
                elif dict["statu"] == 3:
                    color = self.getBackGroundColor("red")
                btn.setStyleSheet('border:3px groove orange;border-radius:10px;padding:2px 4px;' + color)
                tool_tip = '{"car_number":"%s",\n"primary_key":"%s",\n "unit":%d, \n"queue_id":%d, \n"type":%d ,' \
                           '\n "space_info":"%s", \n"measure_info":"%s", \n"export_id":%d}' % (
                               dict["car_number"], dict["primary_key"], dict["unit"], dict["queue_id"], dict["type"],
                               "None" if dict["space_info"] is None else dict["space_info"],
                               "None" if dict["measure_info"] is None else dict["measure_info"],
                               -1 if dict["export_id"] is None else dict["export_id"])
                # if self.findChild(QPBtn, dict["car_number"]) is not None:
                #     self.findChild(QPBtn, dict["car_number"]).setText(str)
                #     self.findChild(QPBtn, dict["car_number"]).setToolTip(tool_tip)
                #     self.findChild(QPBtn, dict["car_number"]).setStyleSheet('border:3px groove %s;border-radius:10px;padding:2px 4px;' % (
                #     "orange" if dict["type"] is 1 else "blue") + color)
                #     continue
                btn.setStyleSheet('border:3px groove %s;border-radius:10px;padding:2px 4px;' % (
                    "orange" if dict["type"] == 1 else "blue") + color)
                btn.setObjectName(dict["car_number"])
                btn.setMinimumHeight(80)
                font = QFont()
                font.setFamily('微软雅黑')
                font.setBold(True)
                font.setPointSize(15)
                font.setWeight(50)
                btn.setFont(font)  # 载入字体设置
                # btn.setGeometry(0, 0, 250, 500)  # （x坐标，y坐标，宽，高）
                btn.setText(str)
                btn.setToolTip(tool_tip)
                btn.clickedSignal.connect(self.process_btn_click)
                if dict["unit"] == 1:
                    self.ui.A_verticalLayout.addWidget(btn)
                elif dict["unit"] == 2:
                    self.ui.B_verticalLayout.addWidget(btn)
                elif dict["unit"] == 3:
                    self.ui.C_verticalLayout.addWidget(btn)

    def drawLed(self):
        export_1 = True
        export_2 = True

        export_3 = True
        export_4 = True

        export_5 = True
        export_6 = True
        out_mcpu_1_statu = message.out_mcpu_statu()
        out_mcpu_2_statu = message.out_mcpu_statu()
        out_mcpu_3_statu = message.out_mcpu_statu()
        out_mcpu_4_statu = message.out_mcpu_statu()
        out_mcpu_5_statu = message.out_mcpu_statu()
        out_mcpu_6_statu = message.out_mcpu_statu()
        if self.ui.out_rmq_1_statu_btn.toolTip() != "None":
            tf.Parse(self.ui.out_rmq_1_statu_btn.toolTip(), out_mcpu_1_statu)
            if out_mcpu_1_statu.outside_safety == 2:
                export_1 = False
        if self.ui.out_rmq_2_statu_btn.toolTip() != "None":
            tf.Parse(self.ui.out_rmq_2_statu_btn.toolTip(), out_mcpu_2_statu)
            if out_mcpu_2_statu.outside_safety == 2:
                export_2 = False
        if self.ui.out_rmq_3_statu_btn.toolTip() != "None":
            tf.Parse(self.ui.out_rmq_3_statu_btn.toolTip(), out_mcpu_3_statu)
            if out_mcpu_3_statu.outside_safety == 2:
                export_3 = False
        if self.ui.out_rmq_4_statu_btn.toolTip() != "None":
            tf.Parse(self.ui.out_rmq_4_statu_btn.toolTip(), out_mcpu_4_statu)
            if out_mcpu_4_statu.outside_safety == 2:
                export_4 = False
        if self.ui.out_rmq_5_statu_btn.toolTip() != "None":
            tf.Parse(self.ui.out_rmq_5_statu_btn.toolTip(), out_mcpu_5_statu)
            if out_mcpu_5_statu.outside_safety == 2:
                export_5 = False
        if self.ui.out_rmq_6_statu_btn.toolTip() != "None":
            tf.Parse(self.ui.out_rmq_6_statu_btn.toolTip(), out_mcpu_6_statu)
            if out_mcpu_6_statu.outside_safety == 2:
                export_6 = False
        if g_space.command_queue_dict is not False and g_space.command_queue_dict is not None:
            for dict in g_space.command_queue_dict:
                if dict["export_id"] == 1:
                    export_1 = False
                if dict["export_id"] == 2:
                    export_2 = False
                if dict["export_id"] == 3:
                    export_3 = False
                if dict["export_id"] == 4:
                    export_4 = False
                if dict["export_id"] == 5:
                    export_5 = False
                if dict["export_id"] == 6:
                    export_6 = False

        led = Led()
        led.setEnabled(False)  # 设置为不使能状态，如果需要切换可以设置为True。则可以实现点击切换指示灯颜色的效果
        led.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        if export_1 == export_2 == False:
            led.setChecked(False)  # 设置为选中状态
        else:
            led.setChecked(True)  # 设置为选中状态
        self.ui.led_process_Layout.addWidget(led, 0, 1)

        led = Led()
        led.setEnabled(False)  # 设置为不使能状态，如果需要切换可以设置为True。则可以实现点击切换指示灯颜色的效果
        led.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        if export_3 == export_4 == False:
            led.setChecked(False)  # 设置为选中状态
        else:
            led.setChecked(True)  # 设置为选中状态
        self.ui.led_process_Layout.addWidget(led, 0, 2)

        led = Led()
        led.setEnabled(False)  # 设置为不使能状态，如果需要切换可以设置为True。则可以实现点击切换指示灯颜色的效果
        led.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        if export_5 == export_6 == False:
            led.setChecked(False)  # 设置为选中状态
        else:
            led.setChecked(True)  # 设置为选中状态
        self.ui.led_process_Layout.addWidget(led, 0, 3)

    def drawRmqBtn(self, list):
        ex_name = list[0]
        key = list[1]
        id = ex_name + ":" + key
        btn = self.findChild(QPushButton, (key.replace("port", "btn")).replace("mcpu", "rmq"))
        if g_rabbitmq[id].statu is not None and g_rabbitmq[id].timeout() is False:
            btn.setToolTip(g_rabbitmq[id].statu)
            if key.find("in") >= 0:
                in_mcpu_statu = message.in_mcpu_statu()
                tf.Parse(g_rabbitmq[id].statu, in_mcpu_statu)
                if in_mcpu_statu.is_occupy == 1:
                    btn.setStyleSheet(self.getBackGroundColor("green"))
                    btn.setText(btn.text()[:9] + "空闲----" + btn.text()[15:])
                else:
                    btn.setStyleSheet(self.getBackGroundColor("yellow"))
                    btn.setText(btn.text()[:9] + "占用----" + btn.text()[15:])
                # print(btn.text())
                if in_mcpu_statu.door_statu == 2:
                    btn.setText(btn.text()[:-3] + "开到位")
                elif in_mcpu_statu.door_statu == 3:
                    btn.setText(btn.text()[:-3] + "关到位")
                elif in_mcpu_statu.door_statu == 4:
                    btn.setText(btn.text()[:-3] + "开关中")
                elif in_mcpu_statu.door_statu == 5:
                    btn.setText(btn.text()[:-3] + "门故障")

            elif btn.text().find("出口") >= 0:
                out_mcpu_statu = message.out_mcpu_statu()
                tf.Parse(g_rabbitmq[id].statu, out_mcpu_statu)
                if out_mcpu_statu.outside_safety == 1:
                    btn.setStyleSheet(self.getBackGroundColor("green"))
                    btn.setText(btn.text()[:9] + "空闲----" + btn.text()[15:])
                else:
                    btn.setStyleSheet(self.getBackGroundColor("yellow"))
                    btn.setText(btn.text()[:9] + "占用----" + btn.text()[15:])
                export_id = re.search('\d+', btn.objectName()).group()
                if g_space.command_queue_dict is not None:
                    for dict in g_space.command_queue_dict:
                        if dict["export_id"] == int(export_id):
                            btn.setStyleSheet(self.getBackGroundColor("yellow"))
                            btn.setText(btn.text()[:9] + "占用----" + btn.text()[15:])
                if out_mcpu_statu.door_statu == 2:
                    btn.setText(btn.text()[:-3] + "开到位")
                elif out_mcpu_statu.door_statu == 3:
                    btn.setText(btn.text()[:-3] + "关到位")
                elif out_mcpu_statu.door_statu == 4:
                    btn.setText(btn.text()[:-3] + "开关中")
                elif out_mcpu_statu.door_statu == 5:
                    btn.setText(btn.text()[:-3] + "门故障")


        else:
            btn.setToolTip("None")
            btn.setStyleSheet(self.getBackGroundColor("gray"))
            btn.setText(btn.text()[:9] + "断连")
    def mcpu_btn_click(self):
        sender = self.sender()
        mcpu_key_list = sender.objectName().split('_')
        menu = QMenu(self)
        action = menu.addAction('手动开门')
        action.triggered.connect(partial(self.manual_open_door, mcpu_key_list))
        action = menu.addAction('手动关门')
        action.triggered.connect(partial(self.manual_close_door, mcpu_key_list))
        action = menu.addAction('恢复半自动')
        action.triggered.connect(partial(self.automatic_door, mcpu_key_list))
        action = menu.addAction('恢复全自动')
        action.triggered.connect(partial(self.fully_automatic_door, mcpu_key_list))
        menu.exec_(QCursor.pos())

    def manual_open_door(self,mcpu_key_list):
        dispatch_direction = 0
        if mcpu_key_list[0] == 'in':
            dispatch_direction = 1
        elif mcpu_key_list[0] == 'out':
            dispatch_direction = 2
        msg = b'{ "TerminalID": %d, "DispatchDirection": %d, "ProcessControl": 2, "OutPutDo": { "Do0": 1, "Do1": 0, "Do2": 0, "Do3": 0, "Do4": 0, "Do5": 0, "Do6": 0, "Do7": 0 }}' % (
        int(mcpu_key_list[2]) - 1,dispatch_direction)
        key = mcpu_key_list[0]+":mcpu_"+mcpu_key_list[2]
        g_mcpu.publish(key,msg)
        QMessageBox.question(None, '提示', '指令发送成功！',
                             QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
    def manual_close_door(self,mcpu_key_list):
        dispatch_direction = 0
        if mcpu_key_list[0] == 'in':
            dispatch_direction = 1
        elif mcpu_key_list[0] == 'out':
            dispatch_direction = 2
        msg = b'{ "TerminalID": %d, "DispatchDirection": %d, "ProcessControl": 2, "OutPutDo": { "Do0": 0, "Do1": 1, "Do2": 0, "Do3": 0, "Do4": 0, "Do5": 0, "Do6": 0, "Do7": 0 }}' % (
            int(mcpu_key_list[2]) - 1, dispatch_direction)
        key = mcpu_key_list[0] + ":mcpu_" + mcpu_key_list[2]
        g_mcpu.publish(key, msg)
        QMessageBox.question(None, '提示', '指令发送成功！',
                             QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
    def automatic_door(self,mcpu_key_list):
        dispatch_direction = 0
        ProcessControl = 0
        if mcpu_key_list[0] == 'in':
            ProcessControl = 3
            dispatch_direction = 1
        elif mcpu_key_list[0] == 'out':
            ProcessControl = 4
            dispatch_direction = 2
        msg = b'{ "TerminalID": %d, "DispatchDirection": %d, "ProcessControl": %d, "OutPutDo": { "Do0": 0, "Do1": 0, "Do2": 0, "Do3": 0, "Do4": 0, "Do5": 0, "Do6": 0, "Do7": 0 }}' % (
            int(mcpu_key_list[2]) - 1, dispatch_direction,ProcessControl)
        key = mcpu_key_list[0] + ":mcpu_" + mcpu_key_list[2]
        g_mcpu.publish(key, msg)
        QMessageBox.question(None, '提示', '指令发送成功！',
                             QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
    def fully_automatic_door(self,mcpu_key_list):
        dispatch_direction = 0
        if mcpu_key_list[0] == 'in':
            dispatch_direction = 1
        elif mcpu_key_list[0] == 'out':
            dispatch_direction = 2
        msg = b'{ "TerminalID": %d, "DispatchDirection": %d, "ProcessControl": 1, "OutPutDo": { "Do0": 0, "Do1": 0, "Do2": 0, "Do3": 0, "Do4": 0, "Do5": 0, "Do6": 0, "Do7": 0 }}' % (
            int(mcpu_key_list[2]) - 1, dispatch_direction)
        key = mcpu_key_list[0] + ":mcpu_" + mcpu_key_list[2]
        g_mcpu.publish(key, msg)
        QMessageBox.question(None, '提示', '指令发送成功！',
                             QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
    def drawSpaceBtn(self, parkspace_dict, unit):

        for park, position in zip(parkspace_dict.values(), self.btn_positions):
            btn = QPBtn()
            str = "车位:%d\n楼层:%d" % ((park["id"] - 1) % 78 + 1, park["floor"])
            if park["statu"] == 1:
                btn.setStyleSheet("background-color:rgb(255,130,130)")
            elif park["statu"] == 0 and park["car_number"] is not None:
                btn.setStyleSheet("background-color:rgb(248,239,71)")
            btn.setGeometry(0, 0, 50, 50)
            btn.setText(str)
            tool_tip = '{"id":%d,\n"floor":%d,\n "subID":%d, \n"height":%f, \n"car_number":"%s" ,\n "unit":%d, \n"statu":%d}' % (
                park["id"], park["floor"], park["subID"], park["height"], park["car_number"], park["unit"],
                park["statu"])

            btn.setToolTip(tool_tip)
            btn.clickedSignal.connect(self.park_btn_click)
            if unit == 1:
                self.ui.A_gridLayout.addWidget(btn, *position)
            if unit == 2:
                self.ui.B_gridLayout.addWidget(btn, *position)
            if unit == 3:
                self.ui.C_gridLayout.addWidget(btn, *position)

    def process_btn_click(self, flag):
        if flag is False:
            sender = self.sender()
            tool_tip = sender.toolTip()
            dict = json.loads(tool_tip)
            menu = QMenu(self)
            action = menu.addAction('清除')
            action.triggered.connect(partial(self.process_delete, dict))
            menu.exec_(QCursor.pos())

    def park_btn_click(self, flag):
        if flag is False:
            sender = self.sender()
            tool_tip = sender.toolTip()
            dict = json.loads(tool_tip)
            menu = QMenu(self)
            action = menu.addAction('启用车位')
            action.triggered.connect(partial(self.btn_opeSpace, dict, 0))
            action = menu.addAction('停用车位')
            action.triggered.connect(partial(self.btn_disableSpace, dict, 1))
            action = menu.addAction('清除车位')
            action.triggered.connect(partial(self.btn_clearSpace, dict))
            action = menu.addAction('取出车辆')
            action.triggered.connect(partial(self.btn_pickUp, dict))

            menu.exec_(QCursor.pos())

    def btn_disableSpace(self, dict, statu):
        if g_space.statu is False:
            QMessageBox.warning(self, '警告', '数据库连接错误，请检查网络状态！',
                                QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
        else:
            g_space.updatePark(dict, statu)

    def btn_opeSpace(self, dict, statu):
        if g_space.statu is False:
            QMessageBox.warning(self, '错误', '数据库连接错误，请检查网络状态！',
                                QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
        else:
            g_space.updatePark(dict, statu)

    def btn_clearSpace(self, dict):
        if g_space.statu is False:
            QMessageBox.warning(self, '错误', '数据库连接错误，请检查网络状态！',
                                QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
        else:
            g_space.clearPark(dict)

    def btn_pickUp(self, dict):
        if g_space.statu is False:
            QMessageBox.warning(self, '错误', '数据库连接错误，请检查网络状态！',
                                QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
        else:
            g_space.pickUpPark(dict)

    def process_delete(self, dict):
        if g_space.statu is False:
            QMessageBox.warning(self, '错误', '数据库连接错误，请检查网络状态！',
                                QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
        else:
            g_space.processDelete(dict)

    def run(self):
        while self.isClose is not True:
            if g_space.statu is False:
                self.setWindowTitle("MainWindow---连接错误！")
                self.setEnabled(False)
            else:
                self.setWindowTitle("MainWindow---连接正常！")
                self.setEnabled(True)
            if g_space.isUpdate_A is True:
                self.drawSpaceBtnSignal.emit(g_space.a_unit_park_dict, 1)
                g_space.isUpdate_A = False
            if g_space.isUpdate_B is True:
                self.drawSpaceBtnSignal.emit(g_space.b_unit_park_dict, 2)
                g_space.isUpdate_B = False
            if g_space.isUpdate_C is True:
                self.drawSpaceBtnSignal.emit(g_space.c_unit_park_dict, 3)
                g_space.isUpdate_C = False

            for list in statu_ex_keys:
                ex_name = list[0]
                key = list[1]
                id = ex_name + ":" + key
                if (id in self.rmq_statu.keys()) is False or self.rmq_statu[id].statu != g_rabbitmq[id].statu or \
                        self.rmq_timeout[id] != g_rabbitmq[id].timeout():
                    self.rmq_timeout[id] = g_rabbitmq[id].timeout()
                    self.rmq_statu[id] = g_rabbitmq[id]
                    g_space.commandIsUpdate = True
                    self.drawRmqBtnSignal.emit(list)
                time.sleep(0.01)

            if g_space.commandIsUpdate is True:
                self.drawLedSignal.emit()
                self.drawUnitProcessSignal.emit()
                g_space.commandIsUpdate = False
            for key, statu in g_mcpu.GetAllMcpuConnectStatus().items():
                self.drawMcpuBtnSignal.emit(key)
                time.sleep(0.01)
            time.sleep(0.5)

    def closeEvent(self, event):
        results = QMessageBox.question(self, '退出', '你确定要退出吗?', QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.No)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
        if results == QMessageBox.Yes:
            g_rabbitmq.close()
            g_mcpu.McpuCommunicatorUnInit()
            g_space.close()
            self.isClose = True

            event.accept()  # 接受关闭事件

        else:
            event.ignore()  # 忽略关闭事件


g_rabbitmq = cmt.RabbitAsyncCommunicator(mq_ip, mq_port, mq_user, mq_password)
g_space = spmng.ParkManage(db_ip, db_port, db_name, db_user, db_password, g_rabbitmq)
g_mcpu = mcn.McpuCommunicator(mcpu_keys)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    g_space.start()
    g_rabbitmq.Init(None, statu_ex_keys)
    g_rabbitmq.start()
    g_mcpu.McpuCommunicatorInit()
    mainWindow = MainWindow()
    mainWindow.start()
    mainWindow.showMaximized()
    time.sleep(0.5)
    mainWindow.show()

    sys.exit(app.exec_())

    # 进入程序的主循环，并通过exit函数确保主循环安全结束(该释放资源的一定要释放)
