from time import sleep
import platform

from config import readConfig
from src.framework.common import get_token

# pages基类
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
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, func=0):
        if func == 0:
            self.find_element(*loc).click()
        else:
            self.find_element(*loc).send_keys(Keys.ENTER)

    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 refresh(self):
        return self.driver.refresh()

    # 查找文本，点击该文本元素
    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 ifElementClickable(self, loc):
        try:
            EC.element_to_be_clickable(self.driver.find_element(*loc))
        except Exception:
            # 打印异常信息
            print("ElementUnclickable")
            # 发生异常，说明页面中未找到该元素，返回False
            return False
        else:
            print("Elementclickable{}".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_dominance(self, loc):
        self.driver.execute_script("document.getElementsByClassName('{}')[0].style.position = 'static'".format(loc))

    # 操作脚本-元素display
    def excute_script_display(self, loc):
        self.driver.execute_script("document.getElementsByClassName('{}')[0].style.display = 'flex'".format(loc))

    # 大招！JS click!
    def excute_script_click(self, loc):
        self.driver.execute_script("document.getElementsByClassName('{}')[0].click()".format(loc))

    def excute_script_set_token(self, loc, ele):
        self.driver.execute_script("""window.localStorage.setItem("{}", "{}")""".format(loc, ele))

    def excute_script_set_url(self):
        self.driver.execute_script("XMHistory.push({pathname: `/home`,})")

    # 切换窗口，切换到存在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, user='lgw-b'):
        driver = self.driver
        sleep(15)
        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")
        # 取消按钮
        cancel_btn = (By.XPATH, """//span[text()="{}"]""".format("取 消"))
        # 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_dominance("form xm_phone_login")
        # login_page.sleep(2)
        # 方法3，注入localStorage
        enterpriseId = readConfig.test_header(user)['enterpriseId']
        get_localStorage = get_token(user)
        login_page.excute_script_set_token("xmykt-client_token", get_localStorage['xmToken'])
        login_page.excute_script_set_token("xmykt-client_enterpriseId", enterpriseId)
        login_page.excute_script_set_token("xmykt-client_userId", get_localStorage['userId'])
        login_page.excute_script_set_url()
        login_page.sleep(2)

        # login_page.input_text(account_input, readConfig.test_header(user)['username'])
        # login_page.input_text(password_input, readConfig.test_header(user)['password'])
        # login_page.click(login_button)
        # login_page.sleep(2)
        if login_page.ifElementExist(cancel_btn):
            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()

    # 鼠标从ele元素开始移动（x,y）个像素后点击
    def mouse_move_with_ele(self, ele, x, y):
        ActionChains(self.driver).move_to_element_with_offset(to_element=ele, xoffset=x, yoffset=y).perform()

    # 鼠标悬停直至元素出现
    def mouse_stop_until_ele_show(self, *ele):
        if len(ele) == 2:
            ActionChains(self.driver).move_to_element(ele[0]).perform()
            try:
                WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(ele[1]))
            except Exception as e:
                print(e.args)
                pass
        else:
            ActionChains(self.driver).move_to_element(ele).perform()
