import json
import os
import re
import ast
import sys
import time
import logging
import traceback
import threading
import zlib
import pandas as pd
import numpy as np
import redis
from datetime import datetime
sys.path.append("/opt/module/spark-3.2.0-bin-hadoop3.2/demo/py_demo/")
sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from sqlalchemy import create_engine
from sqlalchemy.exc import PendingRollbackError
from utils.templates import Templates
# from ..utils.templates import Templates
from utils.templates_mysql import TemplatesMysql
# from ..utils.templates_mysql import TemplatesMysql
from pyspark.sql.types import IntegerType
from pyspark.sql import functions as F
from pyspark.sql.types import *
from utils.mysql_db import sql_connect, sql_update_many, sql_delete, get_country_engine
from pyspark.sql import SparkSession


class SpiderAsinSearch(Templates):

    def __init__(self, site_name='us', date_type='week', date_info='2023-11-16', consumer_type='lastest', batch_size=100000):
        super(SpiderAsinSearch, self).__init__()
        self.site_name = site_name
        self.date_info = date_info
        self.consumer_type = consumer_type  # 消费实时还是消费历史
        self.date_type = date_type
        # 通过date_type 获取 topic
        self.get_topic_name()
        # 通过date_type 获取 schema
        self.init_schema()
        # self.topic_name = topic_name  # 主题名字
        self.batch_size = batch_size
        self.batch_size_history = int(batch_size / 10)
        self.db_save = f'spider_asin_search'
        # self.spark = self.create_spark_object(
        #     app_name=f"{self.db_save}: {self.site_name},{self.date_type}, {self.date_info}, {self.consumer_type}")
        self.app_name = self.get_app_name()
        self.spark = self.create_spark_object(app_name=f"{self.app_name}")
        # self.schema = self.init_schema()

        # 连接mysql
        self.engine = get_country_engine(self.site_name)
        self.pg14_engine = self.get_14pg_country_engine(self.site_name)
        sql_connect(self.site_name)
        logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s %(message)s',
                            level=logging.INFO)
        # 爬虫类型--流程表
        self.spider_type = "反查搜索词"

    def judge_spider_asin_detail_is_finished(self):
        while True:
            try:
                sql = f'SELECT * from selection.workflow_progress WHERE page="反查搜索词" and site_name="{self.site_name}" and date_type="{self.date_type}" and date_info="{self.date_info}" and status_val=3'
                df = pd.read_sql(sql, con=self.engine)
                if df.shape[0] == 1:
                    print(f"ASIN详情状态为3, 抓取完成并终止程序, site_name:{self.site_name}, date_type:{self.date_type}, date_info:{self.date_info}")
                    self.spark.stop()
                    quit()  # 退出程序
                break
            except Exception as e:
                print(e, traceback.format_exc())
                time.sleep(10)
                self.engine = self.get_connection()

    def init_schema(self):
        self.schema = StructType([
            StructField("cate_type", StringType(), True),
            StructField("data_list", StringType(), True),
            StructField("date_info", StringType(), True),
            StructField("spider_time", StringType(), True),
        ])
        # self.col = ['search_term', 'asin', 'page', 'buy_data', 'label']

    @staticmethod
    def clean_kafka_df(df):
        df = df.withColumnRenamed("seller_id", "account_id")
        # cols_python = ["asin", "parentAsin", "variat_num", "best_sellers_rank", "best_sellers_herf", "price", "rating",
        #         "brand", "brand", "account_id", "account_name", "account_url", "buy_box_seller_type",
        #         "volume", "weight", "weight_str", "launchTime", "total_comments", "page_inventory"]
        # oneCategoryRank, aoVal, bsrOrders, bsrOrdersSale
        # siteName volumeFormat weightFormat asinUpdateTime
        # java那边插件的字段名称
        cols_java = ['asin', 'parentAsin', 'asinVarNum', 'oneCategoryRank', 'bestSellersRank', 'lastHerf', 'aoVal', 'price', 'rating',
                    'bsrOrders', 'bsrOrdersSale', 'brandName', 'accountId', 'accountName', 'accountUrl', 'siteName', 'buyBoxSellerType',
                    'volume', 'volumeFormat', 'weight', 'weightFormat', 'launchTime', 'totalComments', 'pageInventory', 'asinUpdateTime']
        df = df.select("asin", "parentAsin", "variat_num", "best_sellers_rank", "best_sellers_herf", "price", "rating",
                        "brand", "account_id", "account_name", "account_url", "buy_box_seller_type",
                        "volume", "weight", "weight_str", "launch_time", "total_comments", "page_inventory", "asinUpdateTime", "site_name", "node_id")
        return df

    def get_topic_name(self):
        if self.date_type == "week":
            self.topic_name = f"{self.site_name}_search_term_rank_type"
        elif self.date_type == "month":
            self.topic_name = f"{self.site_name}_search_term_month_{self.date_info.replace('-', '_')}"
        else:
            logging.info("self.date_type error -----")
            quit()

    def get_14pg_country_engine(self, site_name="us"):
        h14_pg_us = {
            "user": "postgres",
            "password": "F9kL2sXe81rZq",
            # "host": "61.145.136.61",
            "host": "192.168.10.223",
            "port": "5432",
            # "port": 54328,
            "database": "selection",
        }
        if site_name == 'us' or site_name == 'mx' or site_name == 'ca':
            h14_pg_us["database"] = f"selection"
            db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h14_pg_us.values())
        else:
            h14_pg_us["database"] = f"selection_{site_name}"
            db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h14_pg_us.values())
        engine = create_engine(db_, encoding='utf-8')  # , pool_recycle=3600
        return engine

    def cate_type(self, cate_type, df):
        if cate_type in ["sp", "zr"]:
            df = df.loc[:, ['search_term', 'asin', 'page', 'page_row','date_info', 'created_time']]
            df.drop_duplicates(['search_term', 'asin', 'page', 'page_row'], inplace=True)
            return df
        elif cate_type in ['buy']:
            df = df.loc[:, ['search_term', 'asin', 'page', 'buy_data', 'date_info', 'label', 'created_time']]
            df.drop_duplicates(['search_term', 'asin', 'page', 'buy_data', 'label'], inplace=True)
            return df
        else:
            if cate_type in ['sb', 'tr']:
                df = df.loc[:, ['search_term', 'asin', 'page', 'cate_type', 'date_info', 'created_time']]
                df.rename(columns={"cate_type": "data_type"}, inplace=True)
                df.drop_duplicates(['search_term', 'asin', 'page', 'data_type'], inplace=True)
                return df
            elif cate_type in ['buy']:
                df = df.loc[:, ['search_term', 'asin', 'page', 'buy_data', 'date_info', 'label', 'created_time']]
                df.drop_duplicates(['search_term', 'asin', 'page', 'buy_data', 'label'], inplace=True)
                return df
            else:
                df = df.loc[:, ['search_term', 'asin', 'page', 'date_info', 'created_time']]
                df.drop_duplicates(['search_term', 'asin', 'page'], inplace=True)
                return df

    def add_column_to_list(self, row):
        l = []
        for sub_list in json.loads(row['data_list']):
            l.append(sub_list + [row["spider_time"]])
        return l

    def save_data_common(self, name, group):
        logging.info(f"name: {name}")
        search_exploded_list = group['data_list'].explode()
        # 展开后转换为一个大列表
        search_list = [i for i in search_exploded_list.tolist() if not isinstance(i, float)]
        if search_list:
            logging.info(f"搜索词处理{search_list[0:5]}")
            # 列表等分
            # self.list_svg(search_list, chunk_size=100)
            # 转换为df对象
            if name[0] in ['buy']:
                # 将数据转换为df对象
                df_1 = pd.DataFrame(data=search_list, columns=['search_term', 'asin', 'page', 'buy_data', 'label', 'created_time'])
            else:
                # if self.date_type == "week":
                #     # 将数据转换为df对象
                df_1 = pd.DataFrame(data=search_list, columns=['search_term', 'asin', 'page', 'page_row',
                                                               'cate_type', 'title', 'img_url', 'price', 'rating',
                                                               'total_comments', 'created_time'])
                # else:
                #     # 将数据转换为df对象
                #     df_1 = pd.DataFrame(data=search_list, columns=['search_term', 'asin', 'page', 'page_row',
                #                                                    'data_type', 'title', 'img_url', 'price', 'rating',
                #                                                    'total_comments', 'created_time'])
            # 获取date_info
            df_1['date_info'] = name[1]
            # 通过类别对对应数据字段进行清洗
            new_df = self.cate_type(name[0], df_1)
            logging.info(f"{name} {new_df.shape} \n  {new_df.keys()}   {new_df.head()}")
            # 通过站点 类别 和date_info 拼接表名
            if name[0] == "buy":
                if self.date_type == 'month':
                    table_name = f"{self.site_name}_other_search_term_month_{name[1].replace('-', '_')}"
                else:
                    table_name = f"{self.site_name}_other_search_term_{name[1].replace('-', '_')}"
            else:
                if self.date_type == 'month':
                    table_name = f"{self.site_name}_search_term_rank_{name[0]}_month_{name[1].replace('-', '_')}"
                else:
                    table_name = f"{self.site_name}_search_term_rank_{name[0]}_{name[1].replace('-', '_')}"
            while True:
                try:
                    start_time = time.time()
                    new_df.to_sql(name=f'{table_name}', con=self.pg14_engine, if_exists='append', index=False)
                    end_time = time.time()
                    logging.info(f"入库 {table_name} 表 {new_df.shape} {new_df.head(10)} 成功, 耗时：{end_time - start_time}s")
                    break
                except PendingRollbackError as e:
                    time.sleep(3)
                    logging.info(f"error {e} sleep 3")
                    continue

    def save_data(self, df):
        threads = []
        # 将字符串类型改为 python list
        # df['data_list'] = df['data_list'].apply(json.loads)
        df["data_list"] = df.apply(self.add_column_to_list, axis=1)
        for name, group in df.groupby(['cate_type', 'date_info']):
            thread = threading.Thread(target=self.save_data_common, args=(name, group))
            threads.append(thread)
            thread.start()
        for thread in threads:
            thread.join()
        logging.info("线程处理完成")

    def data_save(self, df):
        if not isinstance(df, pd.DataFrame):
            logging.info("df 不是一个 DataFrame 对象 ")
            df = df.toPandas()
        if self.consumer_type != "latest":
            logging.info(f"过滤前： {df.shape}")
            df = df.loc[(~df.date_info.isna()) & (df.date_info == self.date_info)]
            logging.info(f"过滤后： {df.shape}")
        if self.date_type == "week":
            logging.info(f"周数据处理")
            if df.shape[0]:
                self.save_data(df)
        else:
            logging.info("处理month数据")
            if df.shape[0]:
                self.save_data(df)

    def handle_kafka_history(self, kafka_df):
        self.data_save(kafka_df)

    def handle_kafka_stream(self, kafka_df, epoch_id):
        print(type(kafka_df), kafka_df)
        count = kafka_df.count()
        print("当前批次传输的数据量为df.count():", count)
        if count == 0:
            print(f"当前批次{epoch_id}没有数据进来")
            self.judge_spider_asin_detail_is_finished()
        else:
            self.data_save(kafka_df)


