# -*- coding: utf-8 -*-
"""图 7-6　帕累托图示例 —— 教材第 154 页

按「图内要素」逐项还原（软件界面截图样式 → 重绘为教材插图）：
· 左上角标题「帕累托图」，其后紧跟浅灰英文「Pareto chart」；图内居中标题「未及时提交代码」
· 五根竖条降序：需求变更 30、代码修复 22、代码审查延迟 16、团队协作 8、设备故障 3，
  每根柱顶标注该数值
· 柱上叠加累计占比曲线（圆点连线）：38.0%、67.1%、86.1%、96.2%、100.0%，
  各点用细竖线向下连到对应柱顶
· 右侧三列表：因素 / 发生次数 / 累计占比，逐行同上
· 原图无纵轴刻度数字与轴标题
"""
import os
import sys

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from matplotlib.transforms import Bbox
from _draw import setup, save, INK, NAV, ACC, FILL, LINE

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图7-6-帕累托图示例.png')

ITEMS = ['需求变更', '代码修复', '代码审查延迟', '团队协作', '设备故障']
COUNTS = [30, 22, 16, 8, 3]
CUMS = [38.0, 67.1, 86.1, 96.2, 100.0]
TOTAL = 79.0                     # 30+22+16+8+3，累计占比的 100% 基准


def pin(ax):
    """把该 axes 的数据范围钉死在显示范围内 —— _draw.save() 见到「数据超出
    0–100 的相对坐标」会扩画布，对真实坐标轴的图表会整幅压扁；钉住后即不触发。"""
    x0, x1 = ax.get_xlim()
    y0, y1 = ax.get_ylim()
    ax.dataLim.set(Bbox.from_extents(x0, y0, x1, y1))
    ax.set_autoscale_on(False)


def pchip(x, y, xs):
    """单调三次 Hermite 插值（Fritsch–Carlson），用于累计曲线的平滑连接。"""
    x, y = np.asarray(x, float), np.asarray(y, float)
    h, d = np.diff(x), np.diff(y) / np.diff(x)
    m = np.zeros(len(x))
    m[0], m[-1] = d[0], d[-1]
    for i in range(1, len(x) - 1):
        if d[i - 1] * d[i] <= 0:
            m[i] = 0.0
        else:
            w1, w2 = 2 * h[i] + h[i - 1], h[i] + 2 * h[i - 1]
            m[i] = (w1 + w2) / (w1 / d[i - 1] + w2 / d[i])
    idx = np.clip(np.searchsorted(x, xs) - 1, 0, len(x) - 2)
    t = (xs - x[idx]) / h[idx]
    h00 = 2 * t**3 - 3 * t**2 + 1
    h10 = t**3 - 2 * t**2 + t
    h01 = -2 * t**3 + 3 * t**2
    h11 = t**3 - t**2
    return (h00 * y[idx] + h10 * h[idx] * m[idx]
            + h01 * y[idx + 1] + h11 * h[idx] * m[idx + 1])


