import time
import pandas as pd
from db.pg_db import get_pg_con


pg_engine = get_pg_con()


def get_asin_truncate():
    sql1 = f"select asin from us_asin_truncate;"
    df_truncate = pd.read_sql(sql1, con=pg_engine)
    return df_truncate


def get_asin_img_info():
    sql1 = f"select id, asin from us_asin_img_info;"
    df_img_info = pd.read_sql(sql1, con=pg_engine)
    return df_img_info


def update_state(datas):
    with pg_engine.begin() as connection:
        sql1 = f"UPDATE us_asin_img_info set state=3 WHERE asin in {datas};"
        connection.execute(sql1)
        connection.close()


asin_truncate = get_asin_truncate()

asin_img_info = get_asin_img_info()


# df1 = asin_img_info[asin_truncate['asin'].isin(asin_img_info["asin"])]

df1 = asin_img_info.merge(asin_truncate, on='asin', how='inner')

datas_list = df1.dropna()

del datas_list["id"]

datas = [list(i) for i in datas_list.values]

datas = list(*zip(*datas))

print(f"需要插入数{datas}")


def split_list_average_n(origin_list, n):
    for i in range(0, len(origin_list), n):
        yield origin_list[i:i + n]


b = split_list_average_n(datas, 1000)

# print(b.__next__())
error_list = []


for i in b:
    print("------")
    # print(i)
    try:
        stat_time = time.time()
        update_state(tuple(i))
        end_time = time.time()
        print(stat_time-end_time)
    except:
        print(f"修改失败 id {i}")
        error_list.append(tuple(i))

print(f"===={error_list}")
# if error_list:
#     for i in error_list:
#         update_state(tuple(i))

# nohup python pg_asin_img_status.py > asin_img_status.log 2>&1 &


