from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select

from common.untils import DriverTools


class BasePage:
    def __init__(self, type="web"):
        if type == "web":
            self.driver = DriverTools.get_driver()
        elif type == "app":
            self.driver = DriverTools.get_app_driver()
        else:
            print("页面类型输入错误，请输入web/app")

    # 查找元素
    def find_ele(self, loc, time=10, fre=1):
        ele = WebDriverWait(self.driver, time, fre).until(lambda x: x.find_element(*loc))
        return ele

    # 输入内容
    def input_text(self, loc, value):
        ele = self.find_ele(loc)
        ele.clear()
        ele.send_keys(value)

    # 滚动条
    def scroll(self, x, y):
        js = "window.scrollTo({},{})".format(x, y)
        self.driver.execute_script(js)

    # 下拉框文本选择
    def select_text(self, loc, text):
        select = Select(self.find_ele(loc))
        select.select_by_visible_text(text)

    # 获取标题
    def get_title(self):
        title = self.driver.title
        return title

    # 获取url
    def get_url(self):
        url = self.driver.current_url
        return url

    # 鼠标悬停
    def mouse_stop(self, loc):
        action = ActionChains(self.driver)
        action.move_to_element(self.find_ele(loc))
        action.perform()

    # 获取弹出框文本内容
    def alert_text(self):
        alert = self.driver.switch_to.alert
        text = alert.text
        return text

    # 切换弹窗
    def windows_change(self, num):
        self.driver.switch_to.window(self.driver.window_handles[num])

    # 关闭弹窗
    def close_window(self):
        self.driver.close()
