# -*- coding: utf-8 -*-

from time import sleep
from random import randint
import os
os.environ['NO_PROXY'] = 'stackoverflow.com'
import logging
logging.captureWarnings(True)
from DrissionPage import ChromiumPage
import json
import requests
import re
import random
import time
from datetime import datetime, timedelta
from all_connect import ConnectSpider
Con = ConnectSpider()



class TT():
    def __init__(self):
        self.page = ChromiumPage()
        self.headers = {
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;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',
}

    def format_release_date(self,release_date):
        current_year = datetime.now().year

        # 判断是否包含年份（简单判断是否以数字开头且长度小于5）
        if release_date and '-' in release_date:
            parts = release_date.strip().split('-')
            if len(parts) == 2 and all(part.isdigit() for part in parts):
                # 没有年份，补上年份
                return f"{current_year}-{release_date}"

        # 有年份或格式不匹配，保持原样返回
        return release_date


    def get_details(self):
        while True:
            try:
                # 初始化浏览器对象
                self.page = ChromiumPage()
                self.account = "@heartygreet"
                video_id_id_pairs = Con.get_tiktok_data(self.account)

                all_items = []

                for count in range(len(video_id_id_pairs)):
                    item = {}  # 每次循环都创建新的 item 字典

                    item_id, view_href, view_count, page, index = video_id_id_pairs[count].split('||-||')

                    self.page.get(view_href)
                    time.sleep(randint(6, 12))

                    elements = self.page.eles('xpath=//div[contains(@class, "DivActionItemContainer")]//strong')
                    numbers = [ele.text for ele in elements]
                    likes_num = numbers[0]
                    comments_num = numbers[1]
                    collection_num = numbers[2]
                    shares_num = numbers[3] if len(numbers) > 3 and numbers[3].isdigit() else 0

                    print(numbers)
                    time.sleep(randint(3, 4))

                    release_date = self.page.ele(
                        'xpath=//span[@class="css-1kcycbd-SpanOtherInfos evv7pft3"]/span[3]').text
                    time.sleep(randint(2, 4))
                    print(release_date)

                    item['account'] = self.account
                    item['view_href'] = view_href
                    item['view_count'] = view_count
                    item['likes_num'] = likes_num
                    item['comments_num'] = comments_num
                    item['collection_num'] = collection_num
                    item['shares_num'] = shares_num
                    item['release_date'] = self.format_release_date(release_date)
                    item['page'] = page
                    item['index'] = index
                    item['state'] = 1
                    item['created_at'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                    all_items.append(item)

                    # 单条数据保存
                    Con.save_tiktok_details([item])
                    print(f'{index} save success')

                    # 更新状态
                    Con.update_tk_to_3(item_id)
                    print(f'{index} update success')

                print(all_items)
                break  # 如果一切顺利，跳出循环

            except Exception as e:
                print(f"出现错误: {e}")
                if "list index out of range" in str(e):
                    print("列表索引超出范围，等待5分钟后重试...")
                    time.sleep(1800)  # 等待5分钟
                else:
                    print("发生了其他类型的错误，退出程序。")
                    return False

if __name__ == '__main__':
    ck = TT().get_details()





