import time
import os, sys
import logging
import pandas as pd
from queue import Queue
# useful for handling different item types with a single interface
from func_timeout import func_set_timeout
from sqlalchemy.exc import OperationalError
from func_timeout.exceptions import FunctionTimedOut
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))  # 上级目录
from amazon_spider.utils.common import is_internet_available
from amazon_spider.db.mysql_db import df_to_sql, get_country_engine
from amazon_spider.db.pg_db import get_pg_country_engine, get_14pg_country_engine


class TemuBsrSpiderTextPipeline:
    def __init__(self, site):
        self.site = site
        self.q_dict = {
            "inner_item_queue": Queue(),
            "variat_item_queue": Queue(),
            "asin_img_queue": Queue(),
            "error_queue": Queue()
        }
        self.num = 1
        self.save_num = 1

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            site=crawler.spider.site
        )

    @func_set_timeout(300)
    def up_del_dis(self, sql, data=None, site="us", db="mysql"):
        if db == "mysql":
            e = get_country_engine(site)
        elif db == "pg":
            e = get_pg_country_engine(site)
        elif db == "pg14":
            e = get_14pg_country_engine(site)
        try:
            if not is_internet_available():
                return False
            with e.connect() as conn:
                if data != None:
                    if data:
                        conn.execute(sql, data)
                else:
                    conn.execute(sql)
                e.dispose()
                # conn.commit()
                # conn.close()
                return True
        except OperationalError as e:
            logging.info(f"error sql is {sql}")
            return False

    def up_del_db(self, sql, data=None, site="us", db="mysql"):
        if 'delete' in sql.lower():
            sql_msg = "delete"
        else:
            sql_msg = "update"
        while True:
            try:
                if is_internet_available():
                    if self.up_del_dis(sql, data=data, site=site, db=db):
                        logging.info(f"{sql_msg} {db} asin state 3 ok ^_^ -----{len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                        break
                    else:
                        time.sleep(3)
                        logging.info(
                            f"{sql_msg} {db} asin state 3 error T_T --> {len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                        continue
                else:
                    time.sleep(3)
                    logging.info(
                        f"{sql_msg} {db} asin state 3 network error T_T --> {len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                    continue
            except FunctionTimedOut as e:
                time.sleep(3)
                logging.info(f"{sql_msg} {db} asin state 3 time out T_T --> {e}----{len(data or []) or sql}---------{[][0:5] if data is None else data[0:5]}")
                continue

    def save_db(self, table, df, site, db):
        # 入库报错重试
        while True:
            try:
                if df_to_sql(table, df, site=site, db=db):
                    logging.info(
                        f"更新 {db} 数据库 {table} -----{df.shape}---------{df.head()}")
                    break
                else:
                    logging.info(f"更新 {db} 数据库 {table} -----失败")
                    continue
            except OperationalError as e:
                logging.info(f"更新 {db} 数据库 {table} 失败  连接错误{e}")
                continue
            except FunctionTimedOut as e:
                logging.info(
                    f"更新 {db} 数据库 {table} -超时-{e}---{df.shape}---------{df.head()}")
                continue

    def queue_consumer(self, q_size):
        for k, v in self.q_dict.items():
            if q_size == "max":
                if v.qsize():
                    dates = [v.get() for i in range(0, v.qsize())]
                else:
                    dates = []
            else:
                if v.qsize() >= self.num:
                    dates = [v.get() for i in range(0, self.num)]
                else:
                    dates = []
            if dates:
                df = pd.DataFrame(dates)
                if k == "error_queue":
                    if dates:
                        # 表名需要改
                        sql_up = f"UPDATE `temu_bsr_cate` set `state`=(%s)  where opt_name=(%s);"
                        up_datas = list(set([tuple(i) for i in df.values]))
                        if len(up_datas) == 1:
                            d = up_datas[0]
                        else:
                            d = up_datas
                        self.up_del_db(sql_up, d, self.site, db="mysql")

    def process_item(self, item, spider):
        if item.get("finish_spider"):
            print('等待时 将队列数据存储', {k: v.qsize() for k, v in self.q_dict.items()})
            self.queue_consumer(q_size="max")
        if item.get("inner_item"):
            df = pd.DataFrame(item.get('inner_item'))
            if df.shape[0]:
                dele_opt_name = list(set(df['opt_name']))
                if len(dele_opt_name) == 1:
                    sql_del = f'delete from temu_bsr_datas where opt_name in ("{tuple(dele_opt_name)[0]}");'
                else:
                    sql_del = f"delete from temu_bsr_datas where opt_name in {tuple(dele_opt_name)};"
                self.up_del_db(sql_del, site=self.site, db="mysql")
                logging.info(f"temu_bsr_datas delete {dele_opt_name[0:10]}")
                logging.info(f"去重前 {df.shape}")
                self.save_db(f"temu_bsr_datas", df, self.site, "mysql")
                df.drop_duplicates(['goodid'], inplace=True)
                logging.info(f"去重后 {df.shape}")


                sql_up = f"UPDATE `temu_bsr_cate` set `state`=(%s)  where opt_name=(%s);"

                asin_list = list(set([(3, i) for i in df['opt_name']]))
                if len(asin_list) == 1:
                    d = asin_list[0]
                else:
                    d = asin_list
                logging.info(f"temu_bsr_cate   {df.shape}")
                self.up_del_db(sql_up, d, self.site, db="mysql")
            # self.q_dict.get("inner_item_queue").put(item.get('inner_item'))
        elif item.get("error_asin"):
            self.q_dict.get("error_queue").put(item.get("status"))
        self.queue_consumer("min")

    def close_spider(self, spider):
        print('爬虫结束，存储最后 数据', {k: v.qsize() for k, v in self.q_dict.items()})
        self.queue_consumer("max")


# conn = get_con("us")
# s = sql_connect("us")
# dates = [('B09GM8Y8BN', 'amazon.com', '16707', '4.5', '167', 'Visit the AROEVE Store', 'Home & Kitchen', 'Heating, Cooling & Air Quality', 'Air Purifiers', 'HEPA Air Purifiers', '', '', '', '510192', '{"6474046": 804920, "6474270": 816090, "6476596": 576284, "6476866": 623361, "6478072": 712591}', '{"7141123011": 4860126}', '')]
#
# print(dates)
# # dates = list(set([tuple(v.get()) for i in range(0, self.num)]))
# # ['asin', 'salesChannel', 'reviews', 'rating', 'current_rank', 'brand_name', 'root_category', 'second_category', 'three_category', 'four_category', 'five_category', 'six_category', 'seven_category', 'cat_id', 'history_rank', 'history_category', 'current_rank_avg']
# # inset_sql = f"insert into `product_publish_keepa_text` (`asin`, `salesChannel`, `reviews`, `rating`, `current_rank`, `brand_name`, `root_category`, `second_category`, `three_category`, `four_category`, `five_category`, `six_category`, `seven_category`, `cat_id`, `history_rank`, `history_category`, `current_rank_avg`) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE `history_rank` = values(`history_rank`)"
# inset_sql = f"REPLACE into `product_publish_keepa_text` (`asin`, `salesChannel`, `reviews`, `rating`, `current_rank`, `brand_name`, `root_category`, `second_category`, `three_category`, `four_category`, `five_category`, `six_category`, `seven_category`, `cat_id`, `history_rank`, `history_category`, `current_rank_avg`) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
# if len(dates) == 1:
#     sql_insert(inset_sql, dates[0])
# else:
#     sql_insert_many(inset_sql, dates)
# logging.info(f"更新product_publish_keepa_text-----{len(dates)}---------{dates}")