import threading
import time

from PyQt5.QtWidgets import QMessageBox
import pymysql
import google.protobuf.text_format as tf
import message.message_pb2 as msg


class ParkManage(threading.Thread):
    def __init__(self, ip, port, database, user, password, sender):
        threading.Thread.__init__(self)
        self.conn = None
        self.ip = ip
        self.port = port
        self.database = database
        self.user = user
        self.password = password
        self.lock = threading.Lock()
        self.command_queue_dict = None
        self.commandIsUpdate = False

        self.a_unit_park_dict = {}
        self.b_unit_park_dict = {}
        self.c_unit_park_dict = {}
        self.isClose = False
        self.statu = False
        self.isUpdate_A = False
        self.isUpdate_B = False
        self.isUpdate_C = False
        self.g_sender = sender

    def connect(self):
        try:
            self.conn = pymysql.connect(host=self.ip, port=self.port, database=self.database, charset="utf8",
                                        user=self.user, passwd=self.password)
            return True
        except:
            return False

    def updatePark(self, dict, statu):
        self.lock.acquire()
        cursor = self.conn.cursor()
        SQL = "update space set statu=%d where id=%d" % (statu, dict["id"])
        cursor.execute(SQL)
        print(SQL)
        self.conn.commit()
        cursor.close()
        self.lock.release()

    def clearPark(self, dict):
        self.lock.acquire()
        cursor = self.conn.cursor()
        SQL = "update space set car_number=NULL where id=%d" % (dict["id"])
        cursor.execute(SQL)
        print(SQL)
        self.conn.commit()
        cursor.close()
        self.lock.release()
    def processDelete(self, dict):
        self.lock.acquire()
        cursor = self.conn.cursor()
        SQL = "delete from command_queue where car_number='%s';" % (dict["car_number"])
        cursor.execute(SQL)
        print(SQL)
        self.conn.commit()
        cursor.close()
        self.lock.release()

    def pickUpPark(self, dict):
        with self.lock:
            cursor = self.conn.cursor()
            SQL = "select primary_key from vehicle where car_number='%s'" % (dict["car_number"])
            cursor.execute(SQL)
            self.conn.commit()
            results = cursor.fetchall()
            if len(results) == 1:
                key = ''.join(results[0])
                table = msg.pick_table()
                table.primary_key = key
                self.g_sender.publish("command_ex", "user_command_port", tf.MessageToString(table, as_utf8=True))
                QMessageBox.question(None, '提示', '取车消息发送成功！',
                                     QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容

            else:
                QMessageBox.warning(None, '警告', '查询结果有误,请检查数据库！',
                                    QMessageBox.Ok)  # "退出"代表的是弹出框的标题,"你确认退出.."表示弹出框的内容
            cursor.close()
    def close(self):
        self.isClose = True
    def run(self):
        while self.isClose is not True:
            try:
                self.conn.ping()  # 采用连接对象的ping()函数检测连接状态
                # print('connect MySql-OK   statu=' + str(self.statu))
                self.statu = True
            except:
                self.statu = False
                # print('connect MySql-ERROR  statu=' + str(self.statu))
                self.connect()
                time.sleep(0.5)
                continue
            with self.lock:
                # 获取一个光标
                cursor = self.conn.cursor()
                SQL = "select * from space"
                t_a_unit_park_dict = {}
                t_b_unit_park_dict = {}
                t_c_unit_park_dict = {}
                results = cursor.execute(SQL)
                self.conn.commit()
                # 结果数量大于0
                if results > 0:
                    parkspace = cursor.fetchall()
                    column = [index[0] for index in cursor.description]  # 列名
                    for row, i in zip(parkspace, range(results)):
                        if row[5] == 1:
                            t_a_unit_park_dict[i % 78] = dict(zip(column, row))
                        if row[5] == 2:
                            t_b_unit_park_dict[i % 78] = dict(zip(column, row))
                        if row[5] == 3:
                            t_c_unit_park_dict[i % 78] = dict(zip(column, row))

                if self.a_unit_park_dict != t_a_unit_park_dict:
                    self.a_unit_park_dict = t_a_unit_park_dict
                    self.isUpdate_A = True
                elif self.b_unit_park_dict != t_b_unit_park_dict:
                    self.b_unit_park_dict = t_b_unit_park_dict
                    self.isUpdate_B = True
                elif self.c_unit_park_dict != t_c_unit_park_dict:
                    self.c_unit_park_dict = t_c_unit_park_dict
                    self.isUpdate_C = True
                # SQL = "select * from command_queue where type =2 and (statu=1 or statu=2)"
                SQL = "select * from command_queue"
                t_command_dict = {}
                results = cursor.execute(SQL)
                self.conn.commit()
                if results > 0:
                    command_queue = cursor.fetchall()
                    column = [index[0] for index in cursor.description]  # 列名
                    t_command_dict = [dict(zip(column, row)) for row in command_queue]  # row是数据库返回的一条一条记录，其中的每一天和column写成字典，最后就是字典数组
                if self.command_queue_dict != t_command_dict:
                    self.command_queue_dict = t_command_dict
                    self.commandIsUpdate = True

                # 关闭光标
                cursor.close()
                # print("------------------------------")
            time.sleep(0.5)
