
# 将不同时间的swap 合并在一起 分析他们的变化 找出庄家地址/分析庄家变化 
import pandas as pd
import sys
import os
import datetime
import pytz
from openpyxl.styles import *
# from openpyxl.styles.colors import RED, GREEN
arr_file = []
merged_df = None
 
def makeurl( url,url_show):
    return '=HYPERLINK("{}","{}")'.format(url,  url_show)

def get_nowdate():

    timestamp = datetime.datetime.now().timestamp()
    # print(timestamp)
    dt = datetime.datetime.fromtimestamp(timestamp)
    tz = pytz.timezone('Asia/Shanghai')
    normal_time_str = dt.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S')
    time_str = dt.astimezone(tz).strftime('%m%d%H%M')
    return time_str

def utc_2_shanghaidate(df , utc_time_col ):
# 将字符串转换为UTC时间的datetime对象
    df['shanghai_date'] = pd.to_datetime(df[utc_time_col], utc=True)

    # 定义UTC+8时区
    utc_plus_8 = pytz.timezone('Asia/Shanghai')
    # 转换为UTC+8时间
    df['shanghai_date'] = df['shanghai_date'].dt.tz_convert(utc_plus_8)
    # 提取时间字符串
    df['shanghai_date'] = df['shanghai_date'].dt.strftime('%Y-%m-%d %H:%M')

    print(df)
 

 
def merge_swap_df_fun_01():    
    global merged_swap_toal_info_file
    # style = pd.DataFrame().style
    global arr_file , merged_df , token_add
    for index, file in enumerate(arr_file):
        date_range = file.replace(".csv","").split("_")
        date_range = date_range[-2]+"_"+date_range[-1]

        cur_df =   pd.read_csv(file ,dtype=object)
        cur_df=cur_df.dropna(subset=['swap_trader_id'])
        cur_df =cur_df.astype({
            "li_lun_hold":float,
            "token_b_M":float,
            "token_s_M":float,
            "eth_b":float,
            "eth_s":float,
            "b_count":float,
            "s_count":float,
            "avg_b_mc":float,
            "avg_s_mc":float
        })


         
        chaged_cols = [f"{col}_{date_range}" for col in cur_df.columns  ]
        chaged_cols[0] = "swap_trader_id"
        cur_df.columns = chaged_cols

        if index==0 :
            merged_df = cur_df
            continue
        merged_df = pd.merge(merged_df, cur_df, on='swap_trader_id', how='outer')
        
    merged_df["gmgn"] = merged_df.apply(lambda ser: makeurl(
    f"https://gmgn.ai/sol/token/{token_add}?tab=activity&maker={ser['swap_trader_id']}" , "gmgn" ), axis=1)
    merged_df["defined"] = merged_df.apply(lambda ser: makeurl(
     f"https://www.defined.fi/sol/{token_add}?maker={ser['swap_trader_id']}" , "defined" ), axis=1)
    merged_df["beizhu"] = None
    
 
    
    merged_swap_toal_info_file = f"002_merge_swap_total_info_{get_nowdate()}.xlsx"
    merged_df.to_excel(merged_swap_toal_info_file ,index=False)
    
    
    
# https://www.w3schools.com/colors/colors_hex.asp    
yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')  # 黄色填充


IndianRed_fill = PatternFill(start_color='CD5C5C', end_color='CD5C5C', fill_type='solid')  # 黄色填充
LightCoralRed_fill = PatternFill(start_color='F08080', end_color='F08080', fill_type='solid')  # 黄色填充


MediumSpringGreen_fill = PatternFill(start_color='00FA9A', end_color='00FA9A', fill_type='solid')  #  
ForestGreen_fill = PatternFill(start_color='228B22', end_color='228B22', fill_type='solid')  #  
SeaGreen_fill = PatternFill(start_color='2E8B57', end_color='2E8B57', fill_type='solid')  #  

Orange_fill = PatternFill(start_color='FFA500', end_color='FFA500', fill_type='solid')  #  



merged_swap_toal_info_file = ""
def merge_swap_df_fun_02():
    global merged_swap_toal_info_file
    # merged_hodlers_excel = pd.ExcelFile(merged_swap_toal_info_file)
    # arr_sheet_names = list(merged_hodlers_excel.sheet_names)
    # arr_sheet_names.pop(0)
    
    
    arr_df = []
    arr_df.append(merged_df)
    

    with pd.ExcelWriter(merged_swap_toal_info_file) as writer:
        for idx ,cur_df in enumerate(arr_df):
            sheet_name = ''

            if idx==0:
                sheet_name = 'Sheet1'

            cur_df.to_excel(writer, sheet_name=sheet_name, index=False)
            worksheet = writer.sheets[sheet_name]


# pandas 和 openpyxl 如何获取某一列的名字 ，然后对指定列填充颜色
                # 应用填充颜色到指定单元格范围（例如：A2:A4）
            # target_column = 'swap_trader_id'
            arr_col_buy_mc = [col for col in cur_df.columns if 'avg_b_mc' in col  ]
            arr_col_sell_mc = [col for col in cur_df.columns if 'avg_s_mc' in col  ]
            arr_col_li_lun_hold = [col for col in cur_df.columns if 'li_lun_hold' in col  ]
            arr_col_token_b = [col for col in cur_df.columns if 'token_b_M' in col  ]
            arr_col_token_s = [col for col in cur_df.columns if 'token_s_M' in col  ]


            for target_column  in arr_col_buy_mc:
                column_index = cur_df.columns.get_loc(target_column) + 1  # +1 转换为 Excel 列索引
                for row in range(2, len(cur_df) + 2):  # 从第2行到最后一行
                    cell =  worksheet.cell(row=row, column=column_index)
                    cell.fill = MediumSpringGreen_fill
            for target_column  in arr_col_token_b:
                column_index = cur_df.columns.get_loc(target_column) + 1  # +1 转换为 Excel 列索引
                for row in range(2, len(cur_df) + 2):  # 从第2行到最后一行
                    cell =  worksheet.cell(row=row, column=column_index)
                    cell.fill = ForestGreen_fill
 
            for target_column  in arr_col_sell_mc:
                column_index = cur_df.columns.get_loc(target_column) + 1  # +1 转换为 Excel 列索引
                for row in range(2, len(cur_df) + 2):  # 从第2行到最后一行
                    cell =  worksheet.cell(row=row, column=column_index)
                    cell.fill = IndianRed_fill

            for target_column  in arr_col_token_s:
                column_index = cur_df.columns.get_loc(target_column) + 1  # +1 转换为 Excel 列索引
                for row in range(2, len(cur_df) + 2):  # 从第2行到最后一行
                    cell =  worksheet.cell(row=row, column=column_index)
                    cell.fill = LightCoralRed_fill

            for target_column  in arr_col_li_lun_hold:
                column_index = cur_df.columns.get_loc(target_column) + 1  # +1 转换为 Excel 列索引
                for row in range(2, len(cur_df) + 2):  # 从第2行到最后一行
                    cell =  worksheet.cell(row=row, column=column_index)
                    cell.fill = Orange_fill





token_add = "2ZoJVM15fbbDgo6s5cTTX2Sj8V4sJ47rimb7gQhGpump"

if __name__ == "__main__":
 
    arr_file = os.listdir()
    
    arr_file = [file for file in arr_file if   file.startswith( "dune_swap_total_info_xx")  and file.endswith(".csv")]
    arr_file.sort()
    print("read file: ",arr_file)
    merge_swap_df_fun_01()
    merge_swap_df_fun_02()
