import sys
import os

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from utils.db_connect import BaseUtils
from amazon_params import py_ja3
from amazon_params.params import DB_REQUESTS_ASIN_PARAMS
from utils.requests_param import Requests_param_val
from queue import Queue
import time
import random
from lxml import etree
import json
from curl_cffi import requests
import requests as requests2

sess = requests2.Session()
import traceback
import pandas as pd
import threading
import urllib3
import re
import uuid

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
urllib3.disable_warnings()

"""店铺 商品 抓取"""


class async_account_name_products(BaseUtils):
    def __init__(self, site_name='us', read_size=100, proxy_name=None, week=None):
        super().__init__()
        self.site_name = site_name  # 站点
        self.week = week
        print('代理 proxy_nameproxy_nameproxy_name: ', proxy_name)
        self.reuests_para_val = Requests_param_val(site_name=self.site_name, spider="seller_account_product",
                                                   proxy_name=proxy_name)
        self.read_size = read_size
        self.init_db_names()
        self.requests_error_asin_list = []  # 1
        self.asin_not_found_list = []  # 4
        self.asin_not_seller_id = []  # 5
        self.asin_not_sure_list = []  # 6
        self.ingress_num = 0  # 邮编出现中国大陆次数统计
        self.ip_num_proxy = 0  # 切换代理ip的判断
        self.ip_num = 0  # 切换本地ip的判断
        self.cookies_queue = Queue()  # cookie队列
        self.item_queue = Queue()  # 存储 item 详情数据队列
        self.queries_asin_queue = Queue()  # 需要爬取的asin队列
        self.asin_detail_list = []  # 存储asin 详情的列表
        self.delete_cookies_list = []  # 存储出现中国邮编的cookie
        self.stop_item_queue = True  # 用于是否退出循环存储的条件
        self.cookie_dict_delete_id = {}
        self.seller_account_num_list = []  # 存储店铺产品总数
        self.account_name_page_list = []  # 存储已经翻页的店铺名称
        # 返回 对应站点的host，首页链接
        self.site_url, self.host = self.reuests_para_val.get_site_url(self.site_name)
        self.headers_num_int = 0

    def init_db_names(self):
        year = time.strftime("%Y")
        month = time.strftime("%m")
        if int(self.week) < 10:
            _week = f'0{self.week}'
        else:
            _week = self.week
        self.year_week = f"{year}-{_week}"
        self.year_month = f'{year}_{month}'
        self.engine = self.mysql_connect()
        self.engine_pg = self.pg_connect()
        self.db_seller_account_product_syn = self.site_name + DB_REQUESTS_ASIN_PARAMS['db_seller_account_product_syn'][
                                                              2:]
        self.db_asin_detail_product = self.site_name + DB_REQUESTS_ASIN_PARAMS['db_asin_detail_product'][2:]
        self.db_seller_account_feedback = self.site_name + DB_REQUESTS_ASIN_PARAMS['db_seller_account_feedback'][2:]
        self.db_search_term = self.site_name + DB_REQUESTS_ASIN_PARAMS["db_search_term"][2:]
        self.db_seller_account_syn = self.site_name + DB_REQUESTS_ASIN_PARAMS['db_seller_account_syn'][2:] + '_distinct'

    def get_product(self, t_num):
        while True:
            time.sleep(0.3)
            if self.queries_asin_queue.empty() == False:
                querys = self.queries_asin_queue.get()
                thread_num = len(threading.enumerate())
                if self.cookies_queue.empty():
                    cookies_dict = self.reuests_para_val.get_cookie()
                    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('|-|')
                seller_id = query[1]  # 卖家id
                scraper_url = f'{self.site_url}s?me=' + seller_id
                headers = self.reuests_para_val.requests_amazon_headers(host=self.host, site_url=self.site_url,
                                                                        asin=None, scraper_url=scraper_url)
                headers["cookie"] = cookie_str
                try:
                    print(self.headers_num_int, '请求url: ', scraper_url)
                    sess.mount(self.site_url, py_ja3.DESAdapter())
                    resp = sess.get(scraper_url, headers=headers,
                                    timeout=10, verify=False)
                    resp.close()
                    if self.reuests_para_val.check_amazon_yzm(resp):
                        print(f"{self.site_name}  站点 +  使用代理ip出现验证码：{scraper_url}")
                        time.sleep(random.uniform(1.5, 5.5))
                        self.headers_num_int += 1
                        continue
                except Exception as e:
                    print(e, '222222222222222222222')
                    account_name_next_url_queue = query[0] + '|-|' + seller_id + '|-|' + scraper_url
                    print("请求错误错误: ", account_name_next_url_queue)
                    self.requests_error_asin_list.append(seller_id)
                    time.sleep(random.uniform(2, 3.5))
                    continue
                response = resp.text
                response_s = etree.HTML(response)
                account_name = query[0]
                #  状态 4 Listen Now
                print_time = time.strftime('%Y %m %d %H:%M:%S', time.localtime(time.time()))
                if self.reuests_para_val.check_amazon_not_page(response):
                    self.requests_error_asin_list.append(seller_id)
                    print(f"{print_time} 商品不存在 更改状态1 不存储数据 {account_name}")
                    self.headers_num_int += 1
                    time.sleep(random.uniform(2, 3.5))
                    continue
                elif "Need help?" in response and "Try checking your spelling or use more general terms" in response:
                    print('Need help 66666')
                    self.asin_not_sure_list.append(seller_id)
                    time.sleep(random.uniform(2, 3.5))
                    continue
                # 获取邮编
                try:
                    ingress = response_s.xpath("//span[@id='glow-ingress-line2']/text()")
                    print('邮编：：：', ingress)
                except Exception as e:
                    self.requests_error_asin_list.append(seller_id)
                    time.sleep(random.uniform(1.5, 2))
                    continue
                try:
                    ingress = ingress[0].strip()
                except:
                    ingress = None
                    print("获取邮编錯誤:")
                print(ingress, '邮编 ')
                if ingress:
                    if ("中国大陆" in ingress) or ("China" in ingress) or ("Hong" in ingress) or ("Chine" in ingress) or (
                            "Cina" in 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(seller_id)
                        time.sleep(random.uniform(1.5, 2))
                        self.headers_num_int += 1
                        continue
                else:
                    self.requests_error_asin_list.append(seller_id)
                    time.sleep(random.uniform(1.5, 2))
                    continue
                # 获取产品总数
                results_span_list = response_s.xpath(
                    '//span[contains(text(),"results")]/text()|//div[@class="a-section a-spacing-small a-spacing-top-small"]//span/text()')
                results_list = []
                if len(results_span_list) > 0:
                    ele_text = results_span_list[0].replace(".", "").replace(",", "").replace("\xa0", "")
                    ele_a = re.findall("\d+-\d+", ele_text)
                    if len(ele_a) == 0:
                        ele_a = re.findall("\d+–\d+", ele_text)
                    if ele_a:
                        ele_text = ele_text.replace(ele_a[0], '')
                    results_list = re.findall("(\d+)", ele_text)
                if len(results_list) > 1:
                    results_list = [results_list[-1]]
                try:
                    if results_list:
                        results_int = results_list[0]
                    if 'one result for' in ele_text or "One result" == ele_text:
                        results_int = 1
                    num_int = int(results_int)
                    self.seller_account_num_list.append((seller_id, num_int))
                except:
                    num_int = 0
                print("店铺 产品总数：", seller_id, account_name, num_int)
                products_asin_link_list = response_s.xpath(
                    "//div[@class='s-main-slot s-result-list s-search-results sg-row']//@data-asin")
                while '' in products_asin_link_list:
                    products_asin_link_list.remove('')
                if products_asin_link_list:
                    for products_asin in products_asin_link_list:
                        if products_asin and products_asin != '' and products_asin != ' ':
                            # 获取 asin  位置
                            asin_href_list = response_s.xpath(f"//div[@data-asin='{products_asin}']//a/@href")
                            if len(asin_href_list) > 0:
                                asin_href_list = response_s.xpath(f"//div[@data-asin='{products_asin}']//a/@href")
                                asin_href_join = ''.join(asin_href_list)
                                row_num_lsit = re.findall(fr"{products_asin}/ref=sr_1_(\d+)\?", asin_href_join)
                                try:
                                    row_num = row_num_lsit[0] if row_num_lsit else 0
                                    row_num_int = int(row_num)
                                except:
                                    row_num_int = 0
                            else:
                                row_num_int = 0

                            try:
                                asin_img = response_s.xpath(f'//div[@data-asin="{products_asin}"]//img//@src')
                                if len(asin_img):
                                    img = asin_img[0]
                                else:
                                    img = None
                            except Exception as e:
                                img = None
                            try:
                                asin_title = response_s.xpath(
                                    f'//div[@data-asin="{products_asin}"]//span[contains(@class,"a-text-normal")]//text()|//div[@data-asin="{products_asin}"]//a[contains(@href,"{products_asin}")]//h2/@aria-label')
                                if (len(asin_title) == 0):
                                    asin_title = response_s.xpath(
                                        f'//div[@data-asin="{products_asin}"]//span[@class="a-truncate-cut"]//text()|//div[@data-asin="{products_asin}"]//div[contains(@data-cy,"title")]//span/text()')

                                title = asin_title[0]
                            except Exception as e:
                                title = None
                            try:
                                asin_review = response_s.xpath(
                                    f'//div[@data-asin="{products_asin}"]//span[contains(@class,"a-size-base s-")]//text()')
                                if len(asin_review) == 0:
                                    asin_review = response_s.xpath(
                                        f'//div[@data-asin="{products_asin}"]//span[@class="a-color-link"]//text()')
                                total_comments = None
                                if asin_review:
                                    number_of_reviews = asin_review[0].strip().replace(')', '').replace('(', '')
                                    print("number_of_reviews::", number_of_reviews)
                                    if self.site_name == 'uk':
                                        if "rating" in number_of_reviews:
                                            total_comments = re.findall(r"(.*) rating", number_of_reviews)[0]
                                        else:
                                            total_comments = number_of_reviews
                                    elif self.site_name == 'it':
                                        if "voti" in number_of_reviews:
                                            total_comments = re.findall(r"(.*)voti", number_of_reviews)[0].replace(
                                                '\xa0', '').strip()
                                        else:
                                            total_comments = number_of_reviews.replace('\xa0', '').strip()
                                    elif self.site_name == 'fr':
                                        if "évaluations" in number_of_reviews:
                                            total_comments = re.findall(r"(.*)évaluations", number_of_reviews)[
                                                0].replace('\xa0', '').strip()
                                        else:
                                            total_comments = number_of_reviews.replace('\xa0', '').strip()
                                    elif self.site_name == 'es':
                                        if "valoraciones" in number_of_reviews:
                                            total_comments = re.findall(r"(.*)valoraciones", number_of_reviews)[
                                                0].replace('\xa0', '').strip()
                                        else:
                                            total_comments = number_of_reviews.replace('\xa0', '').strip()
                                    elif self.site_name == 'de':
                                        if "Sternebewertungen" in number_of_reviews:
                                            total_comments = \
                                                re.findall(r"(.*) Sternebewertungen", number_of_reviews[0])[0]
                                        elif "Sternebewertung" in number_of_reviews[0]:
                                            total_comments = re.findall(r"(.*) Sternebewertung", number_of_reviews[0])[
                                                0]
                                        else:
                                            total_comments = number_of_reviews.replace('\xa0', '').strip()
                                    elif self.site_name == 'us':
                                        if "rating" in number_of_reviews:
                                            total_comments = re.findall(r"(.*) rating", number_of_reviews)[0]
                                        else:
                                            total_comments = number_of_reviews
                                    if total_comments:
                                        reviews = total_comments.replace('.', '').replace(',', '').replace('\xa0',
                                                                                                           '').strip()
                                        try:
                                            if float(reviews):
                                                pass
                                            else:
                                                reviews = 0
                                        except:
                                            reviews = 0
                                    else:
                                        reviews = None
                                else:
                                    reviews = None
                            except Exception as e:
                                print(e, '22222222222222222')
                                reviews = None
                            try:
                                asin_rating = response_s.xpath(
                                    f'//div[@data-asin="{products_asin}"]//span[@class="a-icon-alt"]//text()')
                                rating = None
                                if asin_rating:
                                    if 'out' in asin_rating[0]:
                                        rating = re.findall(r"(.*) out", asin_rating[0])[0]
                                    else:
                                        if self.site_name == 'uk':
                                            rating = re.findall(r"(.*) out", asin_rating[0])[0]
                                        elif self.site_name == 'it':
                                            rating = re.findall(r"(.*) su", asin_rating[0])[0]
                                        elif self.site_name == 'fr':
                                            rating = re.findall(r"(.*) sur", asin_rating[0])[0]
                                        elif self.site_name == 'es':
                                            rating = re.findall(r"(.*) de", asin_rating[0])[0]
                                        elif self.site_name == 'de':
                                            rating = re.findall(r"(.*) von", asin_rating[0])[0]
                                        elif self.site_name == 'us':
                                            rating = re.findall(r"(.*) out", asin_rating[0])[0]
                                    if rating:
                                        rating = rating.replace(',', '.').replace('\xa0', '').strip()
                                else:
                                    rating = None
                            except Exception as e:
                                rating = None
                            try:
                                asin_price = response_s.xpath(
                                    f'//div[@data-asin="{products_asin}"]//span[@class="a-offscreen"]//text()')
                                if asin_price:
                                    if self.site_name == 'us':
                                        prices = asin_price[0].replace("$", "").replace("£", "").replace("€",
                                                                                                         "").replace(
                                            ",", "").replace('\xa0', '')
                                    else:
                                        prices = asin_price[0].replace("$", "").replace("£", "").replace("€",
                                                                                                         "").replace(
                                            ".", "").replace(",", ".").replace('\xa0', '')
                                    price = prices
                                else:
                                    price = None

                            except Exception as e:
                                price = None
                            if rating:
                                try:
                                    rating = rating.replace(',', '.')
                                    rating = round(float(rating), 2)
                                except:
                                    rating = 0
                            if price:
                                try:
                                    price = price.replace('\xa0', '').replace(",", '').strip()
                                    if (len(price) > 9) or ('Currently' in price):
                                        price = None
                                    if price:
                                        price = round(float(price), 2)
                                except:
                                    price = None
                            buy_data_list = response_s.xpath(
                                f"//div[@data-asin='{products_asin}']//span[contains(text(),'bought')]/text()") # 月销
                            if buy_data_list:
                                buy_data = buy_data_list[0].strip()
                            else:
                                buy_data = None
                            item = {"seller_id": seller_id, "asin": products_asin, 'row_num': row_num_int,
                                    "img": img, "title": title, "reviews": reviews, "rating": rating, "price": price,
                                    "scraper_url": scraper_url, "buy_data": buy_data}
                            print(item)
                            self.item_queue.put(item)
                else:
                    if len(products_asin_link_list) == 0:
                        self.asin_not_sure_list.append(seller_id)
            else:
                print(f"当前线程-{t_num} 已完成-爬取-跳出循环")
                break

    def init_list(self):
        print("=======清空变量==========")
        self.asin_not_found_list = []  # 4
        self.requests_error_asin_list = []  # 1
        self.item_queue = Queue()  # 存储 item 详情数据队列
        self.queries_asin_queue = Queue()  # 需要爬取的asin队列
        self.asin_detail_list = []  # 存储asin 详情的列表
        self.delete_cookies_list = []  # 存储出现中国邮编的cookie
        self.asin_not_sure_list = []  # 6
        self.asin_not_seller_id = []  # 5
        self.seller_account_num_list = []  # 存储店铺产品总数
        self.account_name_page_list = []
        self.headers_num_int = 0

    def run(self):
        asin_list = self.read_db_data()
        if asin_list:
            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)
            for asin in asin_list:
                self.queries_asin_queue.put(asin)
            html_thread = []
            for i in range(10):
                thread2 = threading.Thread(target=self.get_product, args=(i,))
                html_thread.append(thread2)
            for ti in html_thread:
                ti.start()
            for t2 in html_thread:
                t2.join()
            # 存储数据
            print('存储数据')
            self.process_item()
            # 删除cookie
            self.reuests_para_val.delete_china_cookie(list(set(self.delete_cookies_list)))
            self.init_list()
        else:
            if self.stop_item_queue == False:
                from threading_spider.db_connectivity import connect_db
                db_class = connect_db('us')
                cursor_us, connect_us = db_class.us_mysql_db()  # us站点
                print("-----------------店铺feedback----程序结束---------------------跳出")
                sql = f"select status_val from workflow_progress where page='店铺产品' and date_info='{self.year_week}' and site_name='{self.site_name}' and date_type='week'"
                print(sql)
                cursor_us.execute(sql)
                status_val_tuple = cursor_us.fetchone()
                print(status_val_tuple)
                if status_val_tuple[0] in (1, 2):
                    time_strftime = time.strftime("%Y-%m-%d %X", time.localtime())
                    update_workflow_progress = f"update workflow_progress set is_end='是',status_val=3,status='抓取结束' where page='店铺产品' and date_info='{self.year_week}' and site_name='{self.site_name}' and date_type='week'"
                    cursor_us.execute(update_workflow_progress)
                    connect_us.commit()
                    try:
                        into_workflow_progress = f"INSERT INTO workflow_progress (page, date_info, site_name, date_type, is_end, status_val, status, table_name) VALUES ('店铺产品', '{self.year_month.replace('_', '-')}', '{self.site_name}', 'month', '否', 3, '抓取结束','{self.site_name}_asin_detail_product');"
                        cursor_us.execute(into_workflow_progress)
                        connect_us.commit()
                    except:
                        into_workflow_progress = f"update workflow_progress set status_val=3,status='抓取结束' where page='店铺产品' and date_info='{self.year_month.replace('_', '-')}' and site_name='{self.site_name}' and date_type='month'"
                        print(into_workflow_progress)
                        cursor_us.execute(into_workflow_progress)
                        connect_us.commit()
                    url = 'http://47.112.96.71:8082/selection/sendMessage'
                    data = {
                        'account': 'pengyanbing,chenyuanjie,chenjianyun',
                        'title': self.site_name + '站点 店铺产品 top20',
                        'content': self.year_month.replace('_',
                                                           '-') + ' 月  店铺产品 top20 详情 已结束,请确认下一步流程!时间:' + time_strftime
                    }
                    try:
                        requests.post(url=url, data=data, timeout=15)
                    except:
                        pass
                cursor_us.close()
                connect_us.close()

    def process_item(self):
        print("=================开始存储数据======================")
        while True:
            if self.item_queue.empty() == False:
                item = self.item_queue.get()
                item_list = []
                # 需要存到数据库的字段
                item_list.append(item['seller_id'])
                item_list.append(item['asin'])
                item_list.append(item['row_num'])
                item_list.append(item['img'])
                item_list.append(item['title'])
                item_list.append(item['reviews'])
                item_list.append(item['rating'])
                item_list.append(item['price'])
                item_list.append(self.year_month.replace('_', '-'))
                item_list.append(item['buy_data'])
                # item_list.append(item['month'])
                self.asin_detail_list.append(item_list)
            else:
                if self.item_queue.empty():
                    self.save_data()
                    self.asin_detail_list = []
                    self.update_buyBoxname_num()
                    self.seller_account_num_list = []
                    print("结束--跳出--存储")
                    break

    def read_db_data(self):
        while True:
            try:
                self.engine = self.mysql_connect()
                sql_read = f'SELECT account_name, id, seller_id FROM {self.db_seller_account_syn} WHERE product_state=1 LIMIT {self.read_size} for update;'
                print(sql_read)
                self.df_read = self.engine.read_sql(sql_read)
                if self.df_read.shape[0] == 0:
                    self.stop_item_queue = False
                    return []
                with self.engine.begin() as conn:
                    self.index_tuple = tuple(self.df_read['id'])
                    if len(self.index_tuple) == 1:
                        sql_update = f"""UPDATE {self.db_seller_account_syn} a set product_state=2 where a.id in ({self.index_tuple[0]})"""
                    else:
                        sql_update = f"""UPDATE {self.db_seller_account_syn} a set product_state=2 where a.id in {self.index_tuple}"""
                    conn.execute(sql_update)
                asin_list = list(self.df_read.account_name + '|-|' + self.df_read.seller_id)
                return asin_list
            except Exception as e:
                print("读取数据出bug并等待5s继续", e, f"\n{traceback.format_exc()}")
                continue

    def save_data(self):
        # 店铺asin信息
        while True:
            try:
                print(f'存储：：{self.db_asin_detail_product}_{self.year_month}', )
                df_asin_variation = pd.DataFrame(data=self.asin_detail_list,
                                                 columns=['seller_id', 'asin', 'row_num', 'img_url', 'title',
                                                          'total_comments', 'rating', 'price', 'date_info', 'buy_data'])
                df_asin_variation.drop_duplicates(['seller_id', 'asin'], inplace=True)  # 去重
                self.account_name_list_update = list(df_asin_variation.seller_id)  # 获取状态3的店铺名称
                if self.asin_detail_list:
                    self.engine_pg = self.pg_connect()
                    with self.engine_pg.begin() as conn:
                        if len(set(df_asin_variation.seller_id)) == 1:
                            sql_delete = f"delete from {self.db_asin_detail_product}_{self.year_month} where  seller_id in ('{tuple(df_asin_variation.seller_id)[0]}');"
                        else:
                            sql_delete = f"delete from {self.db_asin_detail_product}_{self.year_month} where seller_id in {tuple(set(df_asin_variation.seller_id))};"
                        conn.execute(sql_delete)
                    print(f"存储店铺asin信息  {self.db_asin_detail_product}_{self.year_month}")
                    self.engine_pg.to_sql(df_asin_variation,self.db_asin_detail_product + f'_{self.year_month}',
                                             if_exists='append')
                self.asin_detail_list = []
                break
            except Exception as e:
                print(f"存储'{self.db_asin_detail_product}' 失败，等待5s继续", e, f"\n{traceback.format_exc()}")
                time.sleep(5)
                continue

        if self.requests_error_asin_list:
            self.db_change_state(state=1)
            self.requests_error_asin_list = []
        if self.account_name_list_update:
            self.db_change_state(state=3)
            self.account_name_list_update = []
        if self.asin_not_found_list:
            self.db_change_state(state=4)
            self.asin_not_found_list = []
        if self.asin_not_sure_list:
            self.db_change_state(state=6)
            self.asin_not_sure_list = []
        if self.asin_not_seller_id:
            self.db_change_state(state=5)
            self.asin_not_seller_id = []

    def update_buyBoxname_num(self):
        while True:
            try:
                if self.seller_account_num_list:
                    self.engine_pg = self.pg_connect()
                    with self.engine_pg.begin() as conn:
                        buyBox_list_ = list(set(self.seller_account_num_list))
                        print(f"更新 seller_account_feedback_new 信息 num {len(buyBox_list_)}")
                        for account_name_num in buyBox_list_:
                            sql_update = f"update {self.db_seller_account_feedback + '_' + self.year_month} set num ={account_name_num[1]} where seller_id = '{account_name_num[0]}';"
                            print(sql_update)
                            conn.execute(sql_update)
                break
            except Exception as e:
                print(f"'{self.db_seller_account_feedback}' 存储卖家 name, num 失败，等待5s继续", e)
                time.sleep(5)
                continue

    def db_change_state(self, state=2):
        if state == 1:
            self.db_change_state_common(state=state, account_name_list=self.requests_error_asin_list)
        if state == 3:
            self.db_change_state_common(state=state, account_name_list=self.account_name_list_update)
        elif state == 4:
            self.db_change_state_common(state=state, account_name_list=self.asin_not_found_list)
        elif state == 6:
            self.db_change_state_common(state=state, account_name_list=self.asin_not_sure_list)

    def db_change_state_common(self, state, account_name_list):
        account_name_list = list(set(account_name_list))
        print(f"==================== 存储状态 {state} 数据 ========== {len(account_name_list)} ========")
        df = self.df_read.loc[self.df_read.seller_id.isin(account_name_list)]
        id_tuple = tuple(df.id)
        while True:
            try:
                self.engine = self.mysql_connect()
                with self.engine.begin() as conn:
                    # 1,3：1--回滚；3--成功
                    if id_tuple:
                        if len(id_tuple) == 1:
                            sql_update = f"update {self.db_seller_account_syn} set product_state={state} where id in ({id_tuple[0]}) and product_state=2;"
                        else:
                            sql_update = f"update {self.db_seller_account_syn} set product_state={state} where id in {id_tuple} and product_state=2;"
                        conn.execute(sql_update)
                break
            except Exception as e:
                print(f"更改{self.db_seller_account_syn}表的state={state}出错", e, f"\n{traceback.format_exc()}")
                continue