 

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


from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)

old_print = print
 

def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)

 

print = timestamped_print
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

 
 
str_tokenaddress="4GULMPKBJLruChBZWksZzukAg1AjSCmCTMn9ny2Xpump"
str_dalaoaddress ='EeS7DBots7zF7JA4iCPun1uA779aXCPCBhe4kGkuCuRA'
 
# str_dalaoaddress ='total'

df = pd.read_excel(baseclass.dune_token_graph_path/ str_tokenaddress/f"{str_dalaoaddress}.xlsx", dtype=object)

df =df[["amount" ,"from_owner",	"to_owner" , "owner_count"]].reset_index(drop=True)
df =df.astype({
    "amount":float,
    "owner_count":int
    
})
def merge_gdf_has_mul_ata(gdf):
    if len(gdf)==1:
        return gdf
    
    gdf["amount"] = gdf["amount"].sum()
    gdf["owner_count"] = gdf["owner_count"].sum()
    gdf =gdf.drop_duplicates()
    return gdf

df = df.groupby(by=["from_owner","to_owner"], group_keys=False).apply(
    lambda gdf: merge_gdf_has_mul_ata(gdf))

 

# 创建 Sankey 图
def create_sankey(df):
    labels = list(set(df['from_owner'].tolist() + df['to_owner'].tolist()))
  
    # 获取source和target的索引
    source_indices  = [labels.index(src) for src in df['from_owner'].tolist()]
    target_indices  = [labels.index(tgt) for tgt in df['to_owner'].tolist()]

    fig = go.Figure(data=[go.Sankey(
    node=dict(
               pad=20,
        thickness=15,
        line=dict(color="black", width=0.5),
        label =[ item[0:6] for item in labels],
             hoverinfo="all",  # 在悬停时显示标签和值
             customdata= [{"dalao_address":label,"count":99} for  label in labels] , # 添加完整的标签作为自定义数据
             hovertemplate = '%{label}<br>node: %{customdata.dalao_address}  <br>Value: %{value}<br>',

    ),
    link=dict(
          source = source_indices ,
          target =target_indices,
          value = df['amount'].tolist(),
          label  = labels,
        hovertemplate='Amount: %{value}<br>From: %{source.label}<br>To: %{target.label}<extra></extra>'  # 自定义悬停模板
       
   
    ))])
    # fig.update_layout(
    #     width=2000,  # 增加图表宽度
    #     height=1200,  # 增加图表高度
    #     font=dict(size=10, color="black")  # 调整字体大小和颜色
    # )


    return fig

# 初始化 Dash 应用
app = dash.Dash(__name__)
fig = create_sankey(df)
 
# 定义应用布局
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

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