#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('Agg')
from matplotlib import font_manager, pyplot as plt
import numpy as np

# ---- 注册中文字体 ----
for f in ["/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
          "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
          "/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc"]:
    try:
        font_manager.fontManager.addfont(f)
    except Exception as e:
        print("addfont fail", f, e)

plt.rcParams['font.family'] = ['Noto Sans CJK SC', 'sans-serif']
plt.rcParams['axes.unicode_minus'] = False

# ---- 数据 ----
depts = ['人力资源部', '党群与综合部', '财务部', '生产管理部\n(安健环管理部)', '采购与合同管理部']
rate_2025 = [95, 47, 46, 28, 17]
rate_2026 = [98, 77, 81, 88, 85]
improve   = [3, 30, 35, 60, 68]
due_2026  = [120, 215, 200, 100, 160]   # 2026 应出勤
act_2026  = [118, 165, 162, 88, 136]    # 2026 实际出勤

C2025 = '#B6C2CC'   # 2025 浅灰
C2026 = '#0E7490'   # 2026 青蓝
CACC  = '#F59E0B'   # 强调橙

def style_ax(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_color('#CCCCCC')
    ax.spines['bottom'].set_color('#CCCCCC')
    ax.tick_params(colors='#555555', labelsize=11)
    ax.yaxis.grid(True, color='#EEEEEE', linewidth=0.8)
    ax.set_axisbelow(True)

# ============ 图1：出勤率对比 2025 vs 2026 ============
fig, ax = plt.subplots(figsize=(10.5, 6))
x = np.arange(len(depts))
w = 0.38
b1 = ax.bar(x - w/2, rate_2025, w, label='2025 实际出勤率', color=C2025, zorder=3)
b2 = ax.bar(x + w/2, rate_2026, w, label='2026 实际出勤率', color=C2026, zorder=3)
for rect in list(b1) + list(b2):
    h = rect.get_height()
    ax.annotate(f'{h}%', (rect.get_x() + rect.get_width()/2, h),
                xytext=(0, 4), textcoords='offset points',
                ha='center', va='bottom', fontsize=10, color='#333333', fontweight='bold')
ax.set_xticks(x)
ax.set_xticklabels(depts, fontsize=11)
ax.set_ylim(0, 120)
ax.set_ylabel('实际出勤率 (%)', fontsize=11)
ax.set_title('各部门实际出勤率对比（2025 vs 2026）', fontsize=15, fontweight='bold', pad=14)
ax.legend(frameon=False, fontsize=11, loc='upper right')
style_ax(ax)
fig.tight_layout()
fig.savefig('01_出勤率对比.png', dpi=160, bbox_inches='tight')
plt.close(fig)

# ============ 图2：出勤率提升幅度排行 ============
order = np.argsort(improve)  # 升序 -> 横向条形从下到上
d_sorted = [depts[i] for i in order]
im_sorted = [improve[i] for i in order]
colors = ['#0E7490' if v >= 30 else '#B6C2CC' for v in im_sorted]
fig, ax = plt.subplots(figsize=(9.5, 5.5))
bars = ax.barh(range(len(d_sorted)), im_sorted, color=colors, zorder=3, height=0.62)
for i, v in enumerate(im_sorted):
    ax.annotate(f'+{v}%', (v, i), xytext=(6, 0), textcoords='offset points',
                va='center', fontsize=11, fontweight='bold', color='#333333')
ax.set_yticks(range(len(d_sorted)))
ax.set_yticklabels(d_sorted, fontsize=11)
ax.set_xlim(0, max(im_sorted) * 1.18)
ax.set_xlabel('出勤率提升幅度 (百分点)', fontsize=11)
ax.set_title('各部门出勤率提升幅度排行（2026 vs 2025）', fontsize=15, fontweight='bold', pad=14)
style_ax(ax)
ax.xaxis.grid(True, color='#EEEEEE', linewidth=0.8)
fig.tight_layout()
fig.savefig('02_出勤率提升幅度.png', dpi=160, bbox_inches='tight')
plt.close(fig)

# ============ 图3：2026 应出勤 vs 实际出勤 ============
fig, ax = plt.subplots(figsize=(10.5, 6))
x = np.arange(len(depts))
b1 = ax.bar(x - w/2, due_2026, w, label='2026 应出勤(次)', color='#D8DEE4', zorder=3)
b2 = ax.bar(x + w/2, act_2026, w, label='2026 实际出勤(次)', color=C2026, zorder=3)
for rect in list(b1) + list(b2):
    h = rect.get_height()
    ax.annotate(f'{int(h)}', (rect.get_x() + rect.get_width()/2, h),
                xytext=(0, 4), textcoords='offset points',
                ha='center', va='bottom', fontsize=10, color='#333333', fontweight='bold')
ax.set_xticks(x)
ax.set_xticklabels(depts, fontsize=11)
ax.set_ylim(0, max(due_2026) * 1.18)
ax.set_ylabel('出勤次数 (次)', fontsize=11)
ax.set_title('各部门 2026 年应出勤 vs 实际出勤', fontsize=15, fontweight='bold', pad=14)
ax.legend(frameon=False, fontsize=11, loc='upper right')
style_ax(ax)
fig.tight_layout()
fig.savefig('03_应出勤vs实际出勤.png', dpi=160, bbox_inches='tight')
plt.close(fig)

# ============ 图4：满意度环形图 ============
fig, ax = plt.subplots(figsize=(7.5, 6.5))
vals = [95, 5]
labels = ['收获显著 95%', '没有收获 5%']
colors = ['#0E7490', '#D8DEE4']
wedges, _ = ax.pie(vals, colors=colors, startangle=90, counterclock=False,
                   wedgeprops=dict(width=0.42, edgecolor='white', linewidth=2))
ax.text(0, 0.06, '100%', ha='center', va='center', fontsize=26, fontweight='bold', color='#0E7490')
ax.text(0, -0.16, '整体培训满意度', ha='center', va='center', fontsize=12, color='#555555')
ax.legend(wedges, labels, loc='lower center', bbox_to_anchor=(0.5, -0.12),
          ncol=2, frameon=False, fontsize=11)
ax.set_title('学员满意度调查（回收问卷 19 份）', fontsize=15, fontweight='bold', pad=14)
fig.tight_layout()
fig.savefig('04_满意度分析.png', dpi=160, bbox_inches='tight')
plt.close(fig)

print("DONE: 4 charts generated")
