# -*- coding: utf-8 -*-
"""图 6-3　项目预算的组成 —— 教材第 126 页

照原图绘制：阶梯式（瀑布式）累计构成图，4 根竖矩形柱，底边齐平、顶边逐级下降。
项目预算 = 成本基准 + 管理储备
成本基准 = 工作包成本估算 + 应急储备
工作包成本估算 = 活动成本估算 + 活动应急储备
左侧竖排向上箭头标「总计」；图内自带题名「项目预算的组成」。
"""
import os
import sys

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

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图6-3-项目预算的组成.png')

from matplotlib.patches import FancyArrowPatch, Rectangle

BASE = 14.0          # 柱底
TOTAL = 88.0         # 项目预算全高
BW = 15.0            # 柱宽
XS = [30.0, 47.0, 64.0, 81.0]

# 四级台阶：各级顶边高度（相对全高）
H = [TOTAL, 74.0, 58.0, 46.0]
# 各级上下段文字
SEG = [
    ['项目预算'],
    ['管理储备', '成本基准'],
    ['应急储备', '工作包成本估算'],
    ['活动应急储备', '活动成本估算'],
]
# 上段占比（管理储备占全高约 1/4；应急储备、活动应急储备各约占本级 1/4）
SPLIT = [1.0, 0.75, 0.60, 0.55]     # 下段起点占本级高度的比例


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

    for i, x in enumerate(XS):
        top = H[i]
        # 整柱白底细黑线
        ax.add_patch(Rectangle((x, BASE), BW, top - BASE, fill=True, facecolor='white',
                               edgecolor='#1a1a2e', lw=1.5, zorder=3))
        segs = SEG[i]
        if len(segs) == 1:
            ax.text(x + BW / 2, (BASE + top) / 2, segs[0], ha='center', va='center',
                    fontsize=12.5, color='#1a1a2e', zorder=4)
        else:
            split = BASE + (top - BASE) * SPLIT[i]
            # 上段
            ax.text(x + BW / 2, (split + top) / 2, segs[0], ha='center', va='center',
                    fontsize=11, color='#1a1a2e', zorder=4)
            # 下段（可能两行）
            ax.text(x + BW / 2, (BASE + split) / 2, segs[1], ha='center', va='center',
                    fontsize=11, color='#1a1a2e', zorder=4, linespacing=1.5)
            # 分隔线
            ax.plot([x, x + BW], [split, split], color='#1a1a2e', lw=1.2, zorder=4)

    # 左侧竖排「总计」向上箭头
    ax_x = 24.0
    ar = FancyArrowPatch((ax_x, BASE), (ax_x, TOTAL), arrowstyle='-|>', mutation_scale=16,
                         linewidth=1.8, color=NAV)
    ax.add_patch(ar)
    ax.text(ax_x - 4.0, (BASE + TOTAL) / 2, '总\n计', ha='center', va='center',
            fontsize=12, color=NAV, fontweight='bold', linespacing=1.6)

    # 图内自带题名
    ax.text(55, 6.5, '项目预算的组成', ha='center', va='center', fontsize=12,
            color='#1a1a2e', fontweight='bold')

    save(fig, OUT)
    print('✅ 已绘制', os.path.basename(OUT), os.path.getsize(OUT) // 1024, 'KB')


if __name__ == '__main__':
    main()
