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


def get_b_date():
    sql1 = f"select  asin,last_price,first_bsr_list,first_bsr_label  from us_keepa_trend_b07 where bsr_orders_list is null limit 1000;"
    df_keepa_trend = pd.read_sql(sql1, con=engine)
    return df_keepa_trend


engine = get_pg_con()

while True:
    keepa_trend = get_b_date()
    if keepa_trend.shape[0] > 0:
        datas = []
        for i in keepa_trend.values:
            asin = i[0]
            last_price = i[1]
            if i[2]:
                first_bsr_list = [int(j.strip()) for j in i[2].replace("[", "").replace("]", "").split(",") if
                                  j.strip() not in ["None", "null"]]
            else:
                print("first_bsr_list字段为空", i)
                datas.append((str([-1]), str([-1]), asin))
                continue
            first_bsr_lable = i[3]
            if asin and last_price > 0 and first_bsr_list and first_bsr_lable:
                if len(first_bsr_list) == 1:
                    sql = f"""SELECT orders,orders*{last_price} as "销售额",rank, name from us_one_category_report_2023_05  where name  = '{first_bsr_lable}'  and rank = '{first_bsr_list[0]}';"""
                else:
                    sql = f"""SELECT orders,orders*{last_price} as "销售额",rank, name from us_one_category_report_2023_05  where name  = '{first_bsr_lable}'  and rank in {tuple(first_bsr_list)};"""
                print("sql-------------", asin, sql)
                df_category_report = pd.read_sql(sql, con=engine)
                bsr_orders_list = list(df_category_report['orders'])
                bsr_orders_sale_list = list(df_category_report['销售额'])
                # print("=----", (str(bsr_orders_list or [-1]), str(bsr_orders_sale_list or [-1]), asin))
                datas.append((str(bsr_orders_list or [-1]), str(bsr_orders_sale_list or [-1]), asin))
            else:
                print("缺少字段")
                # print(i)
                if asin:
                    print((str([-1]), str([-1]), asin))
                    datas.append((str([-1]), str([-1]), asin))

        print(datas)




        # 连接到 PostgreSQL 数据库
        conn = psycopg2.connect(database="selection", user="postgres", password="fazAqRRVV9vDmwDNRNb593ht5TxYVrfTyHJSJ3BS", host="192.168.10.216", port="5432")

        # 创建游标对象
        cur = conn.cursor()

        # 定义更新语句
        update_query = """UPDATE us_keepa_trend_b07 SET bsr_orders_list = %s, bsr_orders_sale_list = %s WHERE asin = %s;"""

        print(update_query)
        # 执行更新语句
        cur.executemany(update_query, datas)

        # 提交事务
        conn.commit()

        # 关闭游标和数据库连接
        cur.close()
        conn.close()
    else:
        break