# -*- coding: utf-8 -*-
"""图 9-4　沟通渠道示例 —— 教材第 218 页

逐项对照图内要素：
· 不设坐标轴、不设刻度、不标人名与编号，纯示意图；
· 画面中央 2×2 方阵排布四枚黑色人形剪影（圆头＋宽肩实心人形），
  分别位于左上、右上、左下、右下；
· 四人两两相连共 6 条黑色虚线，均不带箭头：
  上横线（左上—右上）、下横线（左下—右下）、左竖线（左上—左下）、
  右竖线（右上—右下）、左上—右下斜线、右上—左下斜线；
· 对应正文 4×(4-1)/2 = 6 条渠道；
· 图题「图 9-4　沟通渠道示例」居中置于图形正下方。
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, save, caption, line  # noqa: E402

import numpy as np                                    # noqa: E402
import matplotlib.pyplot as plt                       # noqa: E402
from matplotlib.path import Path                      # noqa: E402
from matplotlib.patches import PathPatch              # noqa: E402

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图9-4-沟通渠道示例.png')

BLACK = '#1a1a1a'


def person(ax, cx, cy, s=1.0, color=BLACK):
    """人形剪影：圆头 + 宽肩（半圆肩 + 直身）。

    头与身躯合成**一个复合路径**一次填充，避免两块图元拼缝处出现抗锯齿白线
    （早期版本该白缝会让身后虚线的黑色"透"出来）。"""
    head = Path.circle((cx, cy + 5.4 * s), 2.7 * s)

    th = np.linspace(0.0, np.pi, 60)
    arc = [(cx + 5.4 * s * np.cos(t), cy - 0.6 * s + 5.4 * s * np.sin(t)) for t in th]
    verts = [(arc[0][0], arc[0][1])] + arc[1:]
    verts += [(cx - 5.4 * s, cy - 6.8 * s), (cx + 5.4 * s, cy - 6.8 * s),
              (arc[0][0], arc[0][1])]
    codes = [Path.MOVETO] + [Path.LINETO] * (len(verts) - 1)
    body = Path(verts, codes)

    comp = Path.make_compound_path(head, body)
    ax.add_patch(PathPatch(comp, facecolor=color, edgecolor='none', lw=0, zorder=4))


def main():
    setup()
    fig, ax = canvas(8.0, 7.8, xlim=(16, 84), ylim=(13, 80))

    # ── 四个剪影中心（2×2 方阵）──
    P = {'TL': (30, 68), 'TR': (70, 68), 'BL': (30, 36), 'BR': (70, 36)}

    # ── 6 条虚线：先画线（zorder 低），剪影覆盖其上，形成"两两相通"──
    pairs = [('TL', 'TR'), ('BL', 'BR'), ('TL', 'BL'), ('TR', 'BR'),
             ('TL', 'BR'), ('TR', 'BL')]
    for a, b in pairs:
        line(ax, P[a], P[b], color=BLACK, lw=1.3, ls=(0, (5, 3.2)))

    for k in ('TL', 'TR', 'BL', 'BR'):
        person(ax, *P[k], s=1.0)

    # ── 图题（六号宋体居中，图形正下方）──
    caption(ax, '图 9-4　沟通渠道示例', fs=10.5, y=16.0)

    save(fig, OUT)


if __name__ == '__main__':
    main()
