# -*- coding: utf-8 -*-
"""图 5-12　资源平衡
左：C(3) 之后 E(8)、F(7) 并行，二者汇入 H(6)（虚线框）；
粗黑箭头；
右：调整后 C(3)→E(8)→F(7)→H(6) 串行（虚线框）。
"""
import os
import sys

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

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

setup()

BW, BH = 10.0, 9.5          # 活动框宽高


def act(ax, cx, cy, name, dur, w=BW, h=BH):
    ax.add_patch(Rectangle((cx - w / 2, cy - h / 2), w, h,
                           facecolor=FILL, edgecolor=INK, lw=1.4, zorder=3))
    ax.text(cx, cy + h * 0.16, name, ha='center', va='center',
            fontsize=12, color=INK, zorder=4)
    ax.text(cx, cy - h * 0.22, str(dur), ha='center', va='center',
            fontsize=12, color=INK, zorder=4)


def dashed(ax, x0, y0, x1, y1):
    p = FancyBboxPatch((x0, y0), x1 - x0, y1 - y0,
                       boxstyle='round,pad=0,rounding_size=2.0',
                       fill=False, ec=INK, lw=1.3, linestyle=(0, (5, 3)), zorder=1)
    ax.add_patch(p)


fig, ax = canvas(w=11.4, h=6.6, xlim=(0, 114), ylim=(18, 82))

dashed(ax, 2, 23, 55, 77)
dashed(ax, 62, 23, 110, 77)

# ---- 左：并行网络 ----
C = (11.0, 50.0)
E = (30.0, 68.0)
F = (30.0, 32.0)
Hh = (46.0, 50.0)
act(ax, *C, 'C', 3)
act(ax, *E, 'E', 8)
act(ax, *F, 'F', 7)
act(ax, *Hh, 'H', 6)

arrow(ax, (C[0] + BW / 2, C[1] + 1.0), (E[0] - BW / 2, E[1] - BH / 2 + 1.0), color=INK, lw=1.4)
arrow(ax, (C[0] + BW / 2, C[1] - 1.0), (F[0] - BW / 2, F[1] + BH / 2 - 1.0), color=INK, lw=1.4)
arrow(ax, (E[0] + BW / 2, E[1] - BH / 2 + 1.5), (Hh[0] - BW / 2, Hh[1] + BH / 2 - 1.5), color=INK, lw=1.4)
arrow(ax, (F[0] + BW / 2, F[1] + BH / 2 - 1.5), (Hh[0] - BW / 2, Hh[1] - BH / 2 + 1.5), color=INK, lw=1.4)

# ---- 中间粗黑箭头 ----
ax.annotate('', xy=(61.0, 50), xytext=(56.0, 50),
            arrowprops=dict(arrowstyle='-|>', color=INK, lw=6,
                            mutation_scale=28, shrinkA=0, shrinkB=0))

# ---- 右：串行 ----
RW = 8.5
RC = (67.0, 50.0)
RE = (79.5, 50.0)
RF = (92.0, 50.0)
RH = (104.0, 50.0)
act(ax, *RC, 'C', 3, w=RW)
act(ax, *RE, 'E', 8, w=RW)
act(ax, *RF, 'F', 7, w=RW)
act(ax, *RH, 'H', 6, w=RW)

for a, b in ((RC, RE), (RE, RF), (RF, RH)):
    arrow(ax, (a[0] + RW / 2, a[1]), (b[0] - RW / 2, b[1]), color=INK, lw=1.4)

save(fig, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                       'assets', '图5-12-资源平衡.png'))
