# -*- coding: utf-8 -*-
"""图 5-14　进度压缩
三条横道：正常情况（15 天，3 段各 5 天、每段 1 人）、
赶工（10 天，3 段、每段 2 人）、快速跟进（11 天，3 段交叠、每段 1 人）。
小人图标按教材原图位置绘制。
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from _draw import setup, canvas, save, INK
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle, Polygon

setup()

X0 = 26.0        # 第 1 天左边界
CW = 6.0         # 每天宽度
CH = 4.5         # 横道高度
GREY = '#2d3748'


def day(ax, d, y_top, h=CH):
    x = X0 + (d - 1) * CW
    ax.add_patch(Rectangle((x, y_top - h), CW, h, facecolor='white',
                           edgecolor=INK, lw=1.2, zorder=3))
    ax.text(x + CW / 2, y_top - h / 2, str(d), ha='center', va='center',
            fontsize=9.5, color=INK, zorder=4)
    return x


def bar(ax, d1, d2, y_top):
    for d in range(d1, d2 + 1):
        day(ax, d, y_top)


def person(ax, cx, y_base, s=1.0):
    """在 (cx, y_base) 处画一个小人（头顶朝上）。"""
    ax.add_patch(Circle((cx, y_base + 3.55 * s), 0.72 * s,
                        facecolor=GREY, edgecolor='none', zorder=5))
    pts = [(cx - 1.45 * s, y_base), (cx + 1.45 * s, y_base),
           (cx + 1.05 * s, y_base + 2.05 * s),
           (cx + 0.45 * s, y_base + 2.55 * s),
           (cx - 0.45 * s, y_base + 2.55 * s),
           (cx - 1.05 * s, y_base + 2.05 * s)]
    ax.add_patch(Polygon(pts, closed=True, facecolor=GREY,
                         edgecolor='none', zorder=5))


def label(ax, text, y):
    ax.text(1.0, y, text, ha='left', va='center', fontsize=12.5, color=INK)


fig, ax = canvas(w=12.0, h=9.1, xlim=(0, 120), ylim=(16, 107))

# ---------- 正常情况：1-5 / 6-10 / 11-15，各 1 人 ----------
label(ax, '正常情况', 101.75)
bar(ax, 1, 5, 104)
person(ax, X0 + 2.5 * CW, 95.0)
bar(ax, 6, 10, 95.5)
person(ax, X0 + 7.5 * CW, 86.5)
bar(ax, 11, 15, 87)
person(ax, X0 + 12.5 * CW, 78.0)

# ---------- 赶工：1-3 / 4-6 / 7-10，各 2 人 ----------
label(ax, '赶工', 71.75)
bar(ax, 1, 3, 74)
person(ax, X0 + 0.5 * CW, 65.0)
person(ax, X0 + 1.5 * CW, 65.0)
bar(ax, 4, 6, 65.5)
person(ax, X0 + 3.5 * CW, 56.5)
person(ax, X0 + 4.5 * CW, 56.5)
bar(ax, 7, 10, 57)
person(ax, X0 + 7.2 * CW, 48.0)
person(ax, X0 + 8.2 * CW, 48.0)

# ---------- 快速跟进：1-5 / 4-8 / 7-11 交叠，各 1 人 ----------
label(ax, '快速跟进', 41.75)
bar(ax, 1, 5, 44)
person(ax, X0 + 2.5 * CW, 35.0)
bar(ax, 4, 8, 35.5)
person(ax, X0 + 4.5 * CW, 26.5)
bar(ax, 7, 11, 27)
person(ax, X0 + 8.5 * CW, 18.0)

save(fig, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                       'assets', '图5-14-进度压缩.png'))
