import subprocess
import time
import os
import sys
from datetime import datetime, time as dtime
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.service import Service

# 获取当前 exe 所在目录
BASE_DIR = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))

driver_path = os.path.join(BASE_DIR, "edge", "msedgedriver.exe")
service = Service(driver_path)

# 参数配置
PING_HOST = "www.baidu.com"
USERNAME = "hzxhc60125893"
PASSWORD = "125893"

CHECK_INTERVAL = 60
DISCONNECT_THRESHOLD = 300

# 运行时间段（6:30 到 0:30）
START_TIME = dtime(6, 30)
END_TIME = dtime(0, 30)

options = Options()
options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-blink-features=AutomationControlled")

service = Service("edge/msedgedriver.exe")


def log(msg):
    """带时间戳日志"""
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{now}] {msg}")


def is_in_runtime():
    """判断当前时间是否在运行时间段"""
    now = datetime.now().time()

    # 跨天时间段处理
    if START_TIME <= END_TIME:
        return START_TIME <= now <= END_TIME
    else:
        return now >= START_TIME or now <= END_TIME


def is_network_ok():
    """判断网络是否可用"""
    try:
        result = subprocess.run(
            ["ping", "-n" if subprocess.os.name == "nt" else "-c", "1", PING_HOST],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )
        return result.returncode == 0
    except:
        return False


def perform_login():
    """执行自动认证流程"""
    driver = None
    try:
        driver = webdriver.Edge(service=service, options=options)
        wait = WebDriverWait(driver, 30)

        driver.get("http://10.33.0.2")

        username_input = wait.until(
            EC.presence_of_element_located((By.ID, "username"))
        )
        username_input.clear()
        username_input.send_keys(USERNAME)

        password_input = driver.find_element(By.ID, "password")
        password_input.clear()
        password_input.send_keys(PASSWORD)

        log("已输入账号密码")

        login_btn = wait.until(
            EC.element_to_be_clickable((By.ID, "login-account"))
        )
        login_btn.click()

        log("已点击登录")

        success_confirm = wait.until(
            EC.element_to_be_clickable((By.CLASS_NAME, "btn-confirm"))
        )
        success_confirm.click()

        log("代拨成功")

        time.sleep(3)

    except Exception as e:
        log(f"登录过程中出现异常: {e}")

    finally:
        if driver:
            driver.quit()


def main():
    disconnect_time = 0

    try:
        while True:

            # 判断是否在运行时间段
            if not is_in_runtime():
                log("当前不在运行时间段，程序休眠")
                time.sleep(60)
                continue

            if is_network_ok():
                disconnect_time = 0
                log("网络正常")

            else:
                disconnect_time += CHECK_INTERVAL
                log(f"网络中断 {disconnect_time} 秒")

                if disconnect_time >= DISCONNECT_THRESHOLD:
                    log("断网超时，自动认证...")
                    perform_login()
                    disconnect_time = 0

            time.sleep(CHECK_INTERVAL)

    except KeyboardInterrupt:
        log("用户终止程序，退出中...")


if __name__ == "__main__":
    main()