from matplotlib import rcParams, pyplot as plt
from sqlalchemy import func
from orm import db_session, Sample

# 🔹 全局创建绘图对象
plt.ion()  # 启用交互模式
fig, ax = plt.subplots(figsize=(8, 5))
rcParams['font.family'] = 'Microsoft YaHei'
rcParams['font.size'] = 12

# 初始化柱状图
labels = ['未完成 (-1)', '计算中(0)', '完成 (1)']
initial_values = [0, 0, 0]
bars = ax.bar(labels, initial_values, color=['red', 'orange', 'green'])
value_texts = [ax.text(bar.get_x() + bar.get_width()/2, 0, '0',
                       ha='center', va='bottom', fontsize=12)
               for bar in bars]

ax.set_title('任务进度分布', fontsize=16)
ax.set_xlabel('任务状态', fontsize=14)
ax.set_ylabel('数量', fontsize=14)
ax.tick_params(axis='both', labelsize=12)

def visualize_progress():
    """
    实时更新 Sample 表中 is_done_flag 的分布。
    """
    # 查询数据库
    result = db_session.query(Sample.is_done_flag, func.count(Sample.id))\
                       .group_by(Sample.is_done_flag).all()
    data = {flag: count for flag, count in result}
    for flag in [-1, 0, 1]:
        data.setdefault(flag, 0)
    values = [data[-1], data[0], data[1]]

    # 更新柱子高度和文本
    for bar, new_val, txt in zip(bars, values, value_texts):
        bar.set_height(new_val)
        txt.set_y(new_val + 0.5)
        txt.set_text(str(new_val))

    plt.draw()
    plt.pause(0.1)  # 刷新图表
