import dash
from dash import dcc, html
import plotly.graph_objects as go

# 假设你的节点标签是长度为30的字符串
labels = [f"Label{i:030}" for i in range(1, 8)]  # 生成示例标签

# 数据准备
data = {
    'source': [0, 1, 2, 0],
    'target': [3, 4, 5, 6],
    'value': [10, 15, 5, 20]
}

# 创建Sankey图
def create_sankey():
    fig = go.Figure(data=[go.Sankey(
        node=dict(
            label=[label[:5] + "..." for label in labels],  # 显示前5个字符加省略号
            pad=15,
            thickness=20,
            line=dict(color="black", width=0.5),
            hoverinfo="all",  # 在悬停时显示标签和值
            customdata=labels , # 添加完整的标签作为自定义数据
            hovertemplate = '%{label}<br>Full Label: %{customdata}<br>Value: %{value}<br>',
        ),
        link=dict(
            source=data['source'],
            target=data['target'],
            value=data['value'],
        )
    )])

    # 设置悬停模板以显示完整的节点标签
    # fig['data'][0]['node']['hovertemplate'] = '%{label}<br>Full Label: %{customdata}<br>Value: %{value}<br>'

    fig.update_layout(title_text="Sankey Diagram with Abbreviated Node Labels", font_size=10)
    return fig

# 创建 Dash 应用
app = dash.Dash(__name__)

# 定义应用布局
app.layout = html.Div([
    dcc.Graph(id='sankey', figure=create_sankey())
])

# 运行应用
if __name__ == '__main__':
    app.run_server(debug=True)
