from time import sleep
import platform

from config import readConfig

# pages基类
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By


class Page(object):
    """
        Page基类，所有page都应该继承该类
    """

    def __init__(self, driver):
        self.driver = driver
        self.timeout = 30

    # 寻找单元素或唯一元素
    def find_element(self, loc):
        return self.driver.find_element(*loc)

    # 输入元素输入
    def input_text(self, loc, text):
        try:
            self.find_element(loc).send_keys(text)
        except Exception:
            self.find_elements(loc)[0].send_keys(text)

    # 获取元素文本
    def get_text(self, loc):
        return self.driver.find_element(*loc).text

    # 点击框点击
    def click(self, *loc):
        self.find_element(*loc).click()

    def get_title(self):
        return self.driver.title

    # 打开url站点
    def open_url(self, url):
        self.driver.get(url)

    # 获取当前url
    def current_url(self):
        self.driver.current_url()

    # 关闭浏览器
    def quit_browser(self):
        self.driver.quit()

    # 浏览器前进操作
    def forward(self):
        self.driver.forward()

    # 浏览器后退操作
    def back(self):
        self.driver.back()

    # 清空输入框
    def clear(self):
        self.driver.clear()

    # 隐式等待
    def wait(self, seconds):
        self.driver.implicitly_wait(seconds)

    # 强制等待
    def sleep(self, seconds):
        return sleep(seconds)

    # 查找文本，点击该文本元素
    def click_text(self, ele):
        self.click((By.XPATH, """//span[text()="{}"]""".format(ele)))


    def click_what(self, ele_type, what, ele):
        self.click((By.XPATH, """//{}[{}="{}"]""".format(ele_type, what, ele)))

    # 键盘down
    def keys_down(self):
        ActionChains(self.driver).key_down(Keys.DOWN).key_up(Keys.DOWN).perform()

    # 键盘ctrl+M,command+m
    def get_env_window(self):
        if platform.system().lower() == "windows":
            # ActionChains(self.driver).send_keys(Keys.CONTROL, 'm').perform()
            # ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('m').key_up(Keys.CONTROL).perform()
            self.find_element((By.XPATH, "//div[@id='root']")).send_keys(Keys.CONTROL, 'm')

        elif platform.system().lower() == "darwin":
            ActionChains(self.driver).send_keys(Keys.COMMAND, "m").perform()

    # 屏幕最大化
    def max(self, *loc):
        self.driver.find_element(*loc).click()

    # 判断元素是否存在于页面
    def ifElementExist(self, loc):
        try:
            self.driver.find_element(*loc)
        except NoSuchElementException:
            # 打印异常信息
            print("NoSuchElementException")
            # 发生异常，说明页面中未找到该元素，返回False
            return False
        else:
            print("HaveSuchElement{}".format(loc))
            # 无异常，说明在页面中找到了该元素，返回True
            return True

    # 寻找多元素返回
    def find_elements(self, loc):
        return self.driver.find_elements(*loc)

    # 关闭窗口
    def close(self, loc, num):
        self.find_elements(*loc)[num].click()

    # 保存图片
    def save_screenshot(self, filename):
        self.driver.save_screenshot(filename)

    # 跳入iframe
    def switch_to_iframe(self, iframe_id):
        self.driver.switch_to.frame(iframe_id)

    # 跳出iframe
    def switch_to_current(self):
        self.driver.switch_to.default_content()

    # 操作脚本
    def excute_script(self, loc):
        self.driver.execute_script("document.getElementsByClassName('{}')[0].style.position = 'static'".format(loc))

    # 切换窗口，切换到存在loc元素的窗口
    def change_window(self, loc):
        driver = self.driver
        vars = driver.window_handles
        for var in vars:
            driver.switch_to_window(var)
            have_ele = self.ifElementExist(loc)
            if have_ele:
                break

    def login(self):
        driver = self.driver
        login_page = Page(driver=driver)
        # 手机号登录按钮
        phone_login = (By.ID, "rc-tabs-0-tab-2")
        # 账号输入框
        account_input = (By.ID, "xmphone")
        # 密码输入框
        password_input = (By.ID, "xmpwd")
        # 登录按钮
        login_button = (By.CLASS_NAME, "submit")
        # env = readConfig.get_env()
        # login_page.get_env_window()
        # login_page.click_what('span', 'text()', self.env)
        # login_page.click_close_env_window()
        # login_page.click_text(env)

        # 旧的登录方法
        login_page.click(phone_login)

        # 新的登录方法
        # 执行脚本，隐藏的手机号码输入框弹出
        # login_page.excute_script("form xm_phone_login")
        # login_page.sleep(2)

        login_page.input_text(account_input, readConfig.test_account())
        login_page.input_text(password_input, readConfig.test_password())
        login_page.click(login_button)
        login_page.sleep(2)
        login_page.click_text("取 消")
        login_page.sleep(3)

    # 鼠标键盘操作
    # 拖拽元素，从sourse元素开始拖拽（x,y）像素
    def drag_mouse(self, source, xoffset, yoffset):
        # ActionChains(self.driver).drag_and_drop_by_offset(source=source, xoffset=xoffset, yoffset=yoffset).perform()
        ActionChains(self.driver).click_and_hold(source).move_by_offset(xoffset, yoffset).release().perform()

    # 鼠标左键单击
    def left_click(self):
        ActionChains(self.driver).click().perform()

    # 鼠标移动（x,y）个像素后点击
    def mouse_move(self, x, y):
        ActionChains(self.driver).move_by_offset(xoffset=x, yoffset=y).click().perform()
