# -*- coding: utf-8 -*-
"""图 6-4　项目资金需求、成本基准与支出 —— 教材第 126 页

照原图绘制：直角坐标图，无网格、无数字刻度。
· 图框上边线 = 项目预算水平线
· 框内上部横线 = 成本基准（距上边线约 1/3 图高），两者间竖向双箭头标「管理储备」
· 实线 S 曲线 = 成本基准（右端止于成本基准线）
· 长虚线 S 曲线 = 成本支出（起点约 40% 处升起，约 70% 处上穿实线，末端趋近项目预算线）
· 点线 4 级阶梯 = 资金需求（最高级与成本基准线重合，最右以点线升至项目预算线）
"""
import os
import sys

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, NAV, INK

import matplotlib.pyplot as plt

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图6-4-项目资金需求成本基准与支出.png')

X0, X1 = 16.0, 88.0          # 绘图区左右
Y0, Y1 = 16.0, 82.0          # 绘图区上下
BUDGET = Y1
BASELINE = Y0 + (Y1 - Y0) * 0.62      # 成本基准线（距上边线约 1/3 图高）


def sig(u, k, mid, lo, hi):
    return lo + (hi - lo) / (1 + np.exp(-k * (u - mid)))


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

    # 图框
    ax.plot([X0, X1, X1, X0, X0], [Y0, Y0, Y1, Y1, Y0], color='#1a1a2e', lw=1.5, zorder=2)

    # 成本基准线
    ax.plot([X0, X1], [BASELINE, BASELINE], color='#1a1a2e', lw=1.3, zorder=3)

    # 管理储备：两线之间竖向双箭头（放在左侧，避开曲线）
    xm = X0 + 3.0
    ax.annotate('', xy=(xm, BUDGET - 1.0), xytext=(xm, BASELINE + 1.0),
                arrowprops=dict(arrowstyle='<|-|>', color='#1a1a2e', lw=1.4))
    ax.text(xm + 2.4, (BUDGET + BASELINE) / 2, '管理储备', ha='left', va='center',
            fontsize=10.5, color=INK)

    # 坐标轴
    ax.annotate('', xy=(X1 + 9, Y0), xytext=(X0, Y0),
                arrowprops=dict(arrowstyle='-|>', color='#1a1a2e', lw=1.4))
    ax.text((X0 + X1) / 2, Y0 - 7.5, '时间', ha='center', va='top', fontsize=11, color=INK)
    ax.annotate('', xy=(X0, Y1 + 8), xytext=(X0, Y0),
                arrowprops=dict(arrowstyle='-|>', color='#1a1a2e', lw=1.4))
    ax.text(X0 - 5.0, (Y0 + Y1) / 2, '成本累计值', ha='center', va='center',
            rotation=90, fontsize=11, color=INK)

    xs = np.linspace(X0, X1, 400)
    u = (xs - X0) / (X1 - X0)

    # 实线 S 曲线：成本基准（右端止于成本基准线）
    y_b = sig(u, 7.5, 0.52, Y0 + 1.0, BASELINE)
    ax.plot(xs, y_b, color=NAV, lw=2.2, zorder=4)

    # 长虚线 S 曲线：成本支出（40% 后升起，~70% 上穿实线，末端趋近项目预算）
    y_s = sig(u, 7.0, 0.74, Y0 + 1.0, BUDGET - 1.5)
    y_s = np.where(u < 0.34, Y0 + 0.8, y_s)
    ax.plot(xs, y_s, color='#c05621', lw=2.0, ls=(0, (8, 4)), zorder=5)

    # 点线 4 级阶梯：资金需求
    steps = [(0.00, 0.22, 0.20), (0.22, 0.44, 0.38), (0.44, 0.66, 0.58), (0.66, 1.00, 1.00)]
    prev = None
    for a, b, h in steps:
        xa, xb = X0 + (X1 - X0) * a, X0 + (X1 - X0) * b
        ytop = Y0 + (BASELINE - Y0) * h
        if prev is not None:
            ax.plot([xa, xa], [prev, ytop], color='#2f855a', lw=1.6, ls=(0, (1.6, 1.6)), zorder=6)
        ax.plot([xa, xb], [ytop, ytop], color='#2f855a', lw=1.6, ls=(0, (1.6, 1.6)), zorder=6)
        prev = ytop
    # 最右端升到项目预算线（追加管理储备）
    ax.plot([X1, X1], [prev, BUDGET], color='#2f855a', lw=1.6, ls=(0, (1.6, 1.6)), zorder=6)

    # 标注（放在空白处，用短直线引线，避免互相压字）
    def tag(text, xy, xytext, color):
        ax.annotate(text, xy=xy, xytext=xytext, fontsize=10.5, color=color,
                    ha='left', va='center',
                    arrowprops=dict(arrowstyle='-', color=color, lw=0.9,
                                    shrinkA=2, shrinkB=2))

    tag('项目预算', (X1 - 1, BUDGET), (X1 - 20, BUDGET + 9), INK)
    tag('成本基准', (X1 - 9, BASELINE), (X1 - 2, BASELINE + 13), NAV)
    tag('成本支出', (X0 + (X1 - X0) * 0.80, Y0 + (BUDGET - Y0) * 0.52),
        (X0 + (X1 - X0) * 0.30, Y0 + (BUDGET - Y0) * 0.22), '#c05621')
    tag('资金需求', (X0 + (X1 - X0) * 0.33, Y0 + (BASELINE - Y0) * 0.38),
        (X0 + 1.0, Y0 + 3.0), '#2f855a')

    fig.savefig(OUT)          # 直接保存：本图用绝对坐标布局，不走自动扩展以免压缩画面
    plt.close(fig)
    print('✅ 已绘制', os.path.basename(OUT), os.path.getsize(OUT) // 1024, 'KB')


if __name__ == '__main__':
    main()
