# -*- coding: utf-8 -*-
"""图 5-4　在箭线图中引入虚活动
教材第 90 页顶端（第 89 页正文引用其 (a)(b) 两图）。
(a) 单代号示意：开始 → E、开始 → F，E → H、F → H（E、F 共用同一紧前/紧后事件，出现歧义）；
(b) 箭线图消歧：事件 1 →E→ 2、1 →F→ 3，再由 2 ⇢ 3 加一条虚箭线（虚线），3 →H→ 4，
    从而表达「E、F 同时进行，两者都完成后 H 才能开始」。
"""
import os
import sys
import math
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, box, arrow, save
from matplotlib.patches import Circle

setup()
fig, ax = canvas(11.0, 11.0, (0, 100), (0, 100))

# ---------------- (a)：单代号（节点即活动） ----------------
SP = dict(l=3.0, t=64.0, w=13.0, h=9.0)     # 开始：中心 (9.5, 59.5)
EP = dict(l=24.0, t=84.0, w=10.0, h=8.0)    # E：中心 (29.0, 80.0)
FP = dict(l=24.0, t=54.0, w=10.0, h=8.0)    # F：中心 (29.0, 50.0)
HP = dict(l=40.0, t=70.0, w=10.0, h=8.0)    # H：中心 (45.0, 66.0)
for p, txt in ((SP, '开始'), (EP, 'E'), (FP, 'F'), (HP, 'H')):
    box(ax, p['l'], p['t'], p['w'], p['h'], txt, fs=15 if len(txt) == 1 else 13,
        radius=0.4, lw=1.3)

def ctr(p):
    return (p['l'] + p['w'] / 2, p['t'] - p['h'] / 2)

sx, sy = ctr(SP)[0] + SP['w'] / 2, ctr(SP)[1]        # 开始右缘中点
arrow(ax, (sx, sy), (EP['l'], ctr(EP)[1]), lw=1.4)   # 开始 → E
arrow(ax, (sx, sy), (FP['l'], ctr(FP)[1]), lw=1.4)   # 开始 → F
arrow(ax, (EP['l'] + EP['w'], ctr(EP)[1]), (HP['l'], ctr(HP)[1] + 3.0), lw=1.4)   # E → H
arrow(ax, (FP['l'] + FP['w'], ctr(FP)[1]), (HP['l'], ctr(HP)[1] - 3.0), lw=1.4)   # F → H
ax.text(28.0, 39.0, '(a)', ha='center', va='center', fontsize=13, color='#1a365d')

# ---------------- (b)：双代号（节点为事件，箭线为活动） ----------------
R = 4.0
NODES = {1: (58.0, 54.0), 2: (78.0, 78.0), 3: (78.0, 30.0), 4: (93.0, 18.0)}
for n, (x, y) in NODES.items():
    ax.add_patch(Circle((x, y), R, facecolor='white', edgecolor='#1a365d', lw=1.5, zorder=3))
    ax.text(x, y, str(n), ha='center', va='center', fontsize=12, color='#1a365d', zorder=4)

INK = '#2b6cb0'
def pedge(a, b, label=None, lx=0.0, ly=0.0, dashed=False):
    (x1, y1), (x2, y2) = NODES[a], NODES[b]
    d = math.hypot(x2 - x1, y2 - y1)
    ux, uy = (x2 - x1) / d, (y2 - y1) / d
    p1 = (x1 + ux * R, y1 + uy * R)
    p2 = (x2 - ux * R, y2 - uy * R)
    arrow(ax, p1, p2, color=INK, lw=1.4, ls='--' if dashed else '-')
    if label:
        mx, my = (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2
        ax.text(mx + lx, my + ly, label, ha='center', va='center',
                fontsize=13, color='#1a365d')

pedge(1, 2, 'E', lx=0.4, ly=-3.8)      # 1 →E→ 2（标签在线右侧下）
pedge(1, 3, 'F', lx=0.4, ly=3.8)       # 1 →F→ 3（标签在线右侧上）
pedge(2, 3, None, dashed=True)         # 2 ⇢ 3 虚箭线
pedge(3, 4, 'H', lx=3.0, ly=3.6)       # 3 →H→ 4
ax.text(72.0, 10.0, '(b)', ha='center', va='center', fontsize=13, color='#1a365d')


def trim(path, pad=38):
    """裁掉四周多余白底，只留 pad 像素边距（保证 _check_figs 的贴边判定通过）。"""
    from PIL import Image, ImageChops
    im = Image.open(path).convert('RGB')
    bg = Image.new('RGB', im.size, (255, 255, 255))
    bb = ImageChops.difference(im, bg).getbbox()
    if bb:
        im.crop((max(0, bb[0] - pad), max(0, bb[1] - pad),
                 min(im.width, bb[2] + pad), min(im.height, bb[3] + pad))).save(path)
        print(f'   ↳ 已裁掉多余留白（保留 {pad}px 边距）→', Image.open(path).size)


out = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图5-4-箭线图中引入虚活动.png')
save(fig, os.path.abspath(out))
trim(os.path.abspath(out))
