import os
from PIL import Image
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from time import sleep
import logging
import time


# 点击当前页面中的查询按钮
def click_query(driver):
    is_element_load(driver, '//div[@class = "list-flex flex"]/span')
    span = driver.find_element_by_xpath('//div[@class = "list-flex flex"]/span')
    querys = span.find_elements_by_tag_name('button')
    for query in querys:
        text = query.text
        if text == '查询' or text == '查 询':
            query.click()
            break


# 检查元素是否被加载到
def is_element_load(driver, xpath):
    try:
        WebDriverWait(driver, 2, 0.1).until(lambda d: driver.find_element_by_xpath(xpath), message=xpath + '加载超时')
        return True
    except:
        return False


# 如果有隐藏按钮,就点击
def click_hide(driver):
    is_element_load(driver, '//div[@class = "list-flex flex"]/span')
    span = driver.find_element_by_xpath('//div[@class = "list-flex flex"]/span')
    divs = span.find_elements_by_tag_name('div')
    for hide in divs:
        text = hide.get_attribute('class')
        # 关闭状态
        if text == 'button_spacing button_shrink_bottom':
            sleep(0.5)
            hide.click()
            break
        # 打开状态
        elif text == 'button_spacing button_shrink_top':
            break
        # 没有隐藏按钮
        else:
            continue


# 判断元素是否存在
def is_element_exist(browser, element):
    try:
        browser.find_element_by_xpath(element)
        return True
    except:
        return False


def isset(v):
    try:
        type(eval(v))
    except:
        return 0
    else:
        return 1


# 关闭当前页面
def close_page(driver):
    move = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div[3]/div/article/div/div[2]/div[1]/'
                                        'div[2]/div/div/div/ul/li/a/span')
    ActionChains(driver).move_to_element(move).perform()
    if is_element_load(driver, '/html/body/div[1]/div[1]/div/div[3]/div/article/div/div[2]/div[1]/'
                               'div[2]/div/div/div/ul/li/a/span'):
        driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div[3]/div/article/div/div[2]/div[1]/'
                                     'div[2]/div/div/div/ul/li/a/span').click()


def make_regalur_image(img, size=(256, 256)):
    # 将图片尺寸强制重置为指定的size大小
    # 然后再将其转换成RGB值
    return img.resize(size).convert('RGB')


def split_image(img, part_size=(8, 8)):
    # 将图片按给定大小切分
    w, h = img.size
    pw, ph = part_size
    assert w % pw == h % ph == 0
    return [img.crop((i, j, i + pw, j + ph)).copy() \
            for i in range(0, w, pw) for j in range(0, h, ph)]


def hist_similar(lh, rh):
    # 统计切分后每部分图片的相似度频率曲线
    assert len(lh) == len(rh)
    return sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) \
               for l, r in zip(lh, rh)) / len(lh)


def calc_similar(li, ri):
    # 计算两张图片的相似度
    return sum(hist_similar(l.histogram(), r.histogram()) \
               for l, r in zip(split_image(li), split_image(ri))) / 1024.0


def calc_similar_by_path(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), \
             make_regalur_image(Image.open(rf))
    return calc_similar(li, ri)


# 判断元素是否可点击
def is_element_can_click(element):
    try:
        element.is_enabled()
        return True
    except:
        return False


def see_results(driver):
    doquery(driver)
    click_query(driver)
    is_element_load(driver, '//div[@class = "list-flex flex"]/span')
    span = driver.find_element_by_xpath('//div[@class = "list-flex flex"]/span')
    querys = span.find_elements_by_tag_name('button')
    print(len(querys))
    for query in querys:
        print(query.text)
        text = query.text
        if text == '清空' or text == '清 空':
            query.click()
            print('点 击 了 清 空')
            break


def doquery(driver):
    click_hide(driver)
    # 填写查询条件
    write_condition(driver)
    click_query(driver)
    sleep(1)


# 填写查询条件
def write_condition(driver):
    input_group1 = driver.find_elements_by_xpath('//div[@class="col-sm-2 form-group"]/input')
    input_group2 = driver.find_elements_by_xpath('//div[@class="form-group col-sm-2"]/input')
    input_group3 = driver.find_elements_by_xpath('//div[@class="col-sm-2"]/input')
    input_group4 = driver.find_elements_by_xpath('//div[@class="col-sm-3"]/input')
    input_group5 = driver.find_elements_by_xpath('//div[@class="form-group form-input-group"]/input')

    for input1 in input_group1:
        input1.send_keys('111')

    for input2 in input_group2:
        input2.send_keys('111')

    for input3 in input_group3:
        input3.send_keys('111')

    for input4 in input_group4:
        input4.send_keys('111')

    for input5 in input_group5:
        input5.send_keys('111')

    # 选择下拉框
    select_group1 = driver.find_elements_by_xpath('//div[@class="col-sm-2 form-group"]')
    select_group2 = driver.find_elements_by_xpath('//div[@class="form-group col-sm-2"]')
    select_group3 = driver.find_elements_by_xpath('//div[@class="col-sm-2"]')
    select_group4 = driver.find_elements_by_xpath('//div[@class="form-group col-sm-3"]')
    select_group5 = driver.find_elements_by_xpath('//div[@class="form-group col-sm-2"]')

    for select1 in select_group1:
        if is_element_exist(select1, 'label'):
            if select1.find_element_by_tag_name('label').text != '组织机构':
                if select1.find_elements_by_tag_name('button'):
                    sleep(1)
                    select1.click()
                    element = './/ul/li'
                    if is_element_exist(select1, element):
                        select1.find_element_by_xpath('.//ul/li[2]').click()

    for select2 in select_group2:
        if is_element_exist(select2, 'label'):
            if select2.find_element_by_tag_name('label').text != '组织机构':
                if select2.find_elements_by_tag_name('button'):
                    sleep(1)
                    select2.click()
                    element = './/ul/li'
                    if is_element_exist(select2, element):
                        select2.find_element_by_xpath('.//ul/li[2]').click()

    for select3 in select_group3:
        if is_element_exist(select3, 'label'):
            if select3.find_element_by_tag_name('label').text != '组织机构':
                if select3.find_elements_by_tag_name('button'):
                    sleep(1)
                    select3.click()
                    element = './/ul/li'
                    if is_element_exist(select3, element):
                        select3.find_element_by_xpath('.//ul/li[2]').click()

    for select4 in select_group4:
        if is_element_exist(select4, 'label'):
            if select4.find_element_by_tag_name('label').text != '组织机构':
                if select4.find_elements_by_tag_name('button'):
                    sleep(1)
                    select4.click()
                    element = './/ul/li'
                    if is_element_exist(select4, element):
                        select4.find_element_by_xpath('.//ul/li[2]').click()

    for select5 in select_group5:
        if is_element_exist(select5, 'label'):
            if select5.find_element_by_tag_name('label').text != '组织机构':
                if select5.find_elements_by_tag_name('button'):
                    sleep(1)
                    select5.click()
                    element = './/ul/li'
                    if is_element_exist(select5, element):
                        select5.find_element_by_xpath('.//ul/li[2]').click()

    # 选择日期
    date_group1 = driver.find_elements_by_xpath('//div[@class="col-sm-2 form-group"]/div[@class = "datepicker"]')
    date_group2 = driver.find_elements_by_xpath('//div[@class="form-group col-sm-2"]/div[@class = "datepicker"]')

    for date1 in date_group1:
        sleep(0.5)
        date1.click()
        sleep(0.5)
        ActionChains(driver).move_to_element_with_offset(date1, 120, 120).click().perform()

    for date2 in date_group2:
        print(' date2已找到 ')
        sleep(0.5)
        date2.click()
        sleep(0.5)
        print('date2已点击')
        ActionChains(driver).move_to_element_with_offset(date2, 120, 120).click().perform()


# 显示等待 对应find_element
def present_wait(driver, fun, path):
    element = WebDriverWait(driver, 5, 0.5).until(EC.visibility_of_element_located((fun, path)))
    return element


# 显示等待 对应find_elements
def present_waits(driver, fun, path):
    element = WebDriverWait(driver, 5, 0.5).until(EC.presence_of_all_elements_located((fun, path)))
    return element


def find_li(driver):
    top_list = []
    button_group = present_waits(driver, By.XPATH, '//ul[@role="tablist"]//button')
    for button in button_group:
        if button.is_displayed():
            top_list.append(button.text)
    return top_list


# 关闭当前页面
def close_current_page(driver):
    print('关闭页面')
    close_page = present_wait(driver, By.XPATH,  '//li[@class="bg-info active"]')
    ActionChains(driver).move_to_element(close_page).perform()
    CloseX = WebDriverWait(driver, 5, 0.5).until(EC.element_to_be_clickable((By.ID,  'vc-tabset-close-vuestrap-0')))
    CloseX.click()


def area_choose(driver):
    sleep(0.5)
    if is_element_load(driver, '//span[text()="选择小区"]'):
        area_group = present_waits(driver, By.XPATH, '//span[text()="选择小区"]')
        for area in area_group:
            if area.is_displayed() and area.is_enabled():
                sleep(0.5)
                area.click()
                sleep(0.5)
                last_choose = present_wait(driver, By.XPATH, '//div[@class="btn-group select_list select '
                                                             'open"]//ul/li[last()]//a[last()]')
                if last_choose.is_displayed() and last_choose.is_enabled():
                    last_choose.click()


# 提示框操作
def tips_ctrl(driver):
    notice = present_wait(driver, By.XPATH,  '//*[@id="app-base"]/div[2]/div/div/div/article')
    print(notice.text)
    submit = present_wait(driver, By.ID,  'vc-messagebox-confirm')
    submit.click()
    print(submit.text)


# 输入框通用操作
def input_border(driver, xpath):
    judge = is_element_load(driver, xpath)
    if judge:
        input_group1 = present_waits(driver, By.XPATH, xpath)
        for input1 in input_group1:
            if input1.is_displayed() and input1.is_enabled():
                input1.send_keys('111')


