# -*- coding: utf-8 -*-
"""图 7-10　配置项类及实例 —— 教材第 166 页（7.5.1 配置项识别）

按「图内要素」还原：类—实例一对多的层级树，无坐标轴。
① 顶层「需求规格」矩形框（上部偏左）；
② 框底中点引竖主干向下，与水平母线相交成 T 形分叉；
③ 水平母线左右延伸，横贯三个子框跨度；
④⑤⑥ 左端下折 → 需求规格V1.1，主干直下 → 需求规格V1.2，右端下折 → 需求规格V1.3；
⑦ 三个子框同尺寸、同高度、等距；
⑧ 两个圆形标注框（白底细实线圆，无箭头、仅引线）：
   「配置项类」→ 父框右侧边；「配置项实例」→ V1.3 右上角；
⑨ 图题在图形下方居中。
"""
import os
import sys

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

from matplotlib.patches import Ellipse

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图7-10-配置项类及实例.png')

FIG_W, FIG_H = 10.0, 7.2
ASPECT = FIG_W / FIG_H          # 画布数据单位的长宽比：让圆在视觉上是正圆
INK_LINE = '#1a202c'            # 细实线（黑）


def circle_note(ax, cx, cy, r, text, fs=10.5):
    """白底细实线圆 + 居中文字。r 为视觉半径（数据单位，按 x 方向计）；
    y 方向按 ASPECT 放大，保证视觉为正圆。"""
    e = Ellipse((cx, cy), width=2 * r, height=2 * r * ASPECT,
                facecolor='white', edgecolor=LINE, linewidth=1.4, zorder=4)
    ax.add_patch(e)
    ax.text(cx, cy, text, ha='center', va='center', color=NAV, fontsize=fs, zorder=5)
    return (cx, cy)


def main():
    setup()
    fig, ax = canvas(FIG_W, FIG_H, xlim=(0, 100), ylim=(0, 100))

    # ---- 三个子框（同尺寸、同高度、等距） ----
    CW, CH = 24.0, 10.0
    xs = [17.0, 44.0, 71.0]          # 三个子框中心 x
    child_top = 42.0
    labels = ['需求规格V1.1', '需求规格V1.2', '需求规格V1.3']
    for cx, t in zip(xs, labels):
        box(ax, cx - CW / 2, child_top, CW, CH, t, fc=FILL, ec=LINE, fs=10.5, radius=1.2)

    # ---- 顶层父框（中心与中间子框对齐，整体偏左留出右侧标注区） ----
    PW, PH = 24.0, 10.0
    px, ptop = xs[1], 86.0          # 父框中心 x = 中间子框中心 x
    box(ax, px - PW / 2, ptop, PW, PH, '需求规格', fc=NAV, ec=NAV, tc='white',
        bold=True, fs=12, radius=1.2)
    p_bottom = ptop - PH            # 80

    # ---- 主干 + 水平母线（T 形分叉） ----
    BUS_Y = 58.0
    line(ax, (px, p_bottom), (px, BUS_Y), color=INK_LINE, lw=1.4)   # 竖主干
    line(ax, (xs[0], BUS_Y), (xs[2], BUS_Y), color=INK_LINE, lw=1.4)  # 水平母线

    # ---- 三支下垂线 ----
    for cx in xs:
        line(ax, (cx, BUS_Y), (cx, child_top), color=INK_LINE, lw=1.4)

    # ---- 圆形标注框①：配置项类 → 父框右侧边 ----
    c1 = (69.0, 84.0)
    circle_note(ax, c1[0], c1[1], 7.6, '配置项类')
    ax.plot([c1[0] - 7.0, px + PW / 2 + 0.8], [c1[1] - 2.2, 81.2],
            color=INK_LINE, lw=1.1, zorder=3)

    # ---- 圆形标注框②：配置项实例 → V1.3 右上角 ----
    c2 = (89.0, 57.0)
    circle_note(ax, c2[0], c2[1], 7.4, '配置项实例')
    ax.plot([c2[0] - 4.8, xs[2] + CW / 2 - 0.9], [c2[1] - 8.2, child_top + 0.4],
            color=INK_LINE, lw=1.1, zorder=3)

    caption(ax, '图 7-10　配置项类及实例', fs=11.5, y=14)
    save(fig, OUT)


if __name__ == '__main__':
    main()
