# -*- coding:utf-8 -*-
# 作者：齐振鋆
# 日期：2022/9/23
import logging
import re

import allure
import os
import time
import pytesseract

from PIL import Image
from selenium.common.exceptions import TimeoutException, InvalidArgumentException

from unit.public.UI.BasePage import BasePage
from unit.public.DataDic import DataDic
from page.GuKeYiTiHua.Public.menu import MenuElement

log = logging.getLogger(__name__)


class LoginPage(BasePage):
    mo = MenuElement()

    @allure.step('登录')
    def login(self):
        log.info('登录')
        project_conf = self.dd.get_value('project_conf')
        user_info = project_conf['userinfo']
        username_input = ('id', 'input1')
        password_input = ('id', 'input2')
        self.type(username_input, user_info['username'])
        self.type(password_input, user_info['password'])
        verificationCode = project_conf['verificationCode']
        while verificationCode == 1:
            log.info('输入验证码...')
            self.input_vCode()
            login_button = ('id', 'loginBtn')
            self.click(login_button)
            # time.sleep(1)
            if self.login_check() is True:
                break
        self.enter(password_input) if verificationCode != 1 else 0

    def input_vCode(self, vcode_xpath='//canvas'):
        rate = self.dd.get_value('rate')
        self.screenshot('vcode.png')
        # 定位到图片元素
        captcha_elm = self.get_element(vcode_xpath)

        # 3、取验证码的矩形区域
        point = captcha_elm.location  # 字典形式 水平位置和垂直位置，x和y值
        size = captcha_elm.size  # 字典形式，宽和高
        x = int(point['x'])
        y = int(point['y'])
        width = int(x + size['width'])
        height = int(y + size['height'])

        screen_path = DataDic().get_value('screenshot_path')
        filepath = os.path.join(screen_path, 'vcode.png')
        image_code = Image.open(filepath)

        little_img = image_code.crop((int(x * rate), int(y * rate), int(width * rate), int(height * rate)))  # 截图
        little_file_name = 'vcode{}.png'.format(int(time.time() * 1000))
        little_path = os.path.join(screen_path, little_file_name)
        little_img.save(little_path)  # 截图名字

        result = '8888'
        vCode = '//canvas'
        try:
            result = re.match(r'[\da-zA-Z]{4}', pytesseract.image_to_string(little_path).replace(' ', '')).group()
        except AttributeError:
            self.click(vCode)
            time.sleep(1)
            self.input_vCode()
        log.info('验证码：{}'.format(result))
        os.remove(little_path)
        fil = ['0', '1', 'o', 'i', 'O', 'I']
        fil_res = any(word if word in result else False for word in fil)
        if fil_res is True or len(result) > 4:
            self.click(vCode)
            time.sleep(1)
            self.input_vCode()
        else:
            vCode_input = ('id', 'photoCode')
            self.type(vCode_input, result)

    def login_check(self):
        try:
            self.get_element("//span[text()='退出']", retry=False)
            return True
        except InvalidArgumentException:
            return False
        except TimeoutException:
            return False
