# -*- coding: utf-8 -*-
"""图 7-9　缺陷到达模式 —— 教材第 160 页

按「图内要素」逐项还原：
· 直角坐标系，无网格线；纵轴「缺陷数/个」竖排于轴左侧，只画向上箭头、不标刻度数字
· 横轴等距标出「第1周」…「第6周」，右端画箭头并标「时间」
· 实线「缺陷数」：第1–6 周依次 5、8、6、4、3、2（5 标在首点下方，8/6/4/3 在折线下方，2 在末点右侧）
· 虚线「累计缺陷数」：5、13、19、23、26、28（13/19/23/26/28 标在虚线上方）
· 横轴下方居中图例：实线「缺陷数」、虚线「累计缺陷数」
"""
import os
import sys

import matplotlib.pyplot as plt

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

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图7-9-缺陷到达模式.png')

WK = [1, 2, 3, 4, 5, 6]
BUG = [5, 8, 6, 4, 3, 2]            # 每周缺陷数
CUM = [5, 13, 19, 23, 26, 28]       # 累计缺陷数


def main():
    setup()
    fig, ax = plt.subplots(figsize=(9.6, 6.3))
    ax.set_xlim(0, 7.35)
    ax.set_ylim(-7.4, 33.0)
    ax.axis('off')

    # 坐标轴：仅向上箭头 / 向右箭头
    ax.annotate('', xy=(0.42, 32.0), xytext=(0.42, 0),
                arrowprops=dict(arrowstyle='-|>', color=INK, lw=1.4,
                                shrinkA=0, shrinkB=0))
    ax.annotate('', xy=(7.0, 0), xytext=(0.42, 0),
                arrowprops=dict(arrowstyle='-|>', color=INK, lw=1.4,
                                shrinkA=0, shrinkB=0))

    # 纵轴标题（竖排）
    ax.text(0.02, 16.0, '缺陷数/个', rotation=90, ha='center', va='center',
            fontsize=13, color=INK)
    # 横轴箭头旁「时间」
    ax.text(7.06, 0, '时间', ha='left', va='center', fontsize=12.5, color=INK)

    # 横轴刻度标签
    for w in WK:
        ax.text(w, -0.9, f'第{w}周', ha='center', va='top', fontsize=12, color=INK)

    # 实线：每周缺陷数
    ax.plot(WK, BUG, color=INK, lw=1.8, zorder=3)
    # 虚线：累计缺陷数
    ax.plot(WK, CUM, color=ACC, lw=1.7, linestyle=(0, (4.2, 2.4)), zorder=2)

    # 数值标注
    for w, v in zip(WK, BUG):
        if w == 1:
            ax.text(w + 0.10, v - 1.6, str(v), ha='left', va='top',
                    fontsize=12.5, color=INK)
        elif w == 6:
            ax.text(w + 0.13, v, str(v), ha='left', va='center',
                    fontsize=12.5, color=INK)
        else:
            ax.text(w, v - 1.2, str(v), ha='center', va='top',
                    fontsize=12.5, color=INK)

    for w, v in zip(WK[1:], CUM[1:]):
        ax.text(w, v + 1.2, str(v), ha='center', va='bottom',
                fontsize=12.5, color=ACC)

    # 图例（横轴下方居中）
    from matplotlib.lines import Line2D
    handles = [Line2D([], [], color=INK, lw=1.8, label='缺陷数'),
               Line2D([], [], color=ACC, lw=1.7, linestyle=(0, (4.2, 2.4)),
                      label='累计缺陷数')]
    leg = ax.legend(handles=handles, loc='lower center', ncol=2, frameon=False,
                    fontsize=12.5, handlelength=2.6, columnspacing=2.4,
                    bbox_to_anchor=(0.52, 0.002), borderaxespad=0)
    for t in leg.get_texts():
        t.set_color(INK)

    fig.tight_layout()
    save(fig, OUT)


if __name__ == '__main__':
    main()
