# -*- coding: utf-8 -*-
"""图 5-36　单代号网络图（教材 p114 计算题用图，按图意 Python 重绘）
要素：6 个工作节点 A(5)、B(3)、C(6)、D(6)、E(2)、F(4)。
节点为 3 行方格：第一行 [ES | 工期 | EF]，第二行 工作编号，第三行 [LS | 总时差 | LF]；
除工期与编号外均留空（题目要求填写）。连线：A→B、A→C、A→D、B→E、C→E、E→F、D→F。
"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, INK, NAV, ACC, save
from matplotlib.patches import Rectangle, FancyArrowPatch

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'assets', '图5-36-单代号网络图.png')

NODES = {           # 名称: (cx, cy, 工期)
    'A': (14, 55, 5), 'B': (40, 84, 3), 'C': (40, 52, 6),
    'D': (40, 20, 6), 'E': (67, 72, 2), 'F': (90, 44, 4),
}
EDGES = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'E'), ('C', 'E'), ('E', 'F'), ('D', 'F')]
W, H = 17.0, 14.0           # 节点宽高
RH = H / 3.0                # 每行高


def node(ax, name, cx, cy, dur):
    x0, y0 = cx - W / 2, cy - H / 2
    ax.add_patch(Rectangle((x0, y0), W, H, fill=True, fc='white', ec=INK, lw=1.5, zorder=3))
    # 横线
    for k in (1, 2):
        ax.plot([x0, x0 + W], [y0 + RH * k, y0 + RH * k], color=INK, lw=1.3, zorder=4)
    # 第一行竖线（ES | 工期 | EF）
    ax.plot([x0 + W / 3, x0 + W / 3], [y0 + 2 * RH, y0 + H], color=INK, lw=1.3, zorder=4)
    ax.plot([x0 + 2 * W / 3, x0 + 2 * W / 3], [y0 + 2 * RH, y0 + H], color=INK, lw=1.3, zorder=4)
    # 第三行竖线（LS | 总时差 | LF）
    ax.plot([x0 + W / 3, x0 + W / 3], [y0, y0 + RH], color=INK, lw=1.3, zorder=4)
    ax.plot([x0 + 2 * W / 3, x0 + 2 * W / 3], [y0, y0 + RH], color=INK, lw=1.3, zorder=4)
    ax.text(cx, y0 + 2.5 * RH, str(dur), ha='center', va='center', fontsize=13, color=INK, zorder=5)
    ax.text(cx, y0 + 1.5 * RH, name, ha='center', va='center', fontsize=14, color=INK, zorder=5)


def edge(ax, a, b):
    ax0, ay, _ = NODES[a]; bx, by, _ = NODES[b]
    # 起点：源节点右边缘；终点：目标节点左边缘
    p1 = (ax0 + W / 2, ay); p2 = (bx - W / 2, by)
    ar = FancyArrowPatch(p1, p2, arrowstyle='-|>', mutation_scale=16, lw=1.6,
                         color=INK, shrinkA=0, shrinkB=0, zorder=2)
    ax.add_patch(ar)


setup()
fig, ax = canvas(10.6, 5.6)
for n, (cx, cy, d) in NODES.items():
    node(ax, n, cx, cy, d)
for a, b in EDGES:
    edge(ax, a, b)
save(fig, OUT)
