from PyQt5 import QtCore
from PyQt5.QtGui import QTextDocument
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QHeaderView, QAbstractItemView, QTableView, QWidget, QDesktopWidget
from UI.BlockParameterModel import VarTableModel, VarButtonDelegate

from utils.DBModels.DeviceParModels import *

class ParamsVHeader(QHeaderView):
    def __init__(self, parent, datas):
        super().__init__(Qt.Vertical, parent)
        self.datas = datas

        # print(1111)
    
    def resizeEvent(self, event):
        """Resize table as a whole, need this to enable resizing"""
        super(QHeaderView, self).resizeEvent(event)
        for index, content in enumerate(self.datas):
            self.setSectionResizeMode(index, QHeaderView.Fixed)
            height = 50 * (content[2].count('\r\n') + 1)
            # valueHeight = 50 * (content[5].count('\r\n') + 1)
            # height = desHeight if desHeight > valueHeight else valueHeight
            # print(height, index)
            if content[3] == 'DS-36':
                height = height if height > 5 * 50 else 250
                print(height)
                # self.resizeSection(index, height)
            if content[3] == 'DS-37':
                height = height if height > 4 * 50 else 200
            if content[3] == 'DS-39':
                height = height if height > 7 * 50 else 350
            if content[3] == 'DS-50':
                height = height if height > 4 * 50 else 200
                # self.resizeSection(index, height)
            self.resizeSection(index, height)
        return
    

class ParmView(QTableView):
    def __init__(self, dbModel = None, blcokIndex = None, blockType = None):
        super().__init__()
        self.dbModel = dbModel
        self.blcokIndex = blcokIndex
        self.blockType = blockType
        self.setHeader()
        self.setupUi()
        self.setData()

    def setHeader(self):
        self.setItemDelegateForColumn(6, VarButtonDelegate(self))
        # self.setItemDelegateForColumn(5, ComboBoxDelegate(self))
    
        self.model = VarTableModel(['索引', '参数名', '描述', '数据类型', '访问', '当前值', '输入值'], [], table = self)

    def setupUi(self):
        self.setShowGrid(True)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setObjectName('BlockView')
       
        #设置单元格宽度比例
        self.header = self.horizontalHeader()
        self.header.setSectionResizeMode(QHeaderView.Interactive)
        self.header.setStretchLastSection(True)

        self.proxy = QtCore.QSortFilterProxyModel(self)
        # # self.parameTableView.proxy = self.proxy
        self.proxy.setSourceModel(self.model)

        self.setModel(self.proxy)
        self.setCustomColumnWidths([1, 3, 8, 2, 2, 2, 3])


        # self.header.checkClicked.connect(self.model.headerClick)
        # self.setHorizontalHeader(self.header)
        # self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        # self.header.setSectionResizeMode(0, QHeaderView.Fixed)
        # self.header.resizeSection(0, 70)
    def setCustomColumnWidths(self, ratios):
        # 计算总比例
        totalRatio = sum(ratios)
        # 获取窗口宽度
        screen = QDesktopWidget().screenGeometry()
        width = screen.width() - 80

        # 根据比例设置每列的宽度
        for i, ratio in enumerate(ratios):
            columnWidth = int(width * (ratio / totalRatio))
            self.setColumnWidth(i, columnWidth)
    
    def setData(self):
            # self.datas = PressureTranslationBlock.getallParame()
        self.datas = self.dbModel.getallParame()
        for index, data in enumerate(self.datas):
            data[5] = ''
            desc = data[2].replace('\r\n', '').replace('\n', '')
            lines = [desc[i:i+40] + "\r\n" for i in range(0, len(desc), 40)]
            # 合并列表为一个字符串，移除最后一个换行符
            result = "".join(lines).rstrip("\r\n")
            data[2] = result
            data  = data + ['', '', '']
            self.model.append_data(data)
        self.resizeHeader()
        
    def resizeHeader(self):
        # print(self.verticalHeader())
        self.setVerticalHeader(ParamsVHeader(self, self.model.datas))
        # QtCore.QTimer.singleShot(0, self.verticalHeader().updateGeometry)





        

        