# -*- coding: utf-8 -*-
"""图 5-16　使用 Project 生成的里程碑图（按统一数据 + 照片中的里程碑日期重绘）

左：任务名称（摘要任务 + 5 个里程碑任务）
右：Project 式周刻度（月 / 周起始日），菱形=里程碑，旁标完成日期
"""
import os
import sys
import datetime as dt

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

from _draw import setup, INK, NAV, ACC, FILL, LINE

# 照片中图 5-16 的里程碑标记：11/27、12/12、12/31、1/24、2/3
ROWS = [
    ("1.教务管理系统", None, True),
    ("完成系统需求工作", dt.date(2024, 11, 27), False),
    ("完成系统设计工作", dt.date(2024, 12, 12), False),
    ("完成系统开发工作", dt.date(2024, 12, 31), False),
    ("完成系统测试工作", dt.date(2025, 1, 24), False),
    ("完成系统部署与交付工作", dt.date(2025, 2, 3), False),
]

AXIS_START = dt.date(2024, 11, 11)   # 周一
AXIS_END = dt.date(2025, 2, 9)
N_DAYS = (AXIS_END - AXIS_START).days + 1
N = len(ROWS)


def main():
    setup()
    fig = plt.figure(figsize=(14.0, 4.5))
    gs = fig.add_gridspec(1, 2, width_ratios=[1.0, 2.35], wspace=0.012,
                          left=0.008, right=0.992, top=0.985, bottom=0.02)
    axT = fig.add_subplot(gs[0, 0])
    axG = fig.add_subplot(gs[0, 1])

    HEAD = 2.1
    TOP = N + HEAD
    BOT = -0.4

    # ── 左：任务表 ──────────────────────────────────────────────
    axT.set_xlim(0, 1)
    axT.set_ylim(BOT, TOP)
    axT.axis('off')
    axT.add_patch(Rectangle((0, BOT), 1, TOP - BOT, fill=False, lw=1.2, ec=NAV))
    axT.add_patch(Rectangle((0, N), 1, HEAD, facecolor=FILL, edgecolor=NAV, lw=1.1))
    axT.text(0.022, N + HEAD / 2, "任务名称", ha='left', va='center', fontsize=8.4,
             color=NAV, fontweight='bold')
    for i, (nm, mdate, bold) in enumerate(ROWS):
        y = N - i - 0.5
        if i:
            axT.plot([0, 1], [N - i, N - i], color=LINE, lw=0.6)
        axT.text(0.030 + (0.0 if bold else 0.055), y, nm, ha='left', va='center',
                 fontsize=7.4, color=INK, fontweight='bold' if bold else 'normal')

    # ── 右：里程碑图 ────────────────────────────────────────────
    axG.set_xlim(0, N_DAYS)
    axG.set_ylim(BOT, TOP)
    axG.axis('off')

    # 周分隔虚线
    for k in range(0, N_DAYS + 1, 7):
        axG.plot([k, k], [BOT, N], color='#8fa3b8', lw=0.55, ls=(0, (2, 2)), zorder=1)

    # 头部：周刻度（只标日）+ 月份
    axG.plot([0, N_DAYS], [N, N], color=NAV, lw=1.2)
    axG.plot([0, N_DAYS], [N + 1.1, N + 1.1], color=NAV, lw=0.7, alpha=0.75)
    axG.add_patch(Rectangle((0, N), N_DAYS, HEAD, fill=False, lw=1.2, ec=NAV))
    for k in range(0, N_DAYS, 7):
        dc = AXIS_START + dt.timedelta(days=k)
        axG.text(k + 0.9, N + 0.55, f"{dc.day}", ha='center', va='center',
                 fontsize=7.2, color=NAV)
        axG.plot([k, k], [N + 0.0, N + 1.1], color=NAV, lw=0.6, alpha=0.6)

    m0 = 0
    while m0 < N_DAYS:
        dc = AXIS_START + dt.timedelta(days=m0)
        m1 = m0
        while m1 < N_DAYS and (AXIS_START + dt.timedelta(days=m1)).month == dc.month:
            m1 += 1
        label = f"{dc.year}年{dc.month}月"
        axG.text((m0 + m1) / 2, N + 1.6, label, ha='center', va='center',
                 fontsize=7.6, color=NAV, fontweight='bold')
        if m0:
            axG.plot([m0, m0], [N + 0.0, N + HEAD], color=NAV, lw=0.9)
        m0 = m1

    # 里程碑菱形
    for i, (nm, mdate, bold) in enumerate(ROWS):
        y = N - i - 0.5
        if mdate is None:
            continue
        x = (mdate - AXIS_START).days + 0.5
        axG.plot([x], [y], marker='D', ms=7.0, color=INK, zorder=5)
        axG.text(x + 1.1, y, f"{mdate.month}/{mdate.day}", ha='left', va='center',
                 fontsize=8.0, color=INK, fontweight='bold', zorder=6)

    axG.add_patch(Rectangle((0, BOT), N_DAYS, TOP - BOT, fill=False, lw=1.2, ec=NAV, zorder=9))

    out = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',
                                       'assets', '图5-16-使用Project生成的里程碑图.png'))
    fig.savefig(out)
    print('✅ 已绘制', os.path.basename(out), os.path.getsize(out) // 1024, 'KB')
    plt.close(fig)


if __name__ == '__main__':
    main()