# 下拉框通用操作
def choose_border(driver, xpath):
    border = is_element_load(driver, xpath)
    if border:
        select_group1 = present_waits(driver, By.XPATH, xpath)
        for select1 in select_group1:
            if select1.is_enabled() and select1.is_displayed():
                select1.click()
                element = './/ul/li'
                if is_element_exist(select1, element):
                    last_one = select1.find_element_by_xpath('.//ul/li[last()]/a')
                    if last_one.is_displayed():
                        last_one.click()
                    else:
                        select1.find_element_by_xpath('.//ul/li[2]/a').click()


# 按按钮名来点击按钮
def button_name_click(driver, name):
    sleep(1)
    button_group = present_waits(driver, By.XPATH, '//button[text()="' + name + '"]')
    for button in button_group:
        if button.is_displayed():
            button.click()
            break


def input_name_sandkey(driver, name, name2):
    present_wait(driver, By.XPATH, './/input[@placeholder="' + name + '"]').clear()
    present_wait(driver, By.XPATH, './/input[@placeholder="' + name + '"]').send_keys(name2)


def input_name_sandkeys(driver, name, name2):
    present_waits(driver, By.XPATH, './/input[@placeholder="' + name + '"]')[1].clear()
    present_waits(driver, By.XPATH, './/input[@placeholder="' + name + '"]')[1].send_keys(name2)


def fillin(driver, name):
    sleep(0.5)
    present_wait(driver, By.XPATH, ".//input[@placeholder='请输入搜索组织']").send_keys(name)
    searchbuttons = present_waits(driver, By.XPATH, ".//div[@class='form-group']//button[text()='查询']")
    for searchbutton in searchbuttons:
        searchbutton.click()
        break
    sleep(1)
    present_wait(driver, By.XPATH, './/a[@id="vc-tree-name-' + name + '"]/span').click()
    confirmbuttons = present_waits(driver, By.XPATH, ".//button[text()='确认']")
    for confirmbutton in confirmbuttons:
        confirmbutton.click()
        break


# 日期框通用操作
def data_border(driver, xpath):
    data = is_element_load(driver, xpath)
    if data:
        date_group1 = present_waits(driver, By.XPATH, xpath)
        for date1 in date_group1:
            if date1.is_displayed() and date1.is_enabled():
                date1.click()
                sleep(0.5)
                today = date1.find_element_by_xpath('.//button[text()="今天"]')
                if today.is_displayed() and today.is_enabled():
                    today.click()
                else:
                    group1 = date1.find_elements_by_xpath('.//span[text()="十月"]')
                    group2 = date1.find_elements_by_xpath('.//span[text()="2022"]')
                    for part in group1:
                        if part.is_displayed() and today.is_enabled():
                            part.click()
                        else:
                            for part2 in group2:
                                if part2.is_displayed() and today.is_enabled():
                                    part2.click()


# 点击查询按钮操作
def search_button_click(driver):
    search_buttons = present_waits(driver, By.XPATH, '//button[contains(text(),"查询")]')
    for search_button in search_buttons:
        if search_button.is_displayed():
            search_button.click()
            break


# 点击左侧id属性按钮
def id_click(driver, name):
    present_wait(driver, By.ID, "vc-tree-name-" + name).click()


# 点击下拉箭头
def bottom_push_click(driver):
    topbuttons = present_waits(driver, By.XPATH, '//div[@class="button_spacing button_shrink_bottom"]')
    for topbutton in topbuttons:
        if topbutton.is_displayed():
            topbutton.click()
            break


def criteria(driver, xpath):
    click_hide(driver)
    judge = is_element_load(driver, xpath)
    if judge:
        input_group1 = present_waits(driver, By.XPATH, xpath)
        for input1 in input_group1:
            if input1.is_displayed() and input1.is_enabled():
                input1.send_keys('没数据就行')
                break
    click_query(driver)


def action_charg(self, driver, imgname):
    sleep(2)
    driver.save_screenshot('./Image/newImage/' + imgname + '.png')
    flag = os.path.exists('./Image/oldImage/' + imgname + '.png')
    if flag:
        percentage = calc_similar_by_path('./Image/newImage/' + imgname + '.png',
                                          './Image/oldImage/' + imgname + '.png') * 100
    else:
        driver.save_screenshot('./Image/oldImage/' + imgname + '.png')
        percentage = calc_similar_by_path('./Image/newImage/' + imgname + '.png',
                                          './Image/oldImage/' + imgname + '.png') * 100

    if percentage > 98:
        print(str(round(percentage, 2)) + '%')
        expcet_price = True
    else:
        print(imgname + '与原页面相似度为：' + str(round(percentage, 2)) + '%')
        expcet_price = False

    self.assertEqual(expcet_price, True)
    if expcet_price:
        print("预期结果与实际结果一致，测试通过")
        driver.save_screenshot('./Image/oldImage/' + imgname + '.png')
    close_current_page(driver)
