import pyautogui
from bs4 import BeautifulSoup
from retry import retry
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from bson import ObjectId
import pymongo
from base import BaseCore
baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()
db_storage = pymongo.MongoClient('mongodb://114.115.221.202:27017/', username='admin', password='ZZsn@9988').中科软[
    '数据源_0106']

# 获取当前活动窗口的标题
def get_active_window_title():
    window = pyautogui.getActiveWindow()
    log.info(f'当前活动窗口的标题是：{window.title}')
    return window.title if window else None


@retry(tries=3, delay=1)
def Translate(_id, driver):

    driver.get('file:///C:/Users/EDY/Desktop/aaa.html')

    flag = driver.find_element(By.TAG_NAME, 'body').text
    driver.maximize_window()
    # 切换到Edge浏览器窗口
    driver.switch_to.window(driver.current_window_handle)
    # 等待一段时间，确保页面加载完成
    time.sleep(5)
    # 获取Edge浏览器窗口的句柄
    edge_handle = driver.current_window_handle
    # driver.refresh()
    # time.sleep(5)
    # 右键选择翻译
    rightClick = ActionChains(driver)
    position_element = driver.find_element(By.TAG_NAME, 'body')

    rightClick.context_click(position_element).perform()
    time.sleep(1)
    pyautogui.typewrite(['down'] * 6)
    pyautogui.typewrite(["enter"])

    js = "return action=document.body.scrollHeight"
    new_height = driver.execute_script(js)
    for i in range(0, new_height, 300):
        # js = "var q=document.documentElement.scrollTop=300"
        driver.execute_script(js)
        driver.execute_script('window.scrollTo(0, %s)' % (i))
        time.sleep(1)
    time.sleep(2)

    if driver.find_element(By.TAG_NAME, 'body').text[:500] in flag:
        log.error(f'{_id}---翻译失败,重试')
        # 使用pyautogui模块模拟按下Alt+Tab键，将Edge浏览器置于最前面
        # while get_a
        # ctive_window_title() != "Edge浏览器":
        while 'Microsoft​ Edge' not in get_active_window_title():
            pyautogui.hotkey('alt', 'tab')
            log.info('窗口切换操作')
        # pyautogui.hotkey('alt', 'tab')
        # 切换到Edge浏览器窗口
        driver.switch_to.window(edge_handle)
        driver.refresh()
        raise


    page_source = driver.page_source
    contentWithTag = BeautifulSoup(page_source, 'html.parser')
    db_storage.update_one({'_id':ObjectId(_id)},{'$set':{'postCode':'18','richText':str(contentWithTag)}})
    # with open(rf'C:\Users\EDY\Desktop\{_id}.html', 'w', encoding='utf-8') as f:
    #     f.write(str(contentWithTag))
    # print(str(contentWithTag))


def doJob():
    driver = webdriver.Edge()
    while True:
        datas = db_storage.find({'postCode':'2'}).limit(10)
        for data in datas:
            now = time.time()
            _id = str(data['_id'])
            richTextForeign = data['richTextForeign']
            with open(r'C:\Users\EDY\Desktop\aaa.html', 'w', encoding='utf-8') as f:
                f.write(str(richTextForeign))
            try:

                Translate(_id, driver)
                log.info(f'{_id}翻译用时--{time.time() - now}')
            except:
                log.error(f'{_id}翻译失败')


if __name__ == "__main__":
    doJob()
    baseCore.close()