
# 去除每个token的前两次购买 计算利润
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)


baseclass.makedirpath(baseclass.new_dalao_ana_fm_path)

baseclass.open_base_library()
decimal.getcontext().prec = 100
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---------------")


batchSize = 5
token_TotalAnalysis_list = []

token_TotalAnalysis_list_columns = [
    "tokenadd",

    "beizhu",

    "cost_main",
    "earn_main",
    "earn_percent",
    "nofir_cost_main",
    "nofir_earn_main",
    "nofir_earn_percent",
    "dalao_counts",
    "dalaofirsttimestamp",


]


df = pd.read_excel(baseclass.dalao_total_ana_fm_path /
                   f"total_dalao_profit_df_3dalao.xlsx", dtype=object)
df['datetime'] = pd.to_datetime(
    df['datetime'])

df = df.astype({
    'buy_counts': int,
    'sell_counts': int,
    'swap_eth_amount': float,
    'outtoken_per': float,
    'cost_main': float,
    'earn_main': float,
    'earn_percent': float
})

# df = df[df["outtoken_per"] <= 1.1].reset_index(drop=True)
df = df[df['cost_main'] != 0].reset_index(drop=True)


def get_droptime_0102time_df(gdf):
    # 去除前两次购买
    gdf = gdf[gdf["dalaofirsttimestamp"] > gdf["dalaofirsttimestamp"].min()]
    gdf = gdf[gdf["dalaofirsttimestamp"] > gdf["dalaofirsttimestamp"].min()]
    return gdf


dropfirsttime_df = df.groupby(['swap_tokenaddress']).apply(
    lambda gdf: get_droptime_0102time_df(gdf)).reset_index(drop=True)

dropfirsttime_df = dropfirsttime_df.sort_values(
    by=['swap_tokenaddress', 'dalaofirsttimestamp', 'dalaoaddress', 'timestamp'])

# TotalAnalysis_list.append(analist)
# ["cost_main",	"earn_main", "earn_percent",	"dalaoaddress", "dalaofirsttimestamp"]

df = df[["swap_tokenaddress", "cost_main",	"earn_main", "earn_percent",	"dalaoaddress",
         "dalaofirsttimestamp"]].drop_duplicates().reset_index(drop=True)

dropfirsttime_df = dropfirsttime_df[["swap_tokenaddress", "cost_main",	"earn_main", "earn_percent",
                                     "dalaoaddress", "dalaofirsttimestamp"]].drop_duplicates().reset_index(drop=True)


arr_str_tokenaddress = df["swap_tokenaddress"].drop_duplicates().tolist()

print(f"arr_str_tokenaddress len= {len(arr_str_tokenaddress)}")
# obj_repeattoken_2_arrdalao = {

# }
for str_tokenaddress in arr_str_tokenaddress:
    cur_df = df[df["swap_tokenaddress"] ==
                str_tokenaddress].reset_index(drop=True)
    cur_dropfirsttime_df = dropfirsttime_df[dropfirsttime_df["swap_tokenaddress"]
                                            == str_tokenaddress].reset_index(drop=True)
    number_dalao_counts = len(cur_df)

    # obj_repeattoken_2_arrdalao[str_tokenaddress] = cur_df["dalaoaddress"].drop_duplicates(
    # ).tolist()

    number_sum_cost_main = cur_df["cost_main"].sum()
    number_sum_earn_main = cur_df["earn_main"].sum()
    number_earn_percent = number_sum_earn_main/number_sum_cost_main
    number_dalaofirsttimestamp = cur_df["dalaofirsttimestamp"].min()

    number_sum_nofir_cost_main = cur_dropfirsttime_df["cost_main"].sum()
    number_sum_nofir_earn_main = cur_dropfirsttime_df["earn_main"].sum()
    # 理论上肯定会有一个dalao的交易记录 不会出现number_sum_nofir_cost_main=0
    # 但是如果多个dalao在都是firsttime 购买了 就可能出现 number_sum_nofir_cost_main=0
    number_nofir_earn_percent = number_sum_nofir_earn_main/number_sum_nofir_cost_main

    cur_arr_ana = [
        str_tokenaddress,
        "",
        number_sum_cost_main,
        number_sum_earn_main,
        number_earn_percent,
        number_sum_nofir_cost_main,
        number_sum_nofir_earn_main,
        number_nofir_earn_percent,
        number_dalao_counts,
        number_dalaofirsttimestamp
    ]
    token_TotalAnalysis_list.append(cur_arr_ana)


token_TotalAnalysis_df = pd.DataFrame(
    data=token_TotalAnalysis_list, columns=token_TotalAnalysis_list_columns
)

token_TotalAnalysis_df = token_TotalAnalysis_df.round(4)
token_TotalAnalysis_df = token_TotalAnalysis_df.sort_values(by=["tokenadd"], ascending=[
    True]).reset_index(drop=True)


def makescreenurl(urlname, urlparam):
    # pairAddress = series[address_str]
    urlname = urlname + urlparam
    return '=HYPERLINK("{}","{}")'.format(urlname, urlname)


token_TotalAnalysis_df.insert(
    loc=2, column="DexScreenURL", value="")

token_TotalAnalysis_df['DexScreenURL'] = token_TotalAnalysis_df.apply(lambda ser: makescreenurl(
    "https://dexscreener.com/solana/", f"{ser['tokenadd']}"), axis=1)


token_TotalAnalysis_df.to_excel(
    baseclass.dalao_total_ana_fm_path/f"token_TotalAnalysis_3dalao.xlsx", index=False)


print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
