import time
import logging
import pandas as pd
from queue import Queue
from func_timeout import func_set_timeout
from sqlalchemy.exc import OperationalError
from amazon_spider.utils.utils import send_mg
from func_timeout.exceptions import FunctionTimedOut
# useful for handling different item types with a single interface
from amazon_spider.conf.db import selection_table_name
from amazon_spider.utils.common import is_internet_available
from amazon_spider.db.mysql_db import get_country_engine, df_to_sql
from amazon_spider.db.pg_db import get_pg_country_engine, get_14pg_country_engine, updatas_pg_asin


class AmazonOtherSpiderPipeline:
    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_variat_queue": Queue(),
        }
        self.num = 80
        self.save_num = 20
        self.asin_table_name = selection_table_name.get(f"{self.site}_asin_table")
        self.variat_table_name = selection_table_name.get(f"{self.site}_asin_variat")

    @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} {str(e)}")
            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:
                if "pg" in db and 'asin_image' in sql:
                    sql_backend = f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query={sql} AND query not like '%pg_terminate_backend%';"
                    logging.info(f"sql_backend --> {sql_backend}")
                    if is_internet_available():
                        if updatas_pg_asin(sql_backend, site=site, db=db):
                            logging.info(f"{sql_msg} {db} pg_terminate_backend ok ^_^ -----{data[0][0]}---------")
                            continue
                        else:
                            time.sleep(3)
                            logging.info(
                                f"{sql_msg} {db} pg_terminate_backend asin T_T --> {data[0][0]}---------")
                            continue
                else:
                    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 asin_state_to_list(self, df):
        df_9 = df.loc[df.volume.isna() & df.weight.isna() & df[
            "rank"].isna() & df.launch_time.isna() & df.price.isna() & df.rating.isna() & df.total_comments.isna()]
        df_ = df.loc[~(df.volume.isna() & df.weight.isna() & df[
            "rank"].isna() & df.launch_time.isna() & df.price.isna() & df.rating.isna() & df.total_comments.isna())]
        df_7 = df_.loc[df.volume.isna() & df.weight.isna() & df["rank"].isna() & df.launch_time.isna()]
        df_3 = df_.loc[~(df.volume.isna() & df.weight.isna() & df["rank"].isna() & df.launch_time.isna())]
        df_9["state"] = 9
        df_7["state"] = 7
        df_3["state"] = 3
        df_9 = df_9.loc[:, ["state", "asin", "site"]]
        df_7 = df_7.loc[:, ["state", "asin", "site"]]
        df_3 = df_3.loc[:, ["state", "asin", "site"]]
        asin_list = []
        asin_list += [tuple(i) for i in df_9.values]
        asin_list += [tuple(i) for i in df_7.values]
        asin_list += [tuple(i) for i in df_3.values]
        return asin_list

    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 site_dis(self, x):
        sites = {
            "us": "Amazon.com",
            "uk": "Amazon.co.uk",
            "de": "Amazon.de",
            "es": "Amazon.es",
            "it": "Amazon.it",
            "fr": "Amazon.fr",
            "mx": "Amazon.com.mx",
            "ca": "Amazon.ca",
            "nl": "Amazon.nl",
            "be": "Amazon.com.be",
            "se": "Amazon.se",
            "pl": "Amazon.pl",
            "tr": "Amazon.com.tr",
            'au': "Amazon.com.au",
        }
        return sites[x]

    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 == "inner_item_queue":
                    if dates:
                        if df.shape[0]:
                            self.save_db(f"{self.site}_self_asin_detail", df, self.site, "mysql")
                            logging.info(f"{self.site}_self_asin_detail   {df.shape}")
                            # if self.site == "us":
                            #     self.save_db(f"{self.site}_self_asin_detail_{time.gmtime().tm_year}", df, self.site, "pg")
                        sql_up = f"UPDATE `other_self_asin` set `state`=(%s)  where asin=(%s) and site=(%s);"
                        df['site'] = df.site.apply(self.site_dis)
                        asin_list = self.asin_state_to_list(df)
                        if len(asin_list) == 1:
                            d = asin_list[0]
                        else:
                            d = asin_list
                        self.up_del_db(sql_up, d, self.site, db="mysql")
                        logging.info(f"other_self_asin 更新完成")
                elif k == "error_queue":
                    if dates:
                        # 表名需要改
                        sql_up = f"UPDATE `other_self_asin` set `state`=(%s)  where asin=(%s) and site=(%s);"
                        # 部分不需要删除 site字段
                        # df.drop(columns=["site"], inplace=True)
                        df['site'] = df.site.apply(self.site_dis)
                        up_datas = [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")
                        logging.info(f"other_self_asin 更新完成")
                        # df_st_asin = df.loc[:, ["asin", "state"]]
                        # site_up_asin = [list(i) for i in df_st_asin.values]
                        # logging.info(f"{self.site}_self_all_syn   {df.shape}")
                elif k == "asin_img_queue":
                    if dates:
                        for name, group in df.groupby(['site']):
                            logging.info(f"name: {name}")
                            img_exploded_list = group['asin_img'].explode()
                            # 展开后转换为一个大列表
                            img_list = [i for i in img_exploded_list.tolist() if not isinstance(i, float)]
                            if img_list:
                                logging.info(f"img处理{img_list[0:5]}")
                                df_img = pd.DataFrame(img_list)
                                # df_img['mapped_asin'] = df_img['asin'].apply(self.asin_to_number)
                                df_img.drop_duplicates(subset=["asin", "img_order_by", "data_type"], inplace=True)
                                dele_asin = list(set(df_img.asin))

                                if len(dele_asin) == 1:
                                    sql_del = f"delete from {name}_asin_image where asin in ('{tuple(dele_asin)[0]}');"
                                else:
                                    sql_del = f"delete from {name}_asin_image where asin in {tuple(dele_asin)};"
                                self.up_del_db(sql_del, site=self.site, db="pg")
                                logging.info(f"img delete {dele_asin[0:10]}")
                                # _asin_image库
                                self.save_db(f"{name}_asin_image", df_img, self.site, db="pg")
                                logging.info(f"img save {df_img.head()}")
                elif k == "variat_item_queue":
                    if dates:
                        for name, group in df.groupby(['site']):
                            logging.info(f"variat name: {name}")
                            variat_exploded_list = group['variat_item'].explode()
                            # 展开后转换为一个大列表
                            variat_list = [i for i in variat_exploded_list.tolist() if not isinstance(i, float)]
                            if variat_list:
                                logging.info(f"variat 处理{variat_list[0:5]}")
                                df_variat = pd.DataFrame(variat_list)
                                dele_asin = list(set(df_variat["parent_asin"]))
                                if dele_asin:
                                    if len(dele_asin) == 1:
                                        sql_del = f"delete from `{self.site}_variat` where parent_asin in ('{tuple(dele_asin)[0]}');"
                                    else:
                                        sql_del = f"delete from `{self.site}_variat` where parent_asin in {tuple(dele_asin)};"
                                    # sql_delete(sql_del, site=self.site)
                                    self.up_del_db(sql_del, site=self.site, db="mysql")
                                    logging.info(f"variat delete {dele_asin[0:10]}")

                                    if len(dele_asin) == 1:
                                        sql_del = f"delete from `{self.site}_self_variat` where parent_asin in ('{tuple(dele_asin)[0]}');"
                                    else:
                                        sql_del = f"delete from `{self.site}_self_variat` where parent_asin in {tuple(dele_asin)};"
                                    # sql_delete(sql_del, site=self.site)
                                    self.up_del_db(sql_del, site=self.site, db="mysql")
                                    logging.info(f"_self_variat delete {dele_asin[0:10]}")

                                df_variat.drop_duplicates(subset=["asin"], inplace=True)
                                self.save_db(f"{self.site}_variat", df_variat, self.site, "mysql")
                                logging.info(f"variat save {df_variat.head()}")

                                self.save_db(f"{self.site}_self_variat", df_variat, self.site, "mysql")
                                logging.info(f"_self_variat save {df_variat.head()}")
                elif k == "self_variat_queue":
                    if dates:
                        for name, group in df.groupby(['site']):
                            logging.info(f"self_variat_item name: {name}")
                            variat_exploded_list = group['self_variat_item'].explode()
                            # 展开后转换为一个大列表
                            variat_list = [i for i in variat_exploded_list.tolist() if not isinstance(i, float)]
                            if variat_list:
                                logging.info(f"variat 处理{variat_list[0:5]}")
                                df_variat = pd.DataFrame(variat_list)
                                dele_asin = list(set(df_variat["parent_asin"]))
                                if dele_asin:
                                    if len(dele_asin) == 1:
                                        sql_del = f"delete from `{self.site}_self_variat` where parent_asin in ('{tuple(dele_asin)[0]}');"
                                    else:
                                        sql_del = f"delete from `{self.site}_self_variat` where parent_asin in {tuple(dele_asin)};"
                                    # sql_delete(sql_del, site=self.site)
                                    self.up_del_db(sql_del, site=self.site, db="mysql")
                                    logging.info(f"_self_variat delete {dele_asin[0:10]}")
                                self.save_db(f"{self.site}_self_variat", df_variat, self.site, "mysql")
                                logging.info(f"_self_variat save {df_variat.head()}")

    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"):
            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("asin"))
        # elif item.get("variat_item"):
        #     self.q_dict.get("variat_item_queue").put(item)
        # elif item.get("asin_img"):
        #     self.q_dict.get("asin_img_queue").put(item)
        # elif item.get("self_variat_item"):
        #     self.q_dict.get("self_variat_queue").put(item)

        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")
        send_mg("hezhe", "【内部asin爬取进程退出】", "内部asin爬取进程退出")