def main():
    setup()
    fig = plt.figure(figsize=(11.4, 6.2))

    ax = fig.add_axes([0.075, 0.135, 0.545, 0.645])
    ax2 = ax.twinx()
    ax2.set_ylim(0, 100)

    x = np.arange(len(ITEMS))
    ax.set_ylim(0, TOTAL * 1.05)
    ax2.set_ylim(0, 100)

    # 柱形（深灰实心 → 浅蓝填充 + 细边）
    ax.bar(x, COUNTS, width=0.42, color=FILL, edgecolor=ACC, linewidth=1.2, zorder=2)

    # 柱顶数值（首柱顶正好是 38.0% 累计点的位置，该柱数值改标在柱内顶部，避免压字）
    for i, (xi, v) in enumerate(zip(x, COUNTS)):
        if i == 0:
            ax.text(xi, v - TOTAL * 0.012, str(v), ha='center', va='top',
                    fontsize=12, color=NAV, zorder=8)
        else:
            ax.text(xi, v + TOTAL * 0.018, str(v), ha='center', va='bottom',
                    fontsize=12, color=INK, zorder=8,
                    bbox=dict(facecolor='white', edgecolor='none', pad=1.2))

    # 累计曲线（左端自 0 起，右端收在 100%）
    px = np.concatenate([[-0.62], x, [4.62]])
    py = np.concatenate([[0.0], CUMS, [100.0]])
    xs = np.linspace(px[0], px[-1], 400)
    ax2.plot(xs, pchip(px, py, xs), color=INK, lw=1.6, zorder=5)
    ax2.plot(x, CUMS, linestyle='none', marker='o', ms=6.5, clip_on=False,
             markerfacecolor=INK, markeredgecolor=INK, zorder=6)

    # 各点向下引细竖线到对应柱顶
    for xi, c, v in zip(x, CUMS, COUNTS):
        ax2.plot([xi, xi], [c, v / TOTAL * 100], color='#718096', lw=0.7,
                 linestyle=(0, (2, 2)), zorder=1)

    # 累计占比标注：首点左侧（避开柱顶「30」），其余点在曲线上方
    tags = [(-0.12, 3.5, 'right', 'center'),
            (-0.02, 5.0, 'center', 'bottom'),
            (-0.02, 5.0, 'center', 'bottom'),
            (-0.02, 5.0, 'center', 'bottom'),
            (-0.10, 5.0, 'center', 'bottom')]
    for i, (xi, c) in enumerate(zip(x, CUMS)):
        dx, dy, ha, va = tags[i]
        ax2.text(xi + dx, c + dy, f'{c:.1f}%', ha=ha, va=va,
                 fontsize=11, color=INK, zorder=7,
                 bbox=dict(facecolor='white', edgecolor='none', pad=0.8))

    # 轴：无刻度数字、无轴标题，仅留细底轴
    ax.set_yticks([])
    ax2.set_yticks([])
    ax.set_xticks(list(x))
    ax.set_xticklabels(ITEMS, fontsize=11.5, color=INK)
    ax.tick_params(axis='x', length=0, pad=8)
    for s in ('top', 'right', 'left'):
        ax.spines[s].set_visible(False)
    ax.spines['bottom'].set_color(INK)
    ax.spines['bottom'].set_linewidth(1.1)
    for s in ('top', 'right', 'left'):
        ax2.spines[s].set_visible(False)
    ax2.spines['bottom'].set_visible(False)
    ax2.patch.set_visible(False)

    ax.set_xlim(-0.75, 4.75)
    ax.set_title('未及时提交代码', fontsize=13.5, color=NAV, pad=12)

    # 左上角面板标题
    fig.text(0.068, 0.925, '帕累托图', fontsize=17, color=INK, fontweight='bold',
             ha='left', va='center')
    fig.text(0.163, 0.918, 'Pareto chart', fontsize=12.5, color='#a0aec0',
             style='italic', ha='left', va='center')

    # ── 右侧数据表 ──
    tax = fig.add_axes([0.655, 0.135, 0.315, 0.645])
    tax.set_xlim(0, 1)
    tax.set_ylim(0, 1)
    tax.axis('off')

    rows = 1 + len(ITEMS)
    top, bottom = 0.96, 0.96 - 0.145 * rows
    tax.add_patch(plt.Rectangle((0.0, bottom), 1.0, top - bottom,
                                fill=False, edgecolor=LINE, lw=1.0))
    tax.add_patch(plt.Rectangle((0.0, top - 0.145), 1.0, 0.145,
                                facecolor=FILL, edgecolor=LINE, lw=1.0))
    for i in range(1, rows):
        yy = top - 0.145 * i
        tax.plot([0.0, 1.0], [yy, yy], color=LINE, lw=0.8)

    heads = ['因素', '发生次数', '累计占比']
    hx = [0.05, 0.60, 0.87]
    for h, xi in zip(heads, hx):
        tax.text(xi, top - 0.0725, h, ha='center' if xi > 0.2 else 'left',
                 va='center', fontsize=10.5, color=NAV, fontweight='bold')

    for i, (nm, cnt, cum) in enumerate(zip(ITEMS, COUNTS, CUMS)):
        yy = top - 0.145 * (i + 1) - 0.0725
        tax.text(0.05, yy, nm, ha='left', va='center', fontsize=10.5, color=INK)
        tax.text(0.62, yy, str(cnt), ha='center', va='center', fontsize=10.5, color=INK)
        tax.text(0.855, yy, f'{cum:.1f}%', ha='center', va='center',
                 fontsize=10.5, color=INK)

    pin(ax)
    pin(ax2)
    save(fig, OUT)


if __name__ == '__main__':
    main()
