# -*- coding: utf-8 -*-
"""图 5-11　反向计算法 2
节点为 3 行 3 列格子：上行 ES/工期/EF，中间行活动名（横跨整宽），下行 LS/总浮动时间/LF。
数值逐个照教材第 98 页照片录入。
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from _draw import setup, canvas, arrow, save, INK, NAV, FILL, LINE
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

setup()

W, H = 11.8, 10.6          # 节点宽高（相对单位，1 单位 ≈ 0.12 in）
NUM_FS, NAME_FS = 11, 11.5

# name: (cx, cy, 上行三值, 下行三值)
NODES = {
    'A': (10.0, 63.0, ('0', '5', '5'), ('0', '0', '5')),
    'B': (10.0, 40.0, ('0', '4', '4'), ('2', '2', '6')),
    'C': (27.0, 63.0, ('5', '3', '8'), ('5', '0', '8')),
    'D': (27.0, 41.0, ('4', '5', '9'), ('6', '2', '11')),
    'E': (46.0, 73.0, ('8', '8', '16'), ('8', '0', '16')),
    'F': (46.0, 59.0, ('8', '7', '15'), ('9', '1', '16')),
    'G': (45.0, 41.5, ('9', '5', '14'), ('11', '2', '16')),
    'H': (66.0, 60.0, ('16', '6', '22'), ('16', '0', '22')),
}

EDGES = [('A', 'C'), ('B', 'D'), ('C', 'E'), ('C', 'F'),
         ('D', 'G'), ('E', 'H'), ('F', 'H'), ('G', 'H')]


def node(ax, name, cx, cy, top, bot):
    x0, y0 = cx - W / 2, cy - H / 2
    ax.add_patch(Rectangle((x0, y0), W, H, fill=False, ec=INK, lw=1.3, zorder=3))
    rh = H / 3.0
    # 行分隔线
    ax.plot([x0, x0 + W], [y0 + rh, y0 + rh], color=INK, lw=1.1, zorder=3)
    ax.plot([x0, x0 + W], [y0 + 2 * rh, y0 + 2 * rh], color=INK, lw=1.1, zorder=3)
    # 上下两行的列分隔线
    for k in (1, 2):
        vx = x0 + W * k / 3.0
        ax.plot([vx, vx], [y0, y0 + rh], color=INK, lw=1.1, zorder=3)
        ax.plot([vx, vx], [y0 + 2 * rh, y0 + H], color=INK, lw=1.1, zorder=3)
    # 数字
    for i in range(3):
        tx = x0 + W * (i + 0.5) / 3.0
        ax.text(tx, y0 + 2.5 * rh, top[i], ha='center', va='center',
                fontsize=NUM_FS, color=INK, zorder=4)
        ax.text(tx, y0 + 0.5 * rh, bot[i], ha='center', va='center',
                fontsize=NUM_FS, color=INK, zorder=4)
    # 活动名
    ax.text(cx, y0 + 1.5 * rh, name, ha='center', va='center',
            fontsize=NAME_FS, color=INK, zorder=4)


def anchor(cx, cy, tx, ty, w=W, h=H):
    """求从节点中心指向目标时与节点边框的交点。"""
    dx, dy = tx - cx, ty - cy
    if dx == 0 and dy == 0:
        return cx, cy
    sx = (w / 2.0) / abs(dx) if dx else float('inf')
    sy = (h / 2.0) / abs(dy) if dy else float('inf')
    s = min(sx, sy)
    return cx + dx * s, cy + dy * s


fig, ax = canvas(w=8.9, h=5.8, xlim=(0, 74), ylim=(33.5, 80.0))

for src, dst in EDGES:
    sx, sy = NODES[src][0], NODES[src][1]
    dx, dy = NODES[dst][0], NODES[dst][1]
    p1 = anchor(sx, sy, dx, dy)
    p2 = anchor(dx, dy, sx, sy)
    # 两端各留一点缝，箭头不压框线
    arrow(ax, p1, p2, color=INK, lw=1.4)

for name, (cx, cy, top, bot) in NODES.items():
    node(ax, name, cx, cy, top, bot)

save(fig, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                       'assets', '图5-11-反向计算法2.png'))
