import imp
from UI.DeviceDialogWidget import DeviceDialog
import sys
import re
import random
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QTimer
from PyQt5.Qt import *

from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, \
    QApplication, QLineEdit, QWidget, QTableWidget, QSplitter,QVBoxLayout,QPushButton, QProgressBar, QTableWidgetItem, QMessageBox
from PyQt5.QtWidgets import  QDialog, QListWidgetItem

from protocol.ModBus.DPV1Master import DPV1Master

class CustomProgressBar(QProgressBar):
    def text(self):
        # 获取当前值和最大值
        currentValue = self.value()
        maxValue = self.maximum()
        # 返回自定义的显示文本
        return f"正在加载{currentValue}/{maxValue}"


class SearchAddressWidget(QWidget):
    def __init__(self, deviceAddressEdit):
        super().__init__()
        self.selected_value = None
        self.deviceAddressEdit = deviceAddressEdit
        self.initUI()

    def initUI(self):
        self.resize(800, 500)
        self.setObjectName('deviceDialog')
        self.addressListWidget = QListWidget()
        self.addressListWidget.clicked.connect(self.onCellClicked)
        self.addressListWidget.doubleClicked.connect(lambda: self.onCellClicked(True))

        self.mainlayout = QVBoxLayout()

        self.progressBar = CustomProgressBar()
        self.progressBar.setMaximum(125)
        self.progressBar.setValue(0)

        self.bottomLayout = QHBoxLayout()

        self.confirmBtn = QPushButton('确定')
        self.confirmBtn.clicked.connect(self.onConfirm)

        self.cancelBtn  = QPushButton('取消')
        
        self.bottomLayout.addWidget(self.confirmBtn)
        self.bottomLayout.addWidget(QSplitter())
        self.bottomLayout.addWidget(self.cancelBtn)

        self.mainlayout.addWidget(self.progressBar)
        self.mainlayout.addWidget(self.addressListWidget)
        self.mainlayout.addLayout(self.bottomLayout)

        self.setLayout(self.mainlayout)
        self.setWindowTitle('从站地址查找')
        
        self.DPV1Master = DPV1Master('192.168.3.10', 502)
        self.DPV1Master.searchSlave(self.updateProgress)
        self.cancelBtn.clicked.connect(self.close)
        # self.timer = QTimer()
        # self.timer.timeout.connect(self.updateProgress)
        # self.timer.start(500)
      
    def updateProgress(self, address, isSlave):
         # 模拟一个任务，逐步更新进度条
        self.progressBar.setValue(address)
        if isSlave:
            self.addressListWidget.addItem(QListWidgetItem(str(address)))
    
    def onCellClicked(self, double = False):
        self.address = self.addressListWidget.currentItem().text()
        if double:
            self.onConfirm()

    def onConfirm(self):
        self.deviceAddressEdit.setText(self.address)
        self.close()
    
    def closeEvent(self, event):
        self.DPV1Master.closeThread()
        event.accept()