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


def bubble_chart(x_data=None, y_data=None, size_data=None,
                 color_data=None, labels=None, title="Bubble Chart",
                 xlabel="X", ylabel="Y", cmap='viridis',
                 alpha=0.6, edgecolors='black'):
    """
    绘制气泡图

    参数:
    x_data: X轴数据
    y_data: Y轴数据
    size_data: 气泡大小数据
    color_data: 气泡颜色数据
    labels: 气泡标签
    title: 图表标题
    xlabel: X轴标签
    ylabel: Y轴标签
    cmap: 颜色映射
    alpha: 透明度
    edgecolors: 边框颜色
    """
    fig, ax = plt.subplots(figsize=(10, 8))

    # 生成默认数据
    if x_data is None:
        np.random.seed(42)
        n_points = 30
        x_data = np.random.rand(n_points) * 100
        y_data = np.random.rand(n_points) * 100
        size_data = np.random.rand(n_points) * 1000
        color_data = np.random.rand(n_points)
        labels = [f'Point {i + 1}' for i in range(n_points)]

    # 归一化大小数据用于绘图
    if size_data is not None:
        size_normalized = (size_data - np.min(size_data)) / (np.max(size_data) - np.min(size_data))
        sizes = 50 + size_normalized * 500
    else:
        sizes = 100

    # 绘制气泡图
    scatter = ax.scatter(x_data, y_data, s=sizes,
                         c=color_data, cmap=cmap,
                         alpha=alpha, edgecolors=edgecolors,
                         linewidth=1)

    # 添加标签（可选）
    if labels:
        for i, label in enumerate(labels):
            ax.annotate(label, (x_data[i], y_data[i]),
                        xytext=(5, 5), textcoords='offset points',
                        fontsize=9, alpha=0.7)

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

    ax.grid(True, linestyle='--', alpha=0.5)

    # 添加颜色条（如果有颜色数据）
    if color_data is not None:
        cbar = fig.colorbar(scatter, ax=ax)
        cbar.set_label('Color Value', fontsize=10)

    # 添加图例表示气泡大小（可选）
    if size_data is not None:
        # 创建气泡大小示例
        min_size = np.min(size_data)
        max_size = np.max(size_data)
        median_size = np.median(size_data)

        legend_text = f'Bubble Size\nMin: {min_size:.1f}\nMed: {median_size:.1f}\nMax: {max_size:.1f}'
        props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
        ax.text(0.02, 0.98, legend_text, transform=ax.transAxes, fontsize=9,
                verticalalignment='top', bbox=props)

    plt.tight_layout()
    return fig, ax, scatter