import os.path
import typing

from yangke.ebsilon.graphicsview import YkGraphicsItem, Port
from yangke.ebsilon.constant.constant import Pressure, Temperature, Enthalpy, MassFlow, Power
from yangke.ebsilon.values import Value
from yangke.performance.iapws97 import get_h_by_pt
from yangke.common.QtImporter import QRectF, QLineF, QPointF, Qt, QPoint, QPainter, QWidget, QStyleOptionGraphicsItem, \
    QIcon

SpecificationValues = {
    "流体状态参数(总，滞止)": [
        ["压力", "P", "", Pressure("MPa"), "tacit"],

    ],
}

Results = {
    "Total": [
        ["压力", "P", "", Pressure("MPa"), "disabled"],
        ["温度", "T", "", Temperature("℃"), "disabled"],
        ["焓", "H", "", Enthalpy("kJ/kg"), "disabled"],
    ]
}


class Item(YkGraphicsItem):
    """
    ebsilon的4号组件，基于质量流量的分流器
    """

    def __init__(self):
        super(Item, self).__init__()
        self.width = 40
        self.height = 40
        self.EBS_ID = 10037  # ebsilon软件中的组件id
        self.NAME = "混合器DLT 5054"
        self.EBS_NAME = "Simple Mixer"  # ebsilon中的组件名
        self.EBS_TYPE = "Mixer"  # ebsilon帮助文件中组件所属的组

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

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

        :param painter:
        :param option:
        :param widget:
        :return:
        """
        # 绘制组件实体
        self.pen[0].setColor(Qt.red)
        self.pen[0].setWidth(4)
        painter.setPen(self.pen[0])
        painter.drawLine(QLineF(QPointF(-20, 0), QPointF(20, 0)))
        painter.drawLine(QLineF(QPointF(0, 0), QPointF(0, 20)))

        self.pen[1].setColor(Qt.black)
        self.pen[1].setWidth(1)

        painter.setPen(self.pen[1])
        self.brush[1].setColor(Qt.yellow)
        painter.setBrush(self.brush[1])
        # painter.drawPolygon([QPoint(-30, -10), QPoint(30, -10), QPoint(30, 10), QPoint(-30, 10)], Qt.OddEvenFill)  # 三角形
        painter.drawEllipse(-10, -10, 20, 20)

        super(Item, self).paint(painter, option, widget)  # 必须最后调用

    def make_equal(self, symbol_des, from_symbols: list, step):
        """
        使参数symbol_des的值从from_symbols中给出的值中获得，例如：
        self.make_equal("P", ["P1", "P2", "P3"])
        则当"P1", "P2", "P3"任何一个数非空时，P将获得其值
        """
        for s in from_symbols:
            _ = self.get(s, need_unit=True)
            if _ is not None and _.value is not None and str(_.value).strip() != "":
                self.values.update({symbol_des: _}, step=step, set_none=False)

    def calculate(self, step=0):
        """
        P2 = P1
        P3 = P1
        T2 = T1
        T3 = T1
        H2 = H1
        H3 = H1
        M2 = M1 - M3
        NCV2 = NCV1 (NCV=[lower]calorific value)
        NCV3 = NCV1
        """
        if self.values.values_steps.get(step) is None:  # 无论计算是否成功，组件上当前时间步的值都要初始化
            self.values.values_steps[step] = {}
            self.values.values = {}

        P1 = self.get("P1", need_unit=True)
        P2 = self.get("P1", need_unit=True)
        P3 = self.get("P1", need_unit=True)

        M1 = self.get("M1", need_unit=True)
        M2 = self.get("M2", need_unit=True)
        M3 = self.get("M3", need_unit=True)

        if P1 is not None and P2 is not None:
            if abs(P1 - P2) < 0.00000001:
                result = "done"
            elif P1 < P2:
                # 设置m_if1 更小一些
                self.scene().flag_item.adjust_step_value
                # m_if1 = m_if1['last_step']

        return "done"

    def spread_values(self, step=None, symbols=None):
        """
        只将组件上的symbols中的参数传递到其所有端口，而质量流量因为三个端口不相同，所以不能传递
        """
        super().spread_values(step, symbols=["P", "T", "H", "NCV"])
