# -*- coding: utf-8 -*-
"""图 6-2　项目预算成本汇总示例 —— 教材第 124 页

照原图绘制：自上而下的 WBS 式成本汇总树，共 4 层 9 个矩形框；
框内两行（编号＋名称／金额），箭头由下层指向上层（逐层汇总）。
加和：3000+2000=5000；2000+2000=4000；5000+4000=9000；9000+1000=10000。
"""
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-2-项目预算成本汇总示例.png')

L1 = ('1 需求分析 总预算', '10000')
L2 = [('1 需求分析 总成本估算', '9000'), ('管理储备', '1000')]
L3 = [('1.1 收集需求', '5000'), ('1.2 编写需求文档', '4000')]
L4 = [('1.1.1 需求沟通', '3000'), ('1.1.2 调研行业最佳实践', '2000'),
      ('1.2.1 编写需求文档草稿', '2000'), ('1.2.2 调研行业最佳实践', '2000')]

BW, BH = 21.0, 9.0
Y = [93.0, 71.0, 48.0, 24.0]


def distribute(n, width, span=(3, 97)):
    left, right = span
    gap = (right - left - n * width) / (n - 1) if n > 1 else 0
    return [left + i * (width + gap) for i in range(n)]


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

    xs1 = [50 - BW / 2]
    c1 = box(ax, xs1[0], Y[0], BW, BH, f'{L1[0]}\n{L1[1]}', fc=NAV, ec=NAV, tc='white', bold=True, fs=11.5)

    xs2 = distribute(2, BW, span=(8, 92))
    c2 = [box(ax, x, Y[1], BW, BH, f'{n}\n{a}', fs=11) for x, (n, a) in zip(xs2, L2)]

    xs3 = distribute(2, BW, span=(8, 92))
    c3 = [box(ax, x, Y[2], BW, BH, f'{n}\n{a}', fs=11) for x, (n, a) in zip(xs3, L3)]

    xs4 = distribute(4, BW, span=(1, 99))
    c4 = [box(ax, x, Y[3], BW, BH, f'{n}\n{a}', fs=10.2) for x, (n, a) in zip(xs4, L4)]

    def link(px, py_bottom, cx, cy_top, split):
        """父框底 → 子框顶，箭头朝上（子项汇总到父项）"""
        line(ax, (px, py_bottom), (px, split), color=LINE, lw=1.3)
        line(ax, (px, split), (cx, split), color=LINE, lw=1.3)
        arrow(ax, (cx, split), (cx, cy_top), color=LINE, lw=1.3)

    # 顶层 → 第 2 层（总成本估算 + 管理储备）
    s12 = (Y[0] - BH + Y[1]) / 2
    for x in xs2:
        link(c1[0] + BW / 2 if False else xs1[0] + BW / 2, Y[0] - BH, x + BW / 2, Y[1], s12)

    # 总成本估算 → 1.1 / 1.2
    s23 = (Y[1] - BH + Y[2]) / 2
    for x in xs3:
        link(xs2[0] + BW / 2, Y[1] - BH, x + BW / 2, Y[2], s23)

    # 1.1 → 1.1.1 / 1.1.2 ；1.2 → 1.2.1 / 1.2.2
    s34 = (Y[2] - BH + Y[3]) / 2
    for i, x in enumerate(xs4):
        parent = xs3[0] + BW / 2 if i < 2 else xs3[1] + BW / 2
        link(parent, Y[2] - BH, x + BW / 2, Y[3], s34)

    caption(ax, '图 6-2　项目预算成本汇总示例（单位：元）', fs=11, y=5)
    save(fig, OUT)
    print('✅ 已绘制', os.path.basename(OUT), os.path.getsize(OUT) // 1024, 'KB')


if __name__ == '__main__':
    main()
