# -*- coding: utf-8 -*-
"""图 5-5　引入提前量和滞后量（教材第 90 页）
结构（照照片实际连线）：
  开始 → A、开始 → B
  A --FS-2--> C；C → E、C → F；E → H、F → H；H → 结束
  B --SS+10--> D（连线绕到 B 下方再折上进入 D）；D → G；G → 结束
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, box, arrow, line, caption, save, NAV, ACC

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图5-5-引入提前量和滞后量.png')


def node(ax, cx, cy, w, h, text, fs=13, **kw):
    """按中心点放方框，返回 (左, 右, 上, 下, 中心x, 中心y)。"""
    box(ax, cx - w / 2, cy + h / 2, w, h, text, fs=fs, **kw)
    return cx - w / 2, cx + w / 2, cy + h / 2, cy - h / 2, cx, cy


def main():
    setup()
    fig, ax = canvas(12.0, 6.6, xlim=(0, 100), ylim=(0, 100))

    W, H = 9.2, 8.0          # 活动方框
    W2 = 11.6                # 开始／结束

    # ---------- 节点 ----------
    n_start = node(ax, 9.0, 56.0, W2, H, '开始', fs=12)
    n_A = node(ax, 26.5, 80.0, W, H, 'A')
    n_B = node(ax, 26.5, 40.0, W, H, 'B')
    n_C = node(ax, 47.5, 80.0, W, H, 'C')
    n_D = node(ax, 47.5, 40.0, W, H, 'D')
    n_E = node(ax, 68.5, 86.0, W, H, 'E')
    n_F = node(ax, 68.5, 30.0, W, H, 'F')
    n_H = node(ax, 88.0, 58.0, W, H, 'H')
    n_G = node(ax, 68.5, 13.0, W, H, 'G')
    n_end = node(ax, 93.5, 30.0, W2, H, '结束', fs=12)

    # ---------- 箭线 ----------
    # 开始 → A（斜向上）
    arrow(ax, (n_start[1], 58.5), (n_A[0] + 0.6, n_A[3] + 1.6))
    # 开始 → B（斜向下）
    arrow(ax, (n_start[1], 53.5), (n_B[0] + 0.6, n_B[2] - 1.8))

    # A --FS-2--> C
    arrow(ax, (n_A[1], n_A[5] + 0.6), (n_C[0], n_C[5] + 0.6))
    ax.text((n_A[1] + n_C[0]) / 2, n_A[5] + 4.6, 'FS-2', ha='center', va='center',
            color=NAV, fontsize=13, fontweight='bold')

    # C → E、C → F
    arrow(ax, (n_C[1], n_C[5] + 2.0), (n_E[0], n_E[3] + 2.2))
    arrow(ax, (n_C[1], n_C[5] - 2.0), (n_F[0], n_F[2] - 1.4))

    # E → H、F → H
    arrow(ax, (n_E[1], n_E[5] + 0.8), (n_H[0] + 0.4, n_H[2] - 1.6))
    arrow(ax, (n_F[1], n_F[5] + 1.4), (n_H[0] + 0.4, n_H[3] + 1.6))

    # B --SS+10--> D：连线绕到 B 下方，再折上进入 D 的左边（照原图）
    y_low, x_up = n_B[3] - 13.0, n_D[0] - 6.4
    line(ax, (n_B[4], n_B[3]), (n_B[4], y_low), color=ACC, lw=1.6)
    line(ax, (n_B[4], y_low), (x_up, y_low), color=ACC, lw=1.6)
    line(ax, (x_up, y_low), (x_up, n_D[5]), color=ACC, lw=1.6)
    arrow(ax, (x_up, n_D[5]), (n_D[0], n_D[5]))
    ax.text(x_up + 0.4, n_D[5] + 4.0, 'SS+10', ha='center',
            va='center', color=NAV, fontsize=13, fontweight='bold')

    # D → G
    arrow(ax, (n_D[1], n_D[5] - 1.6), (n_G[0] + 0.8, n_G[2] + 1.0))
    # G → 结束
    arrow(ax, (n_G[1], n_G[5] + 1.4), (n_end[0], n_end[3] + 1.6))
    # H → 结束
    arrow(ax, (n_H[4] - 0.8, n_H[3]), (n_end[4] - 0.4, n_end[2]))

    caption(ax, '图 5-5　引入提前量和滞后量', fs=11, y=1.0)
    save(fig, OUT)


if __name__ == '__main__':
    main()