if __name__ == '__main__':
    site_name = sys.argv[1]  # 参数1：站点
    date_type = sys.argv[2]  # 参数2：类型：week/4_week/month/quarter/day
    date_info = sys.argv[3]  # 参数3：年-周/年-月/年-季/年-月-日, 比如: 2022-1
    consumer_type = sys.argv[4]  # 参数3：实时 lastest 历史 history
    handle_obj = SpiderAsinSearch(site_name=site_name, date_type=date_type, date_info=date_info, consumer_type=consumer_type, batch_size=10000)
    handle_obj.run_kafka()


# for i in `ps -ef|grep "spider_asin_search" |awk '{print $2}' `; do kill -9 $i ; done;

# 历史
# /opt/module/spark/bin/spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.3 --master yarn --driver-memory 2g --executor-memory 20g --executor-cores 4 --num-executors 2 --queue spark /opt/module/spark/demo/py_demo/my_kafka/spider_asin_search.py it week 2023-49 history > amazon_history_search_it.log 2>&1 &
# 实时
# /opt/module/spark/bin/spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.3 --master yarn --driver-memory 2g --executor-memory 2g --executor-cores 4 --num-executors 2 --queue spark /opt/module/spark/demo/py_demo/my_kafka/spider_asin_search.py it week 2023-49 latest > amazon_latest_search_it.log 2>&1 &