"""模拟扫码登录"""
import json
import time

import pymongo
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from base.BaseCore import BaseCore
from pymysql.converters import escape_string

baseCore = BaseCore()
log = baseCore.getLogger()
cnx_ = baseCore.cnx
cursor_ = baseCore.cursor
from selenium.webdriver.chrome.service import Service
def createDriver_():
    path = r'D:\soft\msedgedriver.exe'
    # path = r'F:\spider\117\msedgedriver.exe'

    options = {
        "browserName": "MicrosoftEdge",
        "ms:edgeOptions": {
            "extensions": [], "args": ["--start-maximized"]  # 添加最大化窗口运作参数
        }
    }
    edge_options = Options()
    edge_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 禁用启用Blink运行时的功能
    edge_options.add_argument('--disable-blink-features=AutomationControlled')
    session = webdriver.Edge(executable_path=path, capabilities=options)
    return session

def createDriver():
    chrome_driver = r'D:\cmd100\chromedriver.exe'
    path = Service(chrome_driver)
    chrome_options = webdriver.ChromeOptions()
    chrome_options.binary_location = r'D:\Google\Chrome\Application\chrome.exe'
    # chrome_options.add_argument("--disable-javascript")
    # 设置代理
    # proxy = "127.0.0.1:8080"  # 代理地址和端口
    # chrome_options.add_argument('--proxy-server=http://' + proxy)
    driver = webdriver.Chrome(service=path, chrome_options=chrome_options)
    return driver

def flushAndGetToken():
    log.info('======刷新浏览器=====')
    browser.refresh()
    cookie_list = browser.get_cookies()
    cookies = {}
    print(cookie_list)
    # for cookie in cookie_list:
    #     cookies[cookie['name']] = cookie['value']
    # print(cookies)
    # return cookies
    print(type(cookie_list))
    return cookie_list


if __name__ == "__main__":
    while True:
        userName = input('请输入登录账号：')
        urlqcc = 'https://www.qcc.com/'
        browser = createDriver()
        browser.get(urlqcc)
        wait = WebDriverWait(browser, 10)
        wait.until(EC.presence_of_element_located((By.CLASS_NAME, "nav-item")))
        browser.find_element(By.CLASS_NAME, 'nav-item').click()
        while True:
            try:
                wait.until(EC.presence_of_element_located((By.CLASS_NAME, "login-madal-dialog-new")))
                time.sleep(5)
            except:
                break
        browser.get('https://www.qcc.com/web/search?key=%E9%B2%81%E8%A5%BF%E5%8D%97%E5%8C%BB%E9%99%A2%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8')
        time.sleep(2)
        cookies = flushAndGetToken()
        cookies = str(cookies)
        # dic = {
        #     'userName':userName,
        #     'cookies':cookies,
        #     'createDate':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        #     'fenghaoTime':(datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'),
        #     'updateDate':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # }
        insert = f"insert into QCC_token (cookies,create_time,fenghao_time,update_time,user_name) values ('{escape_string(cookies)}',now(),DATE_SUB(NOW(), INTERVAL 1 DAY),now(),'{userName}')"
        print(insert)
        cursor_.execute(insert)
        cnx_.commit()
        # db_storageInsert.insert_one(dic)
        browser.close()
        flg = input('是否继续登录')
        if flg == 'N' or flg == 'n':
            break
    baseCore.close()





