import json

from PyQt5.QtWidgets import  QMainWindow,  QDialog, QTabWidget, QPushButton, QSpacerItem, QSizePolicy\
                            ,QMessageBox, QHBoxLayout, QWidget, QTabBar, QProxyStyle, QStyle
from PyQt5.QtGui import  QIcon
from PyQt5.QtCore import QSize

from UI.DeviceDialogWidget import DeviceDialog

from model.ProjectModel.DeviceManage import DevicesManange
from utils.DBModels.BaseModel import *
from UI.AreaTabWidget import AreaTabWidget
from utils.DBModels.DeviceModels import DeviceDB
from model.ProjectModel.DeviceManage import DevicesManange


from PyQt5.QtWidgets import QApplication, QStyleOptionTab, QTabBar, QWidget
from PyQt5.QtGui import QPainter, QPen, QColor, QPainterPath, QPolygonF, QFontMetrics, QTextOption, QFont
from PyQt5.QtCore import Qt, QRectF, QPointF, QSizeF

class NewChromeTabStyle(QProxyStyle):
    def drawControl(self, element, option, painter, widget):
        # painter.save()
        # painter.setPen(Qt.red);
        # painter.restore();
        margin = 4
        if element == QStyle.CE_TabBarTabLabel:
            tab = option
            # print(type(tab))
            textRect = QRectF(self.subElementRect(QStyle.SE_TabBarTabText, tab, widget))
            painter.save()
            if (tab.state & QStyle.State_Selected):
                painter.setPen(QPen(QColor("black")))
            elif (tab.state & QStyle.State_MouseOver):
                painter.setPen(QPen(QColor("black")))
            else:
                painter.setPen(QPen(QColor("black")))
            option = QTextOption()
            # 设置对齐方式，Qt.AlignLeft 和 Qt.AlignVCenter 分别对应左对齐和垂直居中
            font = QFont();
            font.setPointSize(20);
            painter.setFont(font);

            option.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
            # 设置换行模式为不换行
            option.setWrapMode(QTextOption.NoWrap)
            painter.drawText(textRect, tab.text, option)
            painter.restore()


        elif element == QStyle.CE_TabBarTabShape:
            tab = option
            painter.setRenderHint(QPainter.Antialiasing);

            shapeRect = QRectF(tab.rect);
            shapeRect.setY(shapeRect.y() + margin)
            arcLen = shapeRect.height() / 2;

            if (tab.state & QStyle.State_Selected):
                painter.save();
                pen = QPen(Qt.white);
                pen.setWidthF(0.5);
                painter.setPen(pen);
                painter.restore();

                painter.save();
                shapeRect.setX(shapeRect.x() - arcLen);
                shapeRect.setWidth(shapeRect.width() + arcLen *3/ 5);

                path = QPainterPath();

                arcRect1 = QRectF(shapeRect.x(),
                                shapeRect.y() + shapeRect.height() / 3,
                                arcLen,
                                shapeRect.height() * 2 / 3);

                path.moveTo(QPointF(arcRect1.x(),
                                     arcRect1.y() + arcRect1.height()));

                path.lineTo(QPointF(arcRect1.x() + arcRect1.width() / 2,
                                     arcRect1.y() + arcRect1.height()));

                # // Starting from 270°, returning to the arc of 90°
                path.arcTo(arcRect1, 270.0, 90.0);

                path.lineTo(QPointF(arcRect1.x() + arcRect1.width(),
                                     arcRect1.y()));

                arcRect2 = QRectF(shapeRect.x() + arcRect1.width(),
                                shapeRect.y(),
                                arcLen,
                                shapeRect.height() * 2 / 3);

                # // Starting from 180°, returning to the arc of -90°
                path.arcTo(arcRect2, 180.0, -90.0);

                path.lineTo(QPointF(arcRect2.x() + shapeRect.width() -  2 * (arcRect2.x()  + arcRect2.width()) + arcRect2.width() / 2,
                                     arcRect2.y()));

                arcRect3 = QRectF(shapeRect.x() + shapeRect.width() - 2 * arcRect1.width(),
                                shapeRect.y(),
                                arcRect1.width(),
                                shapeRect.height() * 2 / 3);

                path.arcTo(arcRect3, 90.0, -90.0);

                path.lineTo(QPointF(arcRect3.x() + arcRect3.width(),
                                     arcRect3.y() + arcRect3.height()));

                arcRect4 = QRectF(arcRect3.x() + arcRect3.width(),
                                arcRect3.y() + arcRect3.height() / 2,
                                arcRect1.width(),
                                shapeRect.height() * 2 / 3);

                path.arcTo(arcRect4, 180.0, 90.0);

                path.lineTo(QPointF(arcRect1.x(),
                                    arcRect1.y() + arcRect1.height()));

                painter.setPen(Qt.NoPen);
                painter.setBrush(Qt.white);
                polygon = path.toFillPolygon();
                painter.drawPolygon(polygon);

                painter.setBrush(QColor('#D3E3FD'));
                magPoint = shapeRect.topLeft()
                magPoint.setY(magPoint.y() - margin)
                painter.drawRect(QRectF(magPoint, QSizeF(shapeRect.width(), margin)))

                painter.restore();
            elif (tab.state & QStyle.State_MouseOver):

                painter.save();
                # 设置画笔颜色和宽度
                painter.setBrush(QColor('#D3E3FD'));
                painter.setPen(Qt.NoPen)
                magPoint = shapeRect.topLeft()
                magPoint.setY(magPoint.y() - margin)
                painter.drawRect(QRectF(magPoint, QSizeF(shapeRect.width(), shapeRect.height() + 4)))

                shapeRect.setX(shapeRect.x());
                shapeRect.setWidth(shapeRect.width() - 15);
                shapeRect.setHeight(shapeRect.height() - 4)
                painter.setPen(QColor('#A8C7FA'))

                # 设置填充颜色（如果需要）
                painter.setBrush(QColor('#A8C7FA'))

                # 圆角矩形的参数：左上角坐标x, y，宽度w，高度h，以及圆角半径r
                radius = 5
                painter.drawRoundedRect(shapeRect, radius, radius)


                painter.restore();

            else:
                painter.save();

                shapeRect.setX(shapeRect.x() - arcLen);
                shapeRect.setWidth(shapeRect.width() + arcLen / 2);

                pen = QPen(QColor('#D3E3FD'));
                pen.setWidthF(0.1);
                painter.setPen(pen)
                painter.drawLine(shapeRect.bottomLeft(),shapeRect.bottomRight());
                # painter.drawLine(QPointF(shapeRect.x() + arcLen*2/3 -1, shapeRect.height() / 3),
                #               QPointF(shapeRect.x() + arcLen*2/3 -1, shapeRect.height() * 2 / 3));
                painter.setBrush(QColor('#D3E3FD'));
                painter.drawRect(shapeRect)

                magPoint = shapeRect.topLeft()
                magPoint.setY(magPoint.y() - margin)
                painter.drawRect(QRectF(magPoint, QSizeF(shapeRect.width(), margin)))
                painter.restore();

                # painter.save();
                # painter.restore();

 
        else:
            super(NewChromeTabStyle, self).drawControl(element, option, painter, widget);



class DeviceTabBar(QTabBar):
    def __init__(self):
        super().__init__()
        self.setStyle(NewChromeTabStyle())

    def tabSizeHint(self, index):
        newSize = QTabBar().tabSizeHint(index)
        width = len(self.tabText(index)) * 20 + 100

        newSize.setWidth(width)
        newSize.setHeight(35)

        # tabRect = QTabBar().tabRect(index)
        # padding = 50
        # tabRect.adjust(padding, padding, padding, padding)

        return newSize


class DeviceTab(QTabWidget):
    def __init__(self, dockWidget, devicesManange):
        super().__init__()
        self.dockWidget = dockWidget
        self.devicesManange = devicesManange
        self.setObjectName('deviceWidget')
        self.initUI()
        
    
    def initUI(self):
        # self.tabBar = DeviceTabBar()
        self.setTabBar(DeviceTabBar())
        #获取DP、PA协议和主从模式
        self.dataTypeAndModel = self.dockWidget.windowTitle()
        self.proType = self.dataTypeAndModel[0:2]
        self.masterSlaveModel = self.dataTypeAndModel[2:4]

        self.setObjectName('deviceTabWidget')

        self.addDeviceButton = QPushButton('添加设备')
        self.addDeviceButton.setObjectName('deviceAddButton')
        self.addDeviceButton.setIcon(QIcon('Static/add.png'))
        self.addDeviceButton.setFlat(True)
        self.addDeviceButton.clicked.connect(self.addDeviceWidget)

        self.setCornerWidget(self.addDeviceButton)
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.closeTab)
        self.state = True
        self.initWidget()
    

    def closeTab(self, index):
        reply = QMessageBox.question(self, 'Confirmation', '确定删掉此设备吗?',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            if index != -1:
                deviceName = self.tabText(index) + self.dockWidget.windowTitle()
                # print(deviceName,index,222)
                self.removeTab(index)
            self.devicesManange.delDevice(deviceName = deviceName )
            DeviceDB.deleteDevice(deviceName = deviceName)  
        else:
            return
        if self.count() == 0:
            self.creatInitWidget()
       
        

    def addDeviceWidget(self,init = False,deviceName = None):
        if deviceName is None:
            dialog = DeviceDialog(self.dataTypeAndModel)
            if dialog.exec_() == QDialog.Accepted:
                self.deviceName, pvUpperLimit, pvLowerLimit, pvUnit = dialog.getParameters()            
                DeviceDB().addDevice(deviceName = self.deviceName, proType = self.proType , masterSlaveModel = self.masterSlaveModel, pvUpperLimit=pvUpperLimit, pvLowerLimit=pvLowerLimit, pvUnit=pvUnit)
                if init:
                    self.removeTab(0)
                tabIndex = self.count()
                self.tabBar().setHidden(False)
                self.addTab(AreaTabWidget(self),str(self.deviceName[:-4]))
                self.setCurrentIndex(tabIndex)
                self.devicesManange.addDevice(proType=self.proType, masterSlaveModel = self.masterSlaveModel, deviceName = self.deviceName)
            else:
                return
        else:
            self.deviceName = deviceName
            self.titleName = self.deviceName[:-4]
            self.tabBar().setHidden(False)
            self.addTab(AreaTabWidget(self),str(self.titleName))
            
            

    def initWidget(self):
        alldevices = DevicesManange.getAllDevice()
        titleName = self.dockWidget.windowTitle()
        if alldevices:
            for devices in alldevices:
                deviceName = devices[0]
                
                if titleName in deviceName:
                    # print(devices,333)
                    self.devicesManange.addDevice(proType = devices[1], masterSlaveModel = devices[2], deviceName = devices[0]) 
                    self.addDeviceWidget(deviceName=deviceName) 
                    self.state = False
        if self.state:
            self.creatInitWidget()
            
    def creatInitWidget(self):
        widget = QWidget()
        widget.setObjectName('initWidget')
        layout = QHBoxLayout()
        addButton = QPushButton('添加设备')
        addButton.setObjectName('initAddDeviceButton')
        icon = QIcon('Static/add.png')
        iconSize = QSize(50,50)
        addButton.setIcon(icon)
        addButton.setIconSize(iconSize)
        addButton.clicked.connect(lambda: self.addDeviceWidget(True))
        layout.addWidget(QWidget())
        layout.addWidget(addButton)
        layout.addWidget(QWidget())
        widget.setLayout(layout)
        self.addTab(widget,'')
        self.tabBar().setHidden(True)


          
                    
                       
                    
    


    



