# -*- coding:utf-8 -*-
# 作者：齐振鋆
# 日期：2023/2/14
# 描述:
import logging
import re
import allure
import pytest

from time import sleep
from page.GuKeYiTiHua.Public.errorMsg import ErrorMessage
from page.GuKeYiTiHua.Public.iFrame import IframeElement
from page.GuKeYiTiHua.Public.table import Table
from unit.public.UI.BasePage import BasePage

log = logging.getLogger(__name__)


class OrderList(BasePage):
    em = ErrorMessage()
    iframe = IframeElement()
    table = Table()

    def list_title(self, title):
        self.wait_element("//p[@class='title-class' and text()='{}']".format(title))

    def order_search(self, page_title, tap_name='待办', field_name=None, field_value=None, count=1, max_try=3,
                     count_check=True):
        """
        查找单据
        parameter page_title: 页面名称，一般为三级菜单
        parameter tap_name:
        parameter field_name: 查找字段  [field1, field2, ...]
        parameter field_value: 查找值  [value1, value2, ...]
        parameter count: 查询结果预期数量
        parameter count_check: 是否启用数量验证，默认启用
        """
        log.info('查询：{}-{}'.format(page_title, tap_name))
        if type(field_name) != type(field_value):
            raise Exception('字段名和字段值参数类型不一致')
        self.out_frame()
        self.iframe.to_main_iframe()
        while self.list_title(page_title) is False:
            sleep(1)
        self.change_list_tap(tap_name) if tap_name is not None else 0
        try_count = 0
        fields = {}
        if type(field_name) is not list:
            fields.setdefault(field_name, field_value)
        else:
            for i in range(0, len(fields)):
                fields.setdefault(field_name[i], field_value[i])
        while self.get_results_number() != count and try_count < 5:
            log.info("查找条件：{}".format(fields))
            for index, key in enumerate(fields.keys()):
                field_name, field_value = key, fields[key]
                search_input = "//label[text()='{}']/following-sibling::div//input".format(field_name)
                self.type(search_input, field_value)
                self.enter(search_input) if index == len(fields) - 1 else 0
            sleep(3)
            if count_check is False:
                break
            try_count += 1
        if try_count >= max_try:
            self.screenshot()
            pytest.fail('{}{}列表未查询到{}相关{}单据.'.format(page_title, tap_name, field_value, page_title))

    def get_cell_text(self, field_name, row=1):
        """获取视图单元格内容"""
        log.info('获取第{}行，字段{}的值')
        col_id = self.table.get_col_id(field_name)
        return self.get_ele_text("//td[@colid='{}' and not(contains(@class, 'fixed--hidden'))][{}]".format(col_id, row))

    def open_order(self, column=None, row=1, order_code=None):
        """
        param tag: link列名
        param index: 行
        """
        if order_code is None:
            tag_colid = self.table.get_col_id(column)
            text = self.get_cell_text(column, row)
            log.info("打开单据【{}】".format(text))
            self.click(
                "(//td[@colid='{}' and not(contains(@class, 'fixed--hidden'))])[{}]//span".format(tag_colid, row))
        else:
            log.info("打开单据【{}】".format(order_code))
            self.click("(//td[contains(@class, 'dw-click-cell')]//*[text()='{}'])[{}]".format(order_code, row))
        self.iframe.to_edit_iframe()
        self.em.check_message()

    def checked_order(self, index=1, tag=None):
        """选择单据"""
        if index == 0:
            log.info("全选单据...")
            check_box = "//th[not(contains(@class, 'fixed--hidden'))]//span[@title='全选/取消']"
        else:
            log.info("勾选单据...")
            check_box_colid = self.table.get_col_id(tag)
            check_box = "(//td[@colid='{}' and not(contains(@class, 'fixed--hidden'))])[{}]//span[contains(@class, 'vxe-cell--checkbox')]".format(
                check_box_colid, index)
        self.click(check_box)

    def get_results_number(self):
        """获取视图查询统计数量"""
        total_str = self.get_ele_text("//span[@class='vxe-pager--total']")
        total = int(re.search(r"\d+", total_str).group(0))
        return total

    def change_list_tap(self, tap_name):
        """切换列表tap"""
        log.info('切换到：【{}】tap页'.format(tap_name))
        self.click("//li[@role='menuitem' and text()='{}']".format(tap_name))

    def edit_iframe_is_show(self):
        """等待编辑窗口关闭"""
        self.out_frame()
        self.iframe.to_main_iframe()
        count = 0
        while self.wait_element("//div[@class='el-drawer__body']/ancestor::div[@class='el-overlay']",
                                wait_time=3) is True and count < 10:
            sleep(1)
            count += 1

    def get_cell_text(self, field_name, row=1):
        log.info('获取第{}行，字段{}的值')
        col_id = self.table.get_col_id(field_name)
        return self.get_ele_text("//div[@id='dw-grid-div']//tbody//td[@colid='{}'][{}]".format(col_id, row))

    @allure.step('字段校验')
    def field_value_check(self, field_name, expected_value, line=1):
        """视图单元格内容校验"""
        text = self.get_cell_text(field_name, line)
        if text != str(expected_value):
            self.fail_screenshot()
            pytest.fail('{}实际结果：{}，与预期结果{} 不符'.format(field_name, text, expected_value))
