# paint/box_plot.py
import matplotlib.pyplot as plt
import numpy as np


def box_plot(data_list=None, labels=None, title="Box Plot",
             ylabel="Value", colors=None, show_mean=False,
             show_points=False, horizontal=False):
    """
    绘制箱线图

    参数:
    data_list: 数据列表（每个元素是一个数据集）
    labels: 数据集标签
    title: 图表标题
    ylabel: Y轴标签
    colors: 颜色列表
    show_mean: 是否显示均值
    show_points: 是否显示数据点
    horizontal: 是否水平显示
    """
    fig, ax = plt.subplots(figsize=(10, 6))

    # 生成默认数据
    if data_list is None:
        np.random.seed(42)
        data_list = [
            np.random.normal(0, 1, 100),
            np.random.normal(2, 1.5, 100),
            np.random.normal(-1, 0.5, 100),
            np.random.normal(3, 2, 100)
        ]
        labels = ['Group A', 'Group B', 'Group C', 'Group D']

    # 设置默认颜色
    if colors is None:
        colors = plt.cm.Set2(np.linspace(0, 1, len(data_list)))

    # 绘制箱线图
    bp = ax.boxplot(data_list, labels=labels, patch_artist=True,
                    showmeans=show_mean, showfliers=show_points,
                    vert=not horizontal)

    # 设置箱子颜色
    for patch, color in zip(bp['boxes'], colors):
        patch.set_facecolor(color)
        patch.set_alpha(0.7)

    # 设置其他元素颜色
    for element in ['whiskers', 'caps', 'medians']:
        for line in bp[element]:
            line.set_color('black')
            line.set_linewidth(1.5)

    # 设置均值点
    if show_mean:
        for mean_line in bp['means']:
            mean_line.set_color('red')
            mean_line.set_linewidth(2)

    # 设置图表属性
    ax.set_title(title, fontsize=14, fontweight='bold', pad=20)
    ax.set_ylabel(ylabel, fontsize=12)

    if horizontal:
        ax.set_xlabel(ylabel, fontsize=12)
        ax.set_ylabel('Groups', fontsize=12)

    ax.grid(True, linestyle='--', alpha=0.3, axis='y' if not horizontal else 'x')

    plt.tight_layout()
    return fig, ax, bp