

import os
os.environ['NO_PROXY'] = 'stackoverflow.com'
import logging
logging.captureWarnings(True)
from DrissionPage import ChromiumPage,ChromiumOptions
import time
from datetime import datetime, timedelta
from time import sleep
from random import randint
import requests
import math
import pandas as pd
import redis
import json
from pathlib import Path
import re



class TkOrderExport():
    def __init__(self):
        co = ChromiumOptions().headless()
        self.page = ChromiumPage(co)
        # 修改请求头
        self.headers = {
            'accept': '*/*',
            'accept-language': 'en-US,en;q=0.9', # 'en-US,en;q=0.9'
            'cache-control': 'no-cache',
            'content-type': 'application/json; charset=UTF-8',
            'origin': 'https://www.tiktok.com',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://www.tiktok.com/',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'cross-site',
            'sec-fetch-storage-access': 'active',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
        }
        self.shop_code_ceshi = "CNUSCB78ELWE"

        # 店铺账号
        self.account = 'PatelaiChank@outlook.com'
        # 下载文件路径
        self.download_folder = r"D:\Downloads"
        self.file_suffix = ".xlsx"  # 设置你期望的文件名后缀（包括点）
        self.receiver_name = 'wangjing5'

        # Redis 配置信息
        self.REDIS_CONFIG =  {
            'host': '120.79.147.190',
            'port': 6379,
            'password': 'fG7#vT6kQ1pX',
            'db': 13,
            'decode_responses': True
        }

        self.url = "https://affiliate.tiktokglobalshop.com/product/order?shop_region=US"
        self.cookies = self.get_cookies()

    def login_with_cookies(self):
        # 检查是否登录状态
        try:
            self.page.get(self.url)
            self.page.set.window.max()

            tou_xiang = self.page.ele('xpath://span[@class="m4b-avatar-image"]', timeout=10)
            tou_xiang.click()
            sleep(randint(5, 10))

            self.store_name = self.page.ele('xpath://div[@class="text-body-m-medium text-neutral-text1"]',timeout=10).text
            print('店铺名：', self.store_name)
            sleep(randint(1, 3))

            self.shop_code = self.page.ele('xpath://div[@class="text-body-s text-neutral-text4"]/span', timeout=10).text
            self.shop_code = self.shop_code.split(': ')[1]
            print('店铺编号：', self.shop_code)
            sleep(randint(1, 3))

            if self.shop_code and str(self.shop_code) == self.shop_code_ceshi:
                print("在登录状态")


            else:
                print("不一样")
                raise
        except:
            print("需要登录")
            try:
                # 打开一个空白页，否则无法设置 cookie
                self.page.get('https://www.tiktok.com')

                # 设置 cookies
                for ck in self.cookies:
                    self.page.set.cookies(ck)

                # 重新打开目标网址，此时应为已登录状态
                self.page.get(self.url)
                time.sleep(5)

            except:
                print("登录失败")

    def save_cookie(self, cookies):
        """将整个 cookies 列表一次性存入 Redis，作为一条 JSON 数据"""
        key = f"tk_shop_cookie:{self.shop_code}:order:list"

        # 将整个 cookies 列表转换为 JSON 字符串
        value = json.dumps(cookies, ensure_ascii=False)

        # 存储到 Redis（覆盖旧数据）
        self.r.set(key, value)
        print(f"💾 已将 {len(cookies)} 个 cookie 存入 Redis，键为: {key}")

    def get_cookies(self):
        self.r = redis.StrictRedis(**self.REDIS_CONFIG)
        """从 Redis 中获取并解析 cookies"""
        key = f"tk_shop_cookie:{self.shop_code_ceshi}:order:list"
        cookie_json = self.r.get(key)

        if cookie_json:
            cookies = json.loads(cookie_json)
            print(f"🔄 从 Redis 成功读取 {len(cookies)} 个 cookie")
            return cookies
        else:
            print("❌ 未找到对应的 cookie 数据")
            return None

    def change_language(self):
        self.login_with_cookies()
        retry_num = 0
        max_retry = 1  # 最多重试次数
        while retry_num <= max_retry:
            try:
                tou_xiang = self.page.ele('xpath://span[@class="m4b-avatar-image"]', timeout=10)
                tou_xiang.click()
                sleep(randint(5, 10))

                self.store_name = self.page.ele('xpath://div[@class="text-body-m-medium text-neutral-text1"]',timeout=10).text
                print('店铺名：', self.store_name)
                sleep(randint(1, 3))

                self.shop_code = self.page.ele('xpath://div[@class="text-body-s text-neutral-text4"]/span',
                                               timeout=10).text
                self.shop_code = self.shop_code.split(': ')[1]
                print('店铺编号：', self.shop_code)
                sleep(randint(1, 3))

                cookies = self.page.cookies()
                self.save_cookie(cookies)
                self.send_success_message_via_wechat()

                break

            except Exception as e:
                print(f"change_language出现错误: {e}")
                self.send_error_notification_via_wechat(e)
                if "没有" in str(e):
                    retry_num += 1
                    sleep(5)
                else:
                    raise
        self.page.quit()

    def connect_redis(self):
        """建立 Redis 连接"""
        self.r = redis.StrictRedis(**self.REDIS_CONFIG)
        try:
            self.r.ping()  # 测试连接
            print("✅ 成功连接到 Redis")
        except redis.exceptions.ConnectionError as e:
            print(f"❌ 无法连接到 Redis: {e}")
            raise

    def send_success_message_via_wechat(self):
        webhook_url = 'http://47.112.96.71:8082/selection/sendMessage'  # 替换为你的企业微信机器人的Webhook URL
        data = {
            "account": self.receiver_name,
            "title": '【TK获取cookie成功提醒】',
            "content": f'账号: {self.account}, 店铺: {self.store_name}, 程序运行时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'
        }

        response = requests.post(url=webhook_url, data=data, timeout=15)
        if response.status_code == 200:
            print("已成功发送通知到企业微信")
        else:
            print(f"发送通知失败: {response.text}")

    def send_error_notification_via_wechat(self, error_message):
        webhook_url = 'http://47.112.96.71:8082/selection/sendMessage'  # 替换为你的企业微信机器人的Webhook URL
        data = {
            "account": self.receiver_name,
            'title': '【TK获取cookie异常提醒】',
            'content': f'账号：{self.account}，店铺：{self.store_name},错误信息：{error_message}, 时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}'
        }

        response = requests.post(url=webhook_url, data=data, timeout=15)
        if response.status_code == 200:
            print("已成功发送错误通知到企业微信")
        else:
            print(f"发送错误通知失败: {response.text}")

    def run(self):
        self.connect_redis()
        self.change_language()
        # self.page.quit()

if __name__ == '__main__':
    TkOrderExport().run()



















