import sys
import os

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from utils.db_connect import BaseUtils
import time
import pandas as pd

"""bsr分类 拆分，。"""
class BsCateDetail(BaseUtils):
    def __init__(self, site_name='us'):
        super().__init__()
        self.site_name = site_name
        self.engine = self.mysql_connect()
        self.df_cate = pd.DataFrame()
        self.df_std = pd.DataFrame()
        self.df_std_save = pd.DataFrame()

    def db_read_data(self):
        sql = f"select * from {self.site_name}_bs_category;"
        self.df_cate = pd.read_sql(sql, con=self.engine)
        self.df_cate['cate_current_node'] = self.df_cate.nodes_num - 1
        print(self.df_cate.shape)

    def handle_data(self):
        node_list = list(set(self.df_cate.cate_current_node))
        node_list.remove(0)
        print("node_list:", node_list)
        cols_id_list = []
        for node in node_list:
            cols_id_list.extend((f"cate_{node}_id", f"cate_{node}_en_name"))
            df_node = self.df_cate.loc[self.df_cate.cate_current_node == node, ['id', 'p_id', 'en_name']]
            df_node.rename(
                columns={"id": f"cate_{node}_id", "p_id": f"cate_{node}_p_id", "en_name": f"cate_{node}_en_name"}, inplace=True)
            if node == 1:
                self.df_std = df_node
            else:
                self.df_std = self.df_std.merge(df_node, left_on=f"cate_{node - 1}_id", right_on=f"cate_{node}_p_id", how='left')
            print(node, df_node.shape)
        self.df_std_save = self.df_std.loc[:, cols_id_list]

    def db_save_data(self):
        with self.engine.begin() as conn:
            sql_truncate = f"truncate {self.site_name}_bs_category_detail;"
            conn.execute(sql_truncate)
        self.df_std_save.to_sql(f"{self.site_name}_bs_category_detail", con=self.engine, if_exists="append", index=False)

    def run(self):
        while True:
            try:
                self.db_read_data()
                self.handle_data()
                self.db_save_data()
                break
            except Exception as e:
                self.mysql_reconnect(table_name=f"{self.site_name}_bs_category", e=e)
                continue


if __name__ == '__main__':
    for site_name in ['us', 'uk', 'de', 'es', 'fr', 'it']:
        s_time = time.time()
        print("site_name:", site_name)
        handle_obj = BsCateDetail(site_name=site_name)
        handle_obj.run()
        print("程序总耗时：", time.time() - s_time)

