# -*- coding: utf-8 -*-
"""图 5-7　项目进度网络图示例（教材第 95 页）

按照片重绘：开始→A(5)、开始→B(4)；A→C(3)；B→D(5)；C→E(8)、C→F(7)；
D→G(5)；E/F/G→H(6)；H→结束。活动节点内只标编号与工期，无 D→F 连线。
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, save  # noqa: E402
import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.patches import Rectangle  # noqa: E402

OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                   'assets', '图5-7-项目进度网络图示例.png')

W, H = 13.0, 12.0          # 活动节点尺寸


def act(ax, x, cy, name, dur):
    """活动节点：上排编号、下排工期（与教材一致）。"""
    y0 = cy - H / 2
    ax.add_patch(Rectangle((x, y0), W, H, facecolor='white', edgecolor='#1a365d', lw=1.5, zorder=3))
    ax.plot([x, x + W], [cy + 1.4, cy + 1.4], color='#1a365d', lw=1.0, zorder=4)
    ax.text(x + W / 2, cy + 3.1, name, ha='center', va='center', fontsize=13, color='#1a202c', zorder=5)
    ax.text(x + W / 2, cy - 3.0, str(dur), ha='center', va='center', fontsize=13, color='#1a202c', zorder=5)
    return dict(l=(x, cy), r=(x + W, cy), t=(x + W / 2, cy + H / 2), b=(x + W / 2, cy - H / 2),
                cx=x + W / 2, cy=cy)


def term(ax, x, cy, text, w=12.0, h=10.0):
    ax.add_patch(Rectangle((x, cy - h / 2), w, h, facecolor='white', edgecolor='#1a365d', lw=1.5, zorder=3))
    ax.text(x + w / 2, cy, text, ha='center', va='center', fontsize=13, color='#1a202c', zorder=5)
    return dict(l=(x, cy), r=(x + w, cy), cx=x + w / 2)


def arr(ax, p1, p2):
    ax.annotate('', xy=p2, xytext=p1, zorder=2,
                arrowprops=dict(arrowstyle='-|>', color='#2b6cb0', lw=1.5,
                                shrinkA=0, shrinkB=0, mutation_scale=16))


def main():
    setup()
    fig, ax = canvas(12.6, 9.4, xlim=(-2, 124), ylim=(3, 97))
    ax.set_aspect('equal')

    A = act(ax, 19, 72, 'A', 5)
    B = act(ax, 19, 28, 'B', 4)
    C = act(ax, 42, 72, 'C', 3)
    D = act(ax, 42, 28, 'D', 5)
    E = act(ax, 65, 87, 'E', 8)
    F = act(ax, 65, 50, 'F', 7)
    G = act(ax, 65, 13, 'G', 5)
    H = act(ax, 88, 50, 'H', 6)
    st = term(ax, 1, 50, '开始')
    en = term(ax, 109, 50, '结束')

    arr(ax, st['r'], (A['l'][0], A['cy'] - 3.0))
    arr(ax, st['r'], (B['l'][0], B['cy'] + 3.0))
    arr(ax, A['r'], C['l'])
    arr(ax, B['r'], D['l'])
    arr(ax, C['r'], (E['l'][0], E['cy'] - 4.0))
    arr(ax, C['r'], (F['l'][0], F['cy'] + 4.0))
    arr(ax, D['r'], (G['l'][0], G['cy'] + 4.0))
    arr(ax, (E['r'][0], E['cy'] - 4.0), (H['l'][0], H['cy'] + 4.0))
    arr(ax, F['r'], H['l'])
    arr(ax, (G['r'][0], G['cy'] + 4.0), (H['l'][0], H['cy'] - 4.0))
    arr(ax, H['r'], en['l'])

    save(fig, OUT)


if __name__ == '__main__':
    main()
