# -*- coding: utf-8 -*-
"""图 5-3　采用箭线图法（双代号网络图）绘制的项目进度网络图
教材第 89 页。节点为带编号的圆圈（事件 1–8），箭线为活动 A–H：
A:1→2、B:1→3、C:2→4、D:3→5、E:4→6、F:4→7、G:5→8、H:7→8，
另有一条 6⇢7 的虚箭线（虚线，无活动代号）。
"""
import os
import sys
import math
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, arrow, save
from matplotlib.patches import Circle

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

R = 4.3
NODES = {1: (10, 48), 2: (30, 74), 3: (30, 24), 4: (51, 74),
         5: (51, 24), 6: (73, 90), 7: (73, 52), 8: (92, 40)}

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=13, color='#1a365d', zorder=4)

INK = '#2b6cb0'

def edge(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.5, 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')

edge(1, 2, 'A', lx=-4.2, ly=1.0)
edge(1, 3, 'B', lx=-3.6, ly=-3.4)
edge(2, 4, 'C', ly=4.2)
edge(3, 5, 'D', ly=4.2)
edge(4, 6, 'E', lx=-3.6, ly=4.2)
edge(4, 7, 'F', lx=3.2, ly=3.4)
edge(6, 7, None, dashed=True)          # 虚活动（虚线）
edge(5, 8, 'G', ly=-4.2)
edge(7, 8, 'H', lx=2.4, ly=4.0)


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-3-采用箭线图法的项目进度网络图.png')
save(fig, os.path.abspath(out))
trim(os.path.abspath(out))
