from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem
from processing.tools.PostgreSQL.PostgreSQL import PostgreSQL


class Tree:
    type = ""
    def __init__(
            self,
            type: str
    ):
        self.type = type


    def createTree(self,data, parent, parentid):
        if parentid is not None:
            for row in data:
                if row[2] == parentid:
                    item = QTreeWidgetItem(parent)
                    item.setText(0, row[1])
                    item.setText(1, row[0])
                    self.createTree(data, item, row[0])
        else:
            for row in data:
                item = QTreeWidgetItem(parent)
                item.setText(0, row[1])
                item.setText(1, row[0])
                self.createTree(data, item, row[0])


    def initTreeWidget(self):
        tree = QTreeWidget()
        tree.setColumnCount(2)
        tree.setColumnHidden(1, True)  # 隐藏路径列
        tree.setObjectName(self.type)
        tree.setHeaderLabels({"标识码", "名称"})
        tree.headerItem().setHidden(True)
        pg = PostgreSQL(schema="base")
        if self.type == "zyml":
            treedata = pg.getZyml()
            self.createTree(treedata, tree, "")
        elif self.type == "xzqh":
            treedata = pg.getXzqh()
            self.createTree(treedata, tree, "")
        # print(treedata)
        pg.close()
        __sortingEnabled = tree.isSortingEnabled()
        tree.setSortingEnabled(True)
        tree.setSortingEnabled(__sortingEnabled)
        return tree
