
# 将不同时间的swap 合并在一起 分析他们的变化 找出庄家地址/分析庄家变化 
import pandas as pd
import sys

import datetime
import pytz
from openpyxl.styles import *
# from openpyxl.styles.colors import RED, GREEN
arr_file = []
merged_df = None
 
token_add = ""

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():    
    # style = pd.DataFrame().style
    global arr_file , merged_df , domains_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_pri":float,
            "avg_s_pri":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.to_excel( f"merge_swap_{get_nowdate()}.xlsx",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_hodlers_file = ""
def merge_swap_df_fun_02():
    global merged_hodlers_file
    merged_hodlers_excel = pd.ExcelFile(merged_hodlers_file)
    arr_sheet_names = list(merged_hodlers_excel.sheet_names)
    arr_sheet_names.pop(0)
    
    
    arr_df = []
    arr_df.append(merged_df)
    
    for sheet_name in arr_sheet_names:
        holder_df = merged_hodlers_excel.parse(sheet_name=sheet_name)
        cur_df = merged_df[  merged_df['swap_trader_id'].isin(holder_df['holder_owner'])].reset_index(drop=True)

        # https://geek-docs.com/pandas/pandas-questions/214_pandas_coloring_cells_in_excel_with_pandas.html
        # 上色
# https://geek-docs.com/pandas/pandas-questions/214_pandas_coloring_cells_in_excel_with_pandas.html#google_vignette
        cur_df = cur_df.set_index('swap_trader_id').reindex(holder_df['holder_owner']).reset_index()

        arr_df.append(cur_df)   
    time_str = get_nowdate()


    with pd.ExcelWriter(f'merge_swap_{time_str}.xlsx') as writer:
        for idx ,cur_df in enumerate(arr_df):
            sheet_name = ''

            if idx==0:
                sheet_name = 'Sheet1'
            else:
                sheet_name = arr_sheet_names[idx-1]
            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_pri = [col for col in cur_df.columns if 'avg_b_pri' in col  ]
            arr_col_sell_pri = [col for col in cur_df.columns if 'avg_s_pri' 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_pri:
                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_pri:
                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



def makeurl( url,url_show):
    return '=HYPERLINK("{}","{}")'.format(url,  url_show)

if __name__ == "__main__":
    if len(sys.argv)<3:
        print("args queshao ")
        sys.exit(1)
    # token_add = sys.argv[1]
    merged_hodlers_file = sys.argv[1]
    arr_file =sys.argv[2:]
    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()
