# -*- coding: utf-8 -*-
"""图 6-5　挣值、计划价值与实际成本 —— 教材第 131 页

照原图绘制（教材原图无刻度、无图例，靠引线标签区分）：
· 外框上边 = 项目预算；其下平行线 = 完工预算（BAC）；两线之间窄带 = 管理储备
· 三条竖直参考线：数据日期（贯通全图）／计划完工日期（兼作右边线，顶端箭头在 BAC 处）／
  预计完工日期（框外右侧，越过项目预算线，顶端箭头＋完工估算 EAC）
· 三条实线曲线：AC（最高最陡，止于数据日期）、PV（居中，止于 BAC 与计划完工日期交点，带箭头）、
  EV（最低最缓，止于数据日期）；数据日期处 AC＞PV＞EV
· 一条虚线预测线：自数据日期处 AC 高度起，穿过 BAC、再穿过项目预算，止于预计完工日期顶端（EAC）
"""
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-5-挣值计划价值与实际成本.png')

XL, XR = 12.0, 86.0        # 图框左右（XR 兼作「计划完工日期」竖线）
XEAC = 99.0                # 预计完工日期（框外右侧）
XD = 54.0                  # 数据日期
YB, YBUD, YBAC = 12.0, 86.0, 70.0     # 框底、项目预算线、BAC 线


def smooth(px, py, n=300):
    """三次多项式拟合，得到平滑且过关键点附近的曲线。"""
    coef = np.polyfit(px, py, 3)
    xs = np.linspace(px[0], px[-1], n)
    return xs, np.polyval(coef, xs)


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

    # ── 图框（左／下／上三条边；右边线由「计划完工日期」的箭头线承担）──
    ax.plot([XL, XL], [YB, YBUD], color='#1a1a2e', lw=1.5, zorder=2)      # 左边
    ax.plot([XL, XR], [YB, YB], color='#1a1a2e', lw=1.5, zorder=2)        # 下边
    ax.plot([XL, XR], [YBUD, YBUD], color='#1a1a2e', lw=1.6, zorder=3)    # 上边 = 项目预算
    ax.plot([XL, XR], [YBAC, YBAC], color='#1a1a2e', lw=1.4, zorder=3)    # BAC 线

    # 管理储备（两线间竖向双箭头）
    xm = XL + 3.2
    ax.annotate('', xy=(xm, YBUD - 0.8), xytext=(xm, YBAC + 0.8),
                arrowprops=dict(arrowstyle='<|-|>', color='#1a1a2e', lw=1.3))
    ax.text(xm + 2.6, (YBUD + YBAC) / 2, '管理储备', ha='left', va='center',
            fontsize=10.5, color=INK)

    # 坐标轴
    ax.annotate('', xy=(XL, YBUD + 9), xytext=(XL, YB),
                arrowprops=dict(arrowstyle='-|>', color='#1a1a2e', lw=1.4))
    ax.text(XL - 5.2, (YB + YBUD) / 2, '成本累计值', ha='center', va='center',
            rotation=90, fontsize=11, color=INK)
    ax.annotate('', xy=(104, YB), xytext=(XL, YB),
                arrowprops=dict(arrowstyle='-|>', color='#1a1a2e', lw=1.4))
    ax.text((XL + XEAC) / 2, YB - 7.5, '时间', ha='center', va='top', fontsize=11, color=INK)

    # ── 竖直参考线 ──
    ax.plot([XD, XD], [YB, YBUD], color='#718096', lw=1.0, ls=(0, (4, 3)), zorder=1)
    ax.text(XD, YB - 3.0, '数据日期', ha='center', va='top', fontsize=10, color='#4a5568')

    # 计划完工日期（兼作右边线）：顶端箭头在 BAC 处
    ax.annotate('', xy=(XR, YBAC + 6), xytext=(XR, YB),
                arrowprops=dict(arrowstyle='-|>', color='#1a1a2e', lw=1.3))
    ax.text(XR - 1.0, YB - 3.0, '计划完工日期', ha='center', va='top', fontsize=10, color='#4a5568')

    # 预计完工日期（框外右侧，越过项目预算线）
    ax.annotate('', xy=(XEAC, YBUD + 13), xytext=(XEAC, YB),
                arrowprops=dict(arrowstyle='-|>', color='#1a1a2e', lw=1.3))
    ax.text(XEAC + 1.5, YB - 3.0, '预计完工日期', ha='left', va='top', fontsize=10, color='#4a5568')
    ax.text(XEAC + 2.0, YBUD + 13, '完工估算（EAC）', ha='left', va='center', fontsize=10.5, color=INK)

    # ── 三条实线曲线：累计成本随时间递增，前期陡、后期缓（幂函数，保证单调） ──
    def curve(x_end, y_end, p):
        t = np.linspace(0, 1, 300)
        xs = XL + (x_end - XL) * t
        ys = YB + (y_end - YB) * (t ** p)
        return xs, ys

    # AC：最陡最高，止于数据日期
    xs, ys = curve(XD, YB + 52, 0.72)
    ax.plot(xs, ys, color='#c05621', lw=2.3, zorder=6)

    # PV：居中，止于 BAC 与计划完工日期交点（带箭头）
    xs, ys = curve(XR, YBAC, 0.86)
    ax.plot(xs, ys, color=NAV, lw=2.3, zorder=5)

    # EV：最低最缓，止于数据日期
    xs, ys = curve(XD, YB + 28, 0.80)
    ax.plot(xs, ys, color='#2f855a', lw=2.3, zorder=4)

    # ── 虚线预测线：数据日期（AC 高度）→ 预计完工日期顶端 ──
    ax.plot([XD, XEAC], [YB + 52, YBUD + 13], color='#805ad5', lw=2.0, ls=(0, (7, 4)), zorder=7)

    # ── 引线标签 ──
    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('项目预算', (XL + 20, YBUD), (XL + 6, YBUD + 9), INK)
    tag('完工预算（BAC）', (XR + 0.6, YBAC), (XR + 2.0, YBAC + 7), INK)
    ax.text(XL + 2.6, YBAC - 5.0, '支出', ha='left', va='center', fontsize=10.5, color=INK)
    tag('实际成本（AC）', (XL + 12, YB + 22), (XL + 14, YB + 34), '#c05621')
    tag('计划价值（PV）', (XD + 6, YB + 40), (XD + 10, YB + 30), NAV)
    tag('挣值（EV）', (XL + 16, YB + 10), (XL + 4, YB + 3.0), '#2f855a')

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


if __name__ == '__main__':
    main()
