# -*- coding: utf-8 -*-
"""图 7-1　质量成本 —— 教材第 145 页

照原图绘制（原图为纯线框、无箭头）：
· 左右并列两个矩形框，两框顶边齐平；框上方各一行居中小标题
· 左框「一致性成本」较高：1.预测成本（生产合格产品）a–d ＋ 2.评价成本（评定质量）a–c
· 右框「非一致性成本」较矮：1.内部失败成本（项目内部发现的）a–b ＋ 2.外部失败成本（客户发现的）a–c
· 框下方框外各一行说明：左边「在项目期间，用于防止失败的费用」；
  右边「在项目期间和项目完成后，用于处理失败的费用」
· 图题居中置于图下方

版式微调（不影响结构）：四个一级条目加浅蓝底纹以区分层级（原图为纯白线框）。
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, box, caption, save, NAV, FILL, LINE

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图7-1-质量成本.png')

# 每行：(类型, 文字)  h = 一级条目（带浅蓝底纹），s = 缩进子项
LEFT = [
    ('h', '1. 预测成本（生产合格产品）'),
    ('s', 'a. 培训'),
    ('s', 'b. 流程文档化'),
    ('s', 'c. 设备'),
    ('s', 'd. 选择正确的做事时间'),
    ('h', '2. 评价成本（评定质量）'),
    ('s', 'a. 测试'),
    ('s', 'b. 破坏性测试导致的损失'),
    ('s', 'c. 检查'),
]

RIGHT = [
    ('h', '1. 内部失败成本（项目内部发现的）'),
    ('s', 'a. 返工'),
    ('s', 'b. 废品'),
    ('h', '2. 外部失败成本（客户发现的）'),
    ('s', 'a. 责任'),
    ('s', 'b. 保修'),
    ('s', 'c. 业务流失'),
]

ROW_Y0 = 85.5      # 首行居中 y
ROW_DY = 7.7       # 行距
FW = 45.0          # 框宽
TOP = 90.0         # 框顶
LX, RX = 3.5, 51.5  # 左／右框左边


def frame(ax, x, bottom, rows, note):
    """画一个分类框：框顶固定 TOP，底部按行数决定；框内逐行写文字。"""
    h = TOP - bottom
    box(ax, x, TOP, FW, h, '', fc='white', ec=NAV, lw=1.5, radius=0)
    for i, (kind, text) in enumerate(rows):
        y = ROW_Y0 - i * ROW_DY
        if kind == 'h':
            box(ax, x + 1.8, y + 3.05, FW - 3.6, 6.1, '', fc=FILL, ec=FILL, radius=0.8)
            ax.text(x + 3.4, y, text, ha='left', va='center', color=NAV,
                    fontsize=10.6, fontweight='bold')
        else:
            ax.text(x + 5.6, y, text, ha='left', va='center', color='#1a202c', fontsize=10.2)
    ax.text(x + FW / 2, bottom - 6.4, note, ha='center', va='center',
            color='#4a5568', fontsize=9.6)


def main():
    setup()
    fig, ax = canvas(10.4, 6.6, xlim=(0, 100), ylim=(0, 100))

    # 框上方的小标题
    ax.text(LX + FW / 2, TOP + 4.2, '一致性成本', ha='center', va='bottom',
            color=NAV, fontsize=13.5, fontweight='bold')
    ax.text(RX + FW / 2, TOP + 4.2, '非一致性成本', ha='center', va='bottom',
            color=NAV, fontsize=13.5, fontweight='bold')

    # 左框较高（9 行），右框较矮（7 行）
    frame(ax, LX, 19.5, LEFT, '在项目期间，用于防止失败的费用')
    frame(ax, RX, 33.0, RIGHT, '在项目期间和项目完成后，用于处理失败的费用')

    caption(ax, '图 7-1　质量成本', fs=11.5, y=3.0)
    save(fig, OUT)


if __name__ == '__main__':
    main()
