import sys
import os
sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from amazon_params import py_ja3
from utils.db_connect import BaseUtils
from last_args import LastEventID
import requests
import json
import time
import random
import pandas as pd
import traceback
from queue import Queue
import socket
import urllib3
import threading
import datetime
import platform
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

""" 在物理机 h 5 6 7 上运行。"""
re_sess = requests.Session()


class Get_ups(BaseUtils):
    def __init__(self):
        super().__init__()
        self.engine = self.mysql_connect()
        self.engine_pg = self.pg_connect()  # 更改变体 时 存储 变体表 使用 self.engine
        self.read_size = 30
        self.asin_list_update = []
        self.db_syn = 'ups_orders_syn'
        self.err_lsit = []
        self.transport_sn_queue = Queue()
        self.Number_list = []
        self.fh_number_list = []
        self.get_token()
        self.update_num = 0

    def get_token(self):
        for i in range(5):
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(('baidu.com', 0))
                ip = s.getsockname()[0]
                print(ip)
                sql_token = f"select Token, cookie from ups_orders_token where ip='{ip}' and type='ups'"
                df_ = pd.read_sql(sql_token, con=self.engine)
                if df_.shape[0] > 0:
                    self.token_cookie_list = list(df_.Token + '|-|' + df_.cookie)
                else:
                    self.token_cookie_list = []
                break
            except:
                time.sleep(5)
                continue

    def proxy_get(self):
        proxies_lsit = [{'http': 'http://t15000409448635:ns0ox6so@w168.kdltps.com:15818/',
                         'https': 'http://t15000409448635:ns0ox6so@w168.kdltps.com:15818/'},
                        {'http': 'http://t17780866032960:57b65ww2@i633.kdltps.com:15818/',
                         'https': 'http://t17780866032960:57b65ww2@i633.kdltps.com:15818/'},
                        {'http': 'http://t16450128695918:2vqy8epc@x783.kdltps.com:15818/',
                         'https': 'http://t16450128695918:2vqy8epc@x783.kdltps.com:15818/'},
                        {'http': 'http://t16450128695918:2vqy8epc@x783.kdltps.com:15818/',
                         'https': 'http://t16450128695918:2vqy8epc@x783.kdltps.com:15818/'},
                        {'http': 'http://t14966226518447:lb23grw2@tps439.kdlapi.com:15818/',
                         'https': 'http://t14966226518447:lb23grw2@tps439.kdlapi.com:15818/'},
                        {'http': 'http://t16208953323855:ib80eped@i537.kdltps.com:15818/',
                         'https': 'http://t16208953323855:ib80eped@i537.kdltps.com:15818/'},
                        {'http': 'http://t16244760032579:0gj5rbnp@n378.kdltps.com:15818/',
                         'https': 'http://t16244760032579:0gj5rbnp@n378.kdltps.com:15818/'}]
        return random.choice(proxies_lsit)

    def read_db_data(self, provider_name=None):
        while True:
            try:
                with self.engine.begin() as conn:
                    if provider_name is None:
                        sql_read = f"SELECT id,transport_sn,provider_name FROM {self.db_syn} WHERE STATE=1 and provider_name !='ups' and prior_status=0 LIMIT {self.read_size} for update;"
                    else:
                        sql_read = f"SELECT id, transport_sn,provider_name FROM {self.db_syn} WHERE STATE=1 and provider_name ='ups' and prior_status=0 LIMIT {self.read_size} for update;"
                    print(sql_read)
                    a = conn.execute(sql_read)
                    self.df_read = pd.DataFrame(a, columns=['id', 'transport_sn', 'provider_name'])
                    self.df_read.drop_duplicates(['transport_sn'], inplace=True)
                    if self.df_read.shape[0] > 0:
                        self.index_tuple = tuple(self.df_read['id'])
                        if len(self.index_tuple) == 1:
                            sql_update = f"""UPDATE {self.db_syn} a set state=2 where a.id in ({self.index_tuple[0]})"""
                        else:
                            sql_update = f"""UPDATE {self.db_syn} a set state=2 where a.id in {self.index_tuple}"""
                        conn.execute(sql_update)
                        transport_sn_list = list(self.df_read.transport_sn + '|' + self.df_read.provider_name)
                        return transport_sn_list
                    else:
                        print('****  数据抓取 完毕 *******', self.db_syn)
                        return []

            except Exception as e:
                print("读取数据出bug并等待5s继续", e, f"\n{traceback.format_exc()}")
                time.sleep(random.uniform(3, 10.5))
                self.mysql_connect()
                continue

    def get_orders_state(self):
        while True:
            if self.transport_sn_queue.empty() == False:
                querys = self.transport_sn_queue.get()
                UPS_orders_FBA = querys.split('|')
                state = False
                provider_name = UPS_orders_FBA[1]
                UPS_orders = UPS_orders_FBA[0]
                print(UPS_orders_FBA)
                i0 = 0
                for i in range(15):
                    if i > 0:
                        i0 += 12
                    data = {"trackingNumber": ["{}".format(UPS_orders)], "locale": "zh_CN", "internalKey": ",,,",
                            "startingTrackIndex": i0, "maxTrackNumbers": 12}
                    if self.token_cookie_list:
                        t_c_list = self.token_cookie_list[0].split('|-|')
                        headers = {
                            "Accept": "application/json, text/plain, */*",
                            "Accept-Encoding": "gzip, deflate, br",
                            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                            "Cache-Control": "no-cache",
                            "Connection": "keep-alive",
                            "Content-Length": "122",
                            "Content-Type": "application/json",
                            "Cookie": t_c_list[1],
                            "Host": "www.ups.com",
                            "Origin": "https://www.ups.com",
                            "Pragma": "no-cache",
                            "Referer": "https://www.ups.com/track/api/Track/GetAdditionalPackages?loc=zh_CN&requester=ST/trackdetails",
                            "Sec-Fetch-Dest": "empty",
                            "Sec-Fetch-Mode": "cors",
                            "Sec-Fetch-Site": "same-origin",
                            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36",
                            "X-XSRF-TOKEN": t_c_list[0]
                        }
                    else:
                        headers = {
                            "Accept": "application/json, text/plain, */*",
                            "Accept-Encoding": "gzip, deflate, br",
                            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                            "Cache-Control": "no-cache",
                            "Connection": "keep-alive",
                            "Content-Length": "122",
                            "Content-Type": "application/json",
                            "Cookie": 'HASSEENNOTICE=TRUE; _gcl_au=1.1.298158492.1602223089; aam_cms=segments%3D15025641%7C18212350; aam_uuid=54559369242038277501618164792818012237; _mkto_trk=id:935-KKE-240&token:_mch-ups.com-1602223123624-57905; ups_language_preference=zh_CN; alertsHide=true; CONSENTMGR=consent:true%7Cts:1603964429164; X-CSRF-TOKEN=CfDJ8Jcj9GhlwkdBikuRYzfhrpLpAATOyH27PT6fWov5aKk9LMWTp-_3h6_0xLa2iB8E7Okaj2oXWXcdvRjmI-qM5GOsXr0cSWaZn88ji8ZBt1gLsdRDCmeAcjIktG9LMfE8VHkzL8-DKRvCgfNx3GP5Ssk; X-XSRF-TOKEN-ST=CfDJ8Jcj9GhlwkdBikuRYzfhrpKmatUqefMnApSa7cVefEvegdJSZ-avsDxPaM01Pl4Lb6dY1wDCl12UCwL7GKtmNaqIVRgMIXLG4CV23VvLTDMEu-GCAJZ6Qx8NkaB84Kbnb86nJfd60Cws1uKRm141sKE; ak_bmsc=05EA034944AD5C3CF6F3A58B673C88D6DE8A050FCD3C00007708A95FDA000B1E~plwyTZ2cf9n8ExbH0axkKsOsWUBvDVsM116m3SD/sNIQb8P2MeLlqC0LVFN7Q3gp1SHqbiD0vmnvwIkQp+hV/Yo0IxqFMPi7xY+wy3ZsZ7I8zMSG6B0xeU6HC2ojYvDrXcicJTY/nrDKOpHlpBipTB7aQg7Es2yz8ycGHGfKCJmXeXvMfPoUVFT3ipEKaNGiIkmlOx9EODp2q6CEt3BAPFuiapIN0RVSnH4q7VsKh6+Zc=; bm_sz=680EADB2D90231726D08AC08D6B00AA3~YAAQDwWK3rNE3Zt1AQAACxNJrAmUrA9g0xOnUei5g/Phz/t4/7NJpAvpLi+BRGhED+/2ULmcnUfFpkTYe5MZfMbnUNgIUJ/2f2dGTvS08DJqNTtVDMh0oXwFt6KAWE70mIcGwtQh1I++AGsuHjz1OwnZgZHr2JW3TSsnmVDW7/qkIEecZZv84GRug0s/; at_check=true; AMCVS_036784BD57A8BB277F000101%40AdobeOrg=1; AMCV_036784BD57A8BB277F000101%40AdobeOrg=-408604571%7CMCIDTS%7C18576%7CMCMID%7C54089497574780712661644925274649213321%7CMCAAMLH-1605518099%7C11%7CMCAAMB-1605518099%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCOPTOUT-1604920499s%7CNONE%7CvVersion%7C4.6.0%7CMCCIDH%7C-557739997; mbox=PC#071af9001a1b452a8898b410ac222df3.38_0#1668158100|session#ffe5a20503e3460c95ff2e1203648ab3#1604915159; mboxEdgeCluster=38; JSESSIONID=3CACD255FEB75C07F04A0B615D583D41; s_vnum=1606752000094%26vn%3D1; s_invisit=true; dayssincevisit_s=More%20than%207%20days; s_cc=true; utag_main=_sn:8$_se:2$_ss:0$_st:1604915136404$vapi_domain:ups.com$v_id:017337d96bc2001ba147ed1d5aec03073005906b00bd0$ses_id:1604913299491%3Bexp-session$_pn:1%3Bexp-session$_prevpage:ups%3Acn%3Azh%3Atrack%3Aapi%3Atrack%3Agetadditionalpackages%3Bexp-1604916936424; s_nr=1604914070247-Repeat; dayssincevisit=1604914070248',
                            "Host": "www.ups.com",
                            "Origin": "https://www.ups.com",
                            "Pragma": "no-cache",
                            "Referer": "https://www.ups.com/track/api/Track/GetAdditionalPackages?loc=zh_CN&requester=ST/trackdetails",
                            "Sec-Fetch-Dest": "empty",
                            "Sec-Fetch-Mode": "cors",
                            "Sec-Fetch-Site": "same-origin",
                            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36",
                            "X-XSRF-TOKEN": "CfDJ8Jcj9GhlwkdBikuRYzfhrpKmatUqefMnApSa7cVefEvegdJSZ-avsDxPaM01Pl4Lb6dY1wDCl12UCwL7GKtmNaqIVRgMIXLG4CV23VvLTDMEu-GCAJZ6Qx8NkaB84Kbnb86nJfd60Cws1uKRm141sKE"
                        }
                    url = "https://www.ups.com/track/api/Track/GetAdditionalPackages?loc=zh_CN"
                    try:
                        time.sleep(random.uniform(3, 8))
                        re_sess.mount("https://www.ups.com", py_ja3.DESAdapter())
                        print('data:::', data)
                        req = requests.post(url, headers=headers, data=json.dumps(data),
                                            timeout=20, verify=False)
                        res = json.loads(req.content.decode())
                        if res.get("trackDetail"):
                            trackingNumber_list = res["trackDetail"]["additionalPackages"]
                            if trackingNumber_list:
                                state = True
                                for trackingNumber in trackingNumber_list:
                                    # while True:
                                    #     try:
                                    #         data_ = {"Locale": "zh_CN",
                                    #                  "TrackingNumber": [f"{trackingNumber['trackingNumber']}"],
                                    #                  "Requester": "wt/",
                                    #                  "returnToValue": ""}
                                    #         print("请求子单号：：", data_)
                                    #         time.sleep(random.uniform(1.5, 3.5))
                                    #         req_ = requests.post(
                                    #             'https://www.ups.com/track/api/Track/GetStatus?loc=zh_CN',
                                    #             headers=headers, data=json.dumps(data_),
                                    #             proxies=self.proxy_get(),
                                    #             timeout=20, verify=False)
                                    #         break
                                    #     except Exception as e:
                                    #         print('子单号报错:', trackingNumber['trackingNumber'], e, '233333333333')
                                    #         time.sleep(random.uniform(3, 8))
                                    # res_json = req_.content.decode('utf-8')
                                    self.Number_list.append(
                                        [UPS_orders, provider_name, trackingNumber['trackingNumber'],
                                         trackingNumber['packageStatus'], json.dumps(res)])
                            else:
                                if state == False:
                                    try:
                                        self.Number_list.append(
                                            [UPS_orders, provider_name, res["trackDetail"]["errorCode"],
                                             res["trackDetail"]["errorText"],
                                             json.dumps(res)])
                                    except:
                                        self.Number_list.append([UPS_orders, provider_name, None, None, None])
                                break
                    except Exception as e:
                        print(UPS_orders_FBA, f"请求报错", e, f"\n{traceback.format_exc()}")
                        time.sleep(random.uniform(3, 8))
                        self.err_lsit.append(UPS_orders)
                        break
            else:
                break

    def get_17_event_id(self, data):
        import execjs
        with open('17encrypt.js', 'r', encoding='utf-8')as f:
            js_17_cookie = f.read()
        ck = execjs.compile(js_17_cookie)
        cookies = ck.call('getCookie', data)
        f.close()
        return cookies


    def get_A_array(self):
        import js2py
        with open("17track4.js", "r", encoding="utf-8")as f:
            m = js2py.EvalJs()
            m.execute(f.read())
            return m.A()

    def p0(self, V):
        t = str(hex(int(time.time()) * 1000)).replace("0x", "")
        # V = f":false:1854735704:0:0/{t}/11/true/-480/1854735704/ed8ccea"
        a = list(V)
        a.reverse()
        d = "".join(a)
        print(d)

        t = 0
        n = None
        while t < len(d):
            if True:
                if not n:
                    n = str(hex(ord(d[t]))).replace("0x", "")

                else:
                    n += str(hex(ord(d[t]))).replace("0x", "")

            else:
                pass
            t += 1
        return n

    def get_j_array(self, V, T):
        import js2py
        with open("17track4.js", "r", encoding="utf-8")as f:
            m = js2py.EvalJs()
            m.execute(f.read())
            return m.j(V, T)

    def T_N(self, d=43):
        return int(random.random() * d)

    def LastEventID(self):
        # d = '{"data":[{"num":"5004339145","fc":0,"sc":0}],"guid":"","timeZoneOffset":-480}'
        # n = len(data)
        T = self.T_N()
        h1 = str(hex(T)).replace("0x", '')
        h2 = len(h1)
        # h5
        j = 192801281
        p5 = "0" + str(hex(j)).replace("0x", '')

        a = self.get_A_array()
        # ":false:1854735704:26:832/187c048a57f/11/true/-480/1854735704/ed8ccea"
        V = f":false:{a}:{T}:{T * 32}"
        t = str(hex(int(time.time()) * 1000)).replace("0x", "")
        V += f"/{t}/11/true/-480/{a}/ed8ccea"

        j = self.get_j_array(V, T)
        return "".join([self.p0(V), h1, str(h2), '4', str(hex(j)).replace("0x", ""), '0b7dea01'])

    # LastEventID('{"data":[{"num":"771868666364","fc":0,"sc":0}],"guid":"","timeZoneOffset":-480}')

    def get_fedex_dhl(self, transport_sn_list):
        for transport_sn in transport_sn_list:
            fedex_dhl_FBA = transport_sn.split('|')
            print("fedex_dhl_FBA:", fedex_dhl_FBA)
            fh_orders = fedex_dhl_FBA[0]
            provider_name = fedex_dhl_FBA[1]
            if provider_name == 'dhl':
                fc = 100001
            else:
                fc = 100003
            data = '{"data":[{"num":"' + fh_orders + '","fc":'+ str(fc) +',"sc":0}],"guid":"","timeZoneOffset":-480}'
            cookie = self.get_17_event_id(data)
            # cookie = self.LastEventID()
            # cookie = LastEventID(data)
            print('cookie::', cookie)
            headers = {
                'origin': 'https://t.17track.net',
                'pragma': 'no-cache',
                'referer': 'https://t.17track.net/zh-cn',
                'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-origin',
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
            }
            headers['cookie'] = '_yq_bid=G-1EF8C052A10539EA;' + 'Last-Event-ID='+cookie
            print(headers['cookie'])
            try:
                re_sess.mount("https://", py_ja3.DESAdapter())
                r_sp = re_sess.post('https://t.17track.net/track/restapi', data=data, headers=headers, timeout=30,proxies=self.proxy_get())
                data_dict = json.loads(r_sp.text)
                print('data_dict::', data_dict)
                print('========================================================')
                data_2 = '{"data":[{"num":"' + fh_orders + '","fc":' + str(fc) + ',"sc":0}]' + ',"guid":' + '"'+ data_dict['guid'] + '"' + ',"timeZoneOffset":-480}'
                print('data_2::', data_2)
                rsop = re_sess.post('https://t.17track.net/track/restapi', data=data_2,
                                    headers=headers, timeout=30)
                data_dict = json.loads(rsop.text)
                prior_status = data_dict['shipments'][0]['prior_status']
                state = data_dict['shipments'][0]['state']
                print('data_dict22222222222::', data_dict)
                print('请求单号:', fh_orders, " prior_status:", prior_status, ' state:', state)
                if 'NotFound' in prior_status and 'Failure' in state:
                    print('NotFound-------Failure')
                    time.sleep(random.uniform(2, 5.5))
                    self.dhl_get_2(transport_sn)
                elif 'Delivered' in prior_status and 'Failure' in state:
                    self.fh_number_list.append([fh_orders, provider_name, None, prior_status, json.dumps(data_dict)])
                else:
                    self.fh_number_list.append(
                        [fh_orders, provider_name, None, prior_status, json.dumps(data_dict)])

                time.sleep(random.uniform(3, 5))
                # break
            except Exception as e:
                print('报错：：：', e)
                time.sleep(random.uniform(2, 5.5))
                # self.dhl_get_2(transport_sn)

        return self.fh_number_list

    def dhl_get_2(self, transport_sn):
        fedex_dhl_FBA = transport_sn.split('|')
        print("dhl_get_223:", fedex_dhl_FBA)
        fh_orders = fedex_dhl_FBA[0]
        provider_name = fedex_dhl_FBA[1]
        if provider_name == 'dhl':
            fc = 100001
        else:
            fc = 100003
        data = '{"data":[{"num":"' + fh_orders + '","fc":' + str(fc) + ',"sc":0}],"guid":"","timeZoneOffset":-480}'
        cookie = self.get_17_event_id(data)
        # cookie = self.LastEventID()
        # cookie = LastEventID(data)
        print('cookie::', cookie)
        headers = {
            'origin': 'https://t.17track.net',
            'pragma': 'no-cache',
            'referer': 'https://t.17track.net/zh-cn',
            'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
        }
        # headers['cookie'] = "country=CN;" + cookie
        headers['cookie'] = '_yq_bid=G-1EF8C052A10539EA;' + 'Last-Event-ID=' + cookie
        for i in range(3):
            try:
                re_sess.mount("https://", py_ja3.DESAdapter())
                r_sp = re_sess.post('https://t.17track.net/track/restapi', data=data, headers=headers, timeout=30
                                     )
                data_dict = json.loads(r_sp.text)
                prior_status = data_dict['shipments'][0]['prior_status']
                state = data_dict['shipments'][0]['state']
                print('dhl_get_2 参数请求 请求单号:', fh_orders, " prior_status:", prior_status, ' state:', state)
                if 'NotFound' in prior_status and 'Failure' in state:
                    print('dhl_get_2 NotFound-------Failure')
                    time.sleep(random.uniform(3, 8.5))
                    continue
                elif 'Delivered' in prior_status and 'Failure' in state:
                    self.fh_number_list.append([fh_orders, provider_name, None, prior_status, json.dumps(data_dict)])
                    break
                else:
                    self.fh_number_list.append(
                        [fh_orders, provider_name, None, prior_status, json.dumps(data_dict)])
                    break
            except Exception as e:
                print('dhl_get_2 带参数请求 报错：12121：：', e)
                time.sleep(random.uniform(3, 8.5))
                continue

    def save_data(self, Number_list, provider_name=None):
        while True:
            try:
                df_roder_detail = pd.DataFrame(data=Number_list,
                                               columns=['transport_sn', 'provider_name',
                                                        'ups_orders', 'transport', 'data_json'])
                self.asin_list_update = list(df_roder_detail.transport_sn)
                if Number_list and provider_name is None:
                    print(f"ups_orders_detail---{len(Number_list)}--")
                    if df_roder_detail.shape[0] > 0:
                        df_roder_detail.drop_duplicates(['transport_sn'], inplace=True)  # 去重
                        with self.engine.begin() as conn:
                            if len(set(df_roder_detail.transport_sn)) == 1:
                                sql_delete_bsr = f"delete from ups_orders_detail where transport_sn in ('{tuple(df_roder_detail.transport_sn)[0]}');"
                            else:
                                sql_delete_bsr = f"delete from ups_orders_detail where transport_sn in {tuple(set(df_roder_detail.transport_sn))};"
                            conn.execute(sql_delete_bsr)

                else:
                    if df_roder_detail.shape[0] > 0:
                        df_roder_detail.drop_duplicates(['transport_sn', 'ups_orders'], inplace=True)  # 去重
                        with self.engine.begin() as conn:
                            for Number in Number_list:
                                sql_delete = f"delete from ups_orders_detail where transport_sn='{Number[0]}' and ups_orders='{Number[2]}';"
                                print('ups 删除：', sql_delete)
                                conn.execute(sql_delete)
                df_roder_detail.to_sql('ups_orders_detail', con=self.engine, if_exists='append',
                                       index=False)
                break
            except Exception as e:
                print(e, 'eeeeeeeeeeeee')
                self.mysql_reconnect()
                time.sleep(20)
                continue

        if self.asin_list_update:
            self.db_change_state(state=3, asin_list=self.asin_list_update)
            self.asin_list_update = []
        if self.err_lsit:
            self.db_change_state(state=1, asin_list=self.err_lsit)
            self.err_lsit = []
            self.fh_number_list = []
        self.update_num += 1

    def db_change_state(self, state=2, asin_list=None):
        self.db_change_state_common(state=state, asin_list=list(set(asin_list)))

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

    def init_list(self):
        self.asin_list_update = []
        self.err_lsit = []
        self.transport_sn_queue = Queue()
        self.Number_list = []
        self.fh_number_list = []
        self.get_token()

    def update_prior_status(self):
        now_time = datetime.datetime.now()
        up_time = (now_time + datetime.timedelta(hours=-36)).strftime("%Y-%m-%d %H:%M:%S")
        up_1_time = (now_time + datetime.timedelta(hours=-0.6)).strftime("%Y-%m-%d %H:%M:%S")
        for i in range(3):
            try:
                with self.engine.begin() as conn:
                    sql = "UPDATE ups_orders_syn a, ups_orders_detail b  set a.prior_status=1,a.state=3 WHERE a.transport_sn=b.transport_sn and b.transport='Delivered'"
                    conn.execute(sql)
                    sql2 = "UPDATE ups_orders_syn a, ups_orders_detail b  set a.prior_status=1,a.state=3 WHERE a.transport_sn=b.transport_sn and b.transport='已递送'"
                    conn.execute(sql2)
                    sql3 = f"UPDATE  ups_orders_syn a, ups_orders_detail b set a.state=1   WHERE a.transport_sn=b.transport_sn and b.transport!='Delivered' and a.provider_name='dhl' and a.prior_status=0 and b.updated_at <'{up_time}'"
                    conn.execute(sql3)
                    sql4 = f"UPDATE  ups_orders_syn a, ups_orders_detail b set a.state=1 WHERE a.transport_sn=b.transport_sn and b.transport!='Delivered' and a.provider_name='fedex' and a.prior_status=0 and b.updated_at <'{up_time}'"
                    conn.execute(sql4)
                    sql5 = f"UPDATE  ups_orders_syn a, ups_orders_detail b set a.state=1 WHERE a.transport_sn=b.transport_sn and b.transport!='已递送' and a.provider_name='ups' and a.prior_status=0 and b.updated_at <'{up_time}'"
                    conn.execute(sql5)
                    sql_6 = f"update ups_orders_syn set state = 1  where state = 2 and updated_at <'{up_1_time}'"
                    conn.execute(sql_6)
                    break
            except:
                time.sleep(5)
                continue

    def run(self):
        while True :
            transport_sn_list = self.read_db_data(provider_name=1)
            if transport_sn_list:
                for transport_sn in transport_sn_list:
                    self.transport_sn_queue.put(transport_sn)
                html_thread = []
                for i in range(10):
                    thread2 = threading.Thread(target=self.get_orders_state)
                    html_thread.append(thread2)
                for ti in html_thread:
                    ti.start()
                    time.sleep(random.uniform(1, 8.5))
                for t2 in html_thread:
                    t2.join()
                self.save_data(self.Number_list, provider_name=1)
                self.init_list()
                if self.update_num > 5:
                    self.update_prior_status()
                    self.update_num = 0
            else:
                break

    def dhl_fedex(self):
        while True:
            transport_sn_list = self.read_db_data()
            if transport_sn_list:
                fh_number_list = self.get_fedex_dhl(transport_sn_list)
                self.save_data(fh_number_list)
                self.init_list()
                if self.update_num > 5:
                    self.update_prior_status()
                    self.update_num = 0
            else:
                break

    def Poll_ups(self):
        self.update_prior_status()
        if platform.system().lower() == 'windows':
            self.dhl_fedex()
        else:
            self.run()



if __name__ == '__main__':
    Get_ups().Poll_ups()
