import sys
import os

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from amazon_params import py_ja3
from amazon_save_db.save_asin_detail import Save_asin_detail
from utils.asin_parse import ParseAsinUs
# from utils.check_columns import spider_check
from queue import Queue
import time
import random
import re
from lxml import etree
from curl_cffi import requests
import uuid
import urllib3
import threading
from func_timeout.exceptions import FunctionTimedOut
from datetime import datetime

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
urllib3.disable_warnings()
import requests as requests2
import traceback

sess = requests2.Session()
import time
import json


class async_asin_mysql(object):
    def __init__(self, site_name='us', proxy_name=None, week=None):
        self.site_name = site_name  # 站点
        self.week_int = week
        if int(week) < 10:
            self.week_ = f'0{int(week)}'
        else:
            self.week_ = week
        self.save_asin_detail = Save_asin_detail(site_name=self.site_name, proxy_name=proxy_name, week=self.week_)
        self.reuests_para_val = self.save_asin_detail.reuests_para_val
        # 返回 对应站点的host，首页链接
        self.site_url, self.host = self.reuests_para_val.get_site_url(self.site_name)
        self.kafuka_producer = self.save_asin_detail.kafuka_producer
        self.asin_variation_list = []  # 变体
        self.all_img_video_list = []  # 存储图片 和 图片位置，视频图片
        self.requests_error_asin_list = []  # 1
        self.asin_not_found_list = []  # 4
        self.asin_not_sure_list = []  # 6
        self.asin_not_foot_list = []  # 7
        self.asin_not_foot2_list = []  # 8
        self.asin_not_buyBox_list = []  # 9
        self.asin_not_response_list = []  # 10
        self.asin_not_redirect_list = []  # 12
        self.asin_not_div_id_dp_list = []  # 返回html没有包含div @id=dp,状态13
        self.asin_list_update = []  # 3
        self.cookies_queue = Queue()  # cookie队列
        self.item_queue = Queue()  # 存储 item 详情数据队列
        self.queries_asin_queue = Queue()  # 需要爬取的asin队列
        self.buyBox_list = []  # 卖家名称 url 列表
        self.asin_detail_list = []  # 存储asin 详情的列表
        self.buyBoxname_asin_list = []  # asin 卖家的列表item
        self.delete_cookies_list = []  # 存储出现中国邮编的cookie
        self.stop_item_queue = True  # 用于是否退出循环存储的条件
        self.spider_de_feedback = False
        self.cookie_dict_delete_id = {}
        self.star_list = []  # 存储星级百分比
        self.add_cart_asin_list = []  # 存储 绑定购买的asin
        self.asin_brand_list = []  # 存储asin 对应 的品牌
        self.bs_category_asin_list_pg = []  # 存储 asin 详情 bsr 文本类目
        # self.spider_check = spider_check(site_name)  # 调用校验字段的类
        self.session = requests.Session()
        self.asin_queue = []
        self.headers_num_int = 0

    def get_asin(self):
        while True:
            if self.queries_asin_queue.empty() == False:
                querys = self.queries_asin_queue.get()
                if self.cookies_queue.empty():
                    cookies_dict = self.reuests_para_val.get_cookie()
                    self.cookie_dict_delete_id = cookies_dict
                    for ck in cookies_dict.values():
                        self.cookies_queue.put(ck)
                # 获取组装cookie
                cookie_str = self.reuests_para_val.get_cookie_str(self.cookies_queue)
                query = querys.split('|')
                is_variat = query[2]
                asin = query[0]
                date_info = query[1]
                data_type_asin = int(query[3])
                volume_str = query[4]
                weight_str = query[5]
                if self.headers_num_int > 20:
                    break
                headers = self.reuests_para_val.requests_amazon_headers(host=self.host, site_url=self.site_url,
                                                                        asin=asin, scraper_url=None)
                headers["cookie"] = cookie_str
                if is_variat == '1':
                    scraper_url = self.site_url + 'dp/' + query[0] + '/qid=' + str(int(time.time())) + "?th=1&psc=2"
                else:
                    scraper_url = self.site_url + 'dp/' + query[0] + '/qid=' + str(int(time.time()))
                log_time = time.strftime('%Y %m %d %H:%M:%S', time.localtime(time.time()))
                try:
                    sess.mount(self.site_url, py_ja3.DESAdapter())
                    resp = sess.get(scraper_url, headers=headers,
                                    timeout=10, verify=False)
                    if self.reuests_para_val.check_amazon_yzm(resp):
                        print('验证码')
                        self.headers_num_int += 1
                        self.requests_error_asin_list.append(query[0])
                        time.sleep(random.uniform(2.5, 5.5))
                        continue
                except Exception as e:
                    print("请求错误错误: ", e)
                    if 'Received response with content-encoding: gzip' in str(e):
                        self.asin_not_found_list.append(asin)
                    else:
                        self.requests_error_asin_list.append(query[0])
                    if 'Could not resolve host' in str(e):
                        time.sleep(random.uniform(10, 20))
                    time.sleep(random.uniform(3, 7))
                    continue
                response_url = resp.url
                response = resp.text
                response_s = etree.HTML(response)
                # 获取邮编
                try:
                    ingress = response_s.xpath("//span[@id='glow-ingress-line2']/text()")
                except Exception as e:
                    self.asin_not_response_list.append(asin)
                    continue
                try:
                    ingress = ingress[0].strip()
                except:
                    ingress = None
                if self.reuests_para_val.check_amazon_not_page(response):
                    self.asin_not_found_list.append(asin)
                    continue
                if self.reuests_para_val.check_amazon_page(response, response_url):
                    self.asin_not_redirect_list.append(asin)
                    continue
                if self.reuests_para_val.check_amazon_allow_redirects(response_url, asin):
                    self.asin_not_redirect_list.append(asin)
                    continue
                print(ingress, ' 打印 邮编 ', resp.url)
                if ingress:
                    if self.reuests_para_val.check_amazon_ingress(ingress):
                        try:
                            cookie_ubid_main_id = re.findall(r'ubid-main=(.*?);', cookie_str)[0]
                        except:
                            cookie_ubid_main_id = re.findall(r'session-id=(.*?);', cookie_str)[0]
                        for cookie_key_value in self.cookie_dict_delete_id.items():
                            if cookie_ubid_main_id in cookie_key_value[1]:
                                self.delete_cookies_list.append(cookie_key_value[0])
                        self.requests_error_asin_list.append(asin)
                        time.sleep(random.uniform(1.2, 3.5))
                        continue
                div_dp = response_s.xpath('//div[@id="dp"]')
                if div_dp:
                    # 解析
                    items = ParseAsinUs(resp=response, asin=asin, week=self.week_, date_info=date_info,
                                        site_name=self.site_name).xpath_html()
                    new_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    item = {'asin': items["asin"], 'week': self.week_int, 'title': items["title"],
                            'img_url': items["img_url"],
                            'rating': items["rating"],
                            'total_comments': items["total_comments"],
                            'price': items["price"], "rank": items["rank"], 'category': items["category"],
                            'launch_time': items["launch_time"],
                            'volume': items["volume"],
                            'weight': items["weight"], "page_inventory": items["page_inventory"],
                            "buy_box_seller_type": items["buy_box_seller_type"],
                            "asin_vartion_list": items["asin_vartion_list"], 'title_len': items["title_len"],
                            'img_num': items["img_num"], 'img_type': items["img_type"],
                            'activity_type': items["activity_type"],
                            'one_two_val': items["one_two_val"], 'three_four_val': items["three_four_val"],
                            'eight_val': items["eight_val"],
                            'qa_num': items["qa_num"], 'five_star': items["five_star"], 'four_star': items["four_star"],
                            'three_star': items["three_star"],
                            'two_star': items["two_star"], 'one_star': items["one_star"], 'low_star': items["low_star"],
                            'together_asin': items["together_asin"],
                            'brand': items["brand"], 'ac_name': items["ac_name"], 'material': items["material"],
                            'node_id': items["node_id"], 'data_type': data_type_asin,
                            'sp_num': items["sp_num"], 'weight_str': items["weight_str"],
                            'package_quantity': items['package_quantity'], 'pattern_name': items['pattern_name'],
                            'seller_id': items["seller_id"], 'describe': items["describe"],
                            'variat_num': items['variat_num'],
                            'site_name': self.site_name, 'best_sellers_rank': items["best_sellers_rank"],
                            'best_sellers_herf': items["best_sellers_herf"], 'account_url': items["account_url"],
                            'account_name': items["account_name"], 'parentAsin': items["parentAsin"],
                            'asinUpdateTime': new_date, 'follow_sellers': items['sellers_num'], 'date_info': date_info,
                            'all_best_sellers_herf': items['all_best_sellers_herf'],
                            'product_description': items['product_description'],
                            'buy_sales': items['buySales'], 'image_view': items['image_view'],
                            'product_json': items['product_json'],
                            'product_detail_json': items['productdetail_json'],
                            'review_ai_text': items['review_ai_text'], 'review_label_json': items['review_label_json'],
                            'lob_asin_json': items['lob_asin_json'],
                            'sp_initial_seen_asins_json': items['sp_initial_seen_asins_json'],
                            'sp_4stars_initial_seen_asins_json': items['sp_4stars_initial_seen_asins_json'],
                            'sp_delivery_initial_seen_asins_json': items['sp_delivery_initial_seen_asins_json'],
                            'compare_similar_asin_json': items['compare_similar_asin_json'],
                            'customer_reviews_json': items['customer_reviews_json'],
                            'together_asin_json': items['together_asin_json'],
                            'min_match_asin_json': items['min_match_asin_json'], 'seller_json': items['seller_json']
                            }
                    if self.site_name in ['uk', 'de', 'fr', 'es', 'it']:
                        item['five_six_val'] = items['five_six_val']
                    print(item)
                    if not item['title'] or not item['img_url']:
                        self.asin_not_sure_list.append(asin)
                        continue
                    elif len(item['img_url']) > 1:
                        for key in ['None', 'null', 'none']:
                            if key in item['img_url']:
                                self.asin_not_sure_list.append(asin)
                                continue
                    elif len(item['title']) > 1:
                        for key in ['None', 'null', 'none']:
                            if key in item['title']:
                                self.asin_not_sure_list.append(asin)
                                continue
                    if (self.reuests_para_val.check_contain_chinese(item['title'])) or (
                            self.reuests_para_val.check_contain_chinese(item['category'])):
                        self.asin_not_sure_list.append(asin)
                        continue
                    # self.spider_check.check_data(item, self.site_name)
                    self.item_queue.put(item)
                    if items["buyBox_list"]:
                        self.buyBox_list.extend(items["buyBox_list"])
                    if items["buyBoxname_asin_list"]:
                        self.buyBoxname_asin_list.extend(items["buyBoxname_asin_list"])
                    if items["bs_category_asin_list_pg"]:
                        self.bs_category_asin_list_pg.extend(items["bs_category_asin_list_pg"])
                    if items["all_img_video_list"]:
                        for img in items["all_img_video_list"]:
                            self.all_img_video_list.append(img)
                    if items["asin_variation_list"]:
                        self.asin_variation_list.extend(items["asin_variation_list"])
                    item['asin_vartion_list'] = items["asin_variation_list"]
                    item['img_list'] = items["all_img_video_list"]
                    if item['volume'] is None and volume_str != 'null':
                        item['volume'] = volume_str
                    if item['weight_str'] is None and weight_str != 'null':
                        item['weight_str'] = weight_str
                    self.send_kafka(item)
                else:
                    print(f"{log_time} html 没有包含 div @id=dp {resp.url}")
                    self.asin_not_div_id_dp_list.append(asin)
                    continue
            else:
                break

    def send_kafka(self, items):
        for i in range(5):
            try:
                print('数据传输：send_kafka')
                topic = f"{self.site_name}_asin_detail"
                self.kafuka_producer.send(topic, items)
                self.kafuka_producer.flush()
                break
            except Exception as e:
                time.sleep(10)
                self.kafuka_producer = self.save_asin_detail.kafuka_producer
                print("调用卡夫卡接口报错", e, f"\n{traceback.format_exc()}")

    def init_list(self):
        print("=======清空变量==========")
        self.asin_variation_list = []  # 变体
        self.asin_not_found_list = []  # 4
        self.asin_not_sure_list = []  # 6
        self.asin_not_foot_list = []  # 7
        self.asin_not_foot2_list = []  # 8
        self.asin_not_buyBox_list = []  # 9
        self.asin_not_response_list = []  # 10
        self.asin_not_redirect_list = []  # 12
        self.asin_not_div_id_dp_list = []  # 13 返回html没有包含div @id=dp,状态13
        self.requests_error_asin_list = []  # 1
        self.asin_list_update = []  # 3
        self.item_queue = Queue()  # 存储 item 详情数据队列
        self.queries_asin_queue = Queue()  # 需要爬取的asin队列
        self.buyBox_list = []  # 卖家名称 url 列表
        self.asin_detail_list = []  # 存储asin 详情的列表
        self.buyBoxname_asin_list = []  # asin 卖家的列表
        self.delete_cookies_list = []  # 存储出现中国邮编的cookie
        self.all_img_video_list = []  # 存储图片 和 图片位置，视频图片
        self.star_list = []
        self.add_cart_asin_list = []  # 存储绑定购买的asin
        self.asin_brand_list = []
        self.bs_category_asin_list_pg = []
        self.headers_num_int = 0
        self.asin_queue = []

    def run(self):
        asin_list = self.save_asin_detail.read_db_data()
        # asin_list = ['B06XWQ2KQR|2024-04-14|0|0|null|null']
        if asin_list:
            for asin in asin_list:
                self.queries_asin_queue.put(asin)
            if self.cookies_queue.empty():
                cookies_dict = self.reuests_para_val.get_cookie()
                self.cookie_dict_delete_id = cookies_dict
                for ck in cookies_dict.values():
                    self.cookies_queue.put(ck)
            html_thread = []
            for i in range(25):
                thread2 = threading.Thread(target=self.get_asin)
                html_thread.append(thread2)
            for ti in html_thread:
                ti.start()
            for t2 in html_thread:
                t2.join()
            # 存储数据
            print("存储数据 存储asin详情，信息，")
            while True:
                try:
                    self.save_asin_detail.process_item(self.item_queue, self.requests_error_asin_list,
                                                       self.asin_list_update, self.asin_not_found_list,
                                                       self.asin_not_sure_list, self.asin_not_foot_list,
                                                       self.asin_not_foot2_list, self.asin_not_buyBox_list,
                                                       self.asin_not_response_list, self.asin_not_redirect_list,
                                                       self.asin_not_div_id_dp_list, self.star_list,
                                                       self.add_cart_asin_list,
                                                       self.week_)
                    break
                except FunctionTimedOut as e:
                    print('断网', e)
            print('存储 asin bsr 文本 存储pg')
            while True:
                try:
                    self.save_asin_detail.save_bs_category_asin_detail(self.bs_category_asin_list_pg)
                    break
                except FunctionTimedOut as e:
                    print('断网', e)
            print('存储 save_buyBoxname_url，店铺 店铺 url')
            while True:
                try:
                    self.save_asin_detail.save_buyBoxname_url(self.buyBox_list)
                    break
                except FunctionTimedOut as e:
                    print('断网', e)
            print("存储 店铺 名称 和 asin")
            while True:
                try:
                    self.save_asin_detail.save_buyBoxname_asin(self.buyBoxname_asin_list)
                    break
                except FunctionTimedOut as e:
                    print('断网', e)
            # 删除cookie
            self.reuests_para_val.delete_china_cookie(self.delete_cookies_list)
            # 清空变量，
            self.init_list()
# if __name__ == '__main__':
#     async_asin_mysql(site_name='de',week=14).run()