import os.path
import typing

from yangke.ebsilon.graphicsview import YkGraphicsItem, Port
from yangke.ebsilon.constant.constant import Pressure, Temperature, Enthalpy, MassFlow, Power, Length, Area, One, Other, \
    VolumeFlow, SpecificVolume
from yangke.performance.iapws97 import get_h_by_pt, IAPWS97
from yangke.common.QtImporter import QColor, QLineF, QPointF, Qt, QPoint, QPainter, QWidget, QStyleOptionGraphicsItem

SpecificationValues = {
    "控制器主属性": [
        ["计算设置", "FFU", ["1:ON", "2:SET", "3:OFF"], None],
        ["控制器特性", "FCHAR", ["1:正相关", "2:负相关"], None],
    ],
    "过程参数": [
        ["参数类型", "FL1SCV",
         ["1:压力", "2:温度", "3:焓", "4:质量流量", "5:功率/热流", "6:指定压力下的沸水焓", "7:指定压力下的饱和蒸汽焓"],
         None],
        ["被控制的工质", "FSUBST", "", None],
    ],
    "控制器输出": [
        ["控制参数类型", "FL2", ["1:压力", "2:温度", "3:焓", "4:质量流量", "5:功率/热流", "24:电压", "26:频率"]],
        ["L2MIN和L2MAX处理方法", "FLIM", ["1:不许越限", "2:超限后停止控制"], None],
        ["控制参数最小值", "L2MIN", "", {"func": "dynamic_unit(FL2)"}, ],
        ["控制参数最大值", "L2MAX", "", {"func": "dynamic_unit(FL2)"}, ],
        ["初始值来源", "FL2START", ["0:由L2START指定", "1:外部"]],
        ["初始值", "L2START", "", {"func": "dynamic_unit(FL2)"}],
    ],
    "目标值": [
        ["目标值来源", "FSCV", ["0:通过指定值", "2:通过核函数"], None],
        ["目标值", "SCV", "1", {"func": "dynamic_unit(FL2)"}],
    ]
}  # 不能有逗号
Result = {
    "Total": [
        ["目标值", "RSCV", "", {"func": "dynamic_unit(FL2)"}],
        ["实际值", "RACT", "", {"func": "dynamic_unit(FL2)"}],
    ]
}


class Item(YkGraphicsItem):
    def __init__(self):
        """

        """
        super(Item, self).__init__()
        self.width = 80
        self.height = 20
        self.EBS_ID = 39  # ebsilon软件中的组件id
        self.NAME = "控制器-内置目标"
        self.EBS_NAME = "Controller with internal target value"  # ebsilon中的组件名
        self.EBS_TYPE = "Controller"  # ebsilon帮助文件中组件所属的组
        # self.icon = QIcon(os.path.join(os.path.dirname(__file__), "Comp13.PNG"))  # 组件的图标

        # Ebsilon组件面板中的Ports页信息
        self.ports = {
            1: Port(idx=1, point=QPointF(-40, 0), type1="Signal Inlet", description="Signal Inlet"),
            2: Port(idx=2, point=QPointF(40, 0), type1="Signal Outlet", description="Signal Outlet")
        }
        self.SpecificationValues = SpecificationValues
        self.Result = Result

    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem,
              widget: typing.Optional[QWidget] = ...) -> None:
        """
        绘制组件图形

        :param painter:
        :param option:
        :param widget:
        :return:
        """
        # 绘制组件实体
        self.pen[0].setColor(Qt.yellow)
        painter.setPen(self.pen[0])
        painter.drawLine(QLineF(QPointF(-30, 0), QPointF(-40, 0)))
        self.pen[1].setColor(Qt.black)
        painter.setPen(self.pen[1])
        painter.drawLine(QLineF(QPointF(30, 0), QPointF(40, 0)))

        self.pen[2].setColor(Qt.black)
        self.pen[2].setWidth(1)
        painter.setPen(self.pen[2])
        self.brush[2].setColor(QColor('#800080'))
        painter.setBrush(self.brush[2])
        painter.drawPolygon([QPoint(-30, -10), QPoint(30, -10), QPoint(30, 10), QPoint(-30, 10)], Qt.OddEvenFill)  # 三角形
        super(Item, self).paint(painter, option, widget)  # 必须最后调用

    def calculate(self, step=0):
        DI = self.get("DI")
        if DI is None:
            area = self.get("A")
            if area is None:
                return f"未设置管道直径！---0"  # ---0表示立即退出计算循环

        p1 = self.get("P1")
        t1 = self.get("T1")
        h1 = self.get("H1")
        m1 = self.get("M1")
        p2 = self.get("P2")
        t2 = self.get("T2")
        h2 = self.get("H2")
        m2 = self.get("M2")
        if p1 is not None:  # 端口1的压力与端口2的压力相同
            self.set("P2", p1)
        elif p2 is not None:
            self.set("P1", p2)
        if t1 is not None:
            self.set("T2", t1)
        elif t2 is not None:
            self.set("T1", t2)
        if m1 is not None:
            self.set("M2", m1)
            self.set("M", m1)
        elif m2 is not None:
            self.set("M1", m2)
            self.set("M", m2)
        try:
            water = IAPWS97(T=t1, P=p1, H=h1)
            self.set("V", water.v)
            self.set("DP", self.get("P1") - self.get("P2"))

        except:
            return "not finished"

        return "done"


def 等值粗糙度(管道类型) -> float:
    """
    参考《GB 50764 电厂动力管道设计规范》表格C.0.2

    :param 管道类型:
    :return: 返回各类管子的等值粗糙度，单位为mm
    """
    epsilon = 0.2591
    if 管道类型 == '冷拔钢管':
        epsilon = 0.0015
    elif 管道类型 == "普通钢管/熟铁管":
        epsilon = 0.0457
    elif 管道类型 == "涂沥青铸铁管":
        epsilon = 0.1220
    elif 管道类型 == "镀锌铸铁管":
        epsilon = 0.1524
    elif 管道类型 == "其他":
        epsilon = None
    return epsilon
