# -*- coding: utf-8 -*-
"""图 6-1　某软件项目的自下而上成本估算示例（单位：元）—— 教材第 120 页

照原图绘制：三层树形结构（WBS 自上而下展开、成本自下而上汇总）；
无坐标轴、无图例、无刻度；矩形方框内两行文字（编号+活动名称／金额）；
连线为折线，箭头朝上（子项汇总到父项）。
"""
import os
import sys

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

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图6-1-某软件项目的自下而上成本估算示例.png')

L1 = ('1 需求分析', '9000')
L2 = [('1.1 收集需求', '5000'), ('1.2 编写需求文档', '4000')]
L3 = [('1.1.1 需求沟通', '3000'), ('1.1.2 调研行业最佳实践', '2000'),
      ('1.2.1 编写需求文档草稿', '2000'), ('1.2.2 调研行业最佳实践', '2000')]

BW, BH = 20.0, 9.5          # 框宽、框高
Y1, Y2, Y3 = 92.0, 66.0, 38.0


def center_x(width, idx, n, span=(4, 96)):
    """把 n 个框均匀铺在 span 内，返回第 idx 个框的左边界。"""
    left, right = span
    gap = (right - left - n * width) / (n - 1) if n > 1 else 0
    return left + idx * (width + gap)


def main():
    setup()
    fig, ax = canvas(11.0, 7.2, xlim=(0, 100), ylim=(0, 104))

    # 顶层
    x1 = 50 - BW / 2
    c1 = box(ax, x1, Y1, BW, BH, f'{L1[0]}\n{L1[1]}', fc=NAV, ec=NAV, tc='white', bold=True, fs=12)

    # 第二层
    xs2, c2 = [], []
    for i, (name, amt) in enumerate(L2):
        x = center_x(BW, i, len(L2), span=(14, 86))
        xs2.append(x)
        c2.append(box(ax, x, Y2, BW, BH, f'{name}\n{amt}', fs=11.5))

    # 第三层
    xs3, c3 = [], []
    for i, (name, amt) in enumerate(L3):
        x = center_x(BW, i, len(L3), span=(2, 98))
        xs3.append(x)
        c3.append(box(ax, x, Y3, BW, BH, f'{name}\n{amt}', fs=11))

    # 连线（折线：父框底边中点 → 竖直下 → 斜向 → 竖直下 → 子框顶边；箭头朝上）
    def link(parent_cx, parent_bottom, child_cx, child_top, split_y):
        line(ax, (parent_cx, parent_bottom), (parent_cx, split_y), color=LINE, lw=1.4)
        line(ax, (parent_cx, split_y), (child_cx, split_y), color=LINE, lw=1.4)
        arrow(ax, (child_cx, split_y), (child_cx, child_top), color=LINE, lw=1.4)

    mid12 = (Y1 - BH + Y2) / 2
    mid23 = (Y2 - BH + Y3) / 2
    for x in xs2:
        link(c1[0], Y1 - BH, x + BW / 2, Y2, mid12)
    for i, x in enumerate(xs3):
        parent = c2[0][0] if i < 2 else c2[1][0]
        link(parent, Y2 - BH, x + BW / 2, Y3, mid23)

    caption(ax, '图 6-1　某软件项目的自下而上成本估算示例（单位：元）', fs=11, y=6)
    save(fig, OUT)
    print('✅ 已绘制', os.path.basename(OUT), os.path.getsize(OUT) // 1024, 'KB')


if __name__ == '__main__':
    main()
