# -*- coding:utf-8 -*-
# 作者：齐振鋆
# 日期：2022/9/27
import logging
import os
import shutil
import pytest

from typing import Dict, Tuple
# from unit.public.WindowsUnit import WindowsCommon
from unit.public.DataDic import DataDic
from unit.public.TimeUnit import TimeUnit
from unit.public.YamlUtil import UtilYaml

_test_failed_incremental: Dict[str, Dict[Tuple[int, ...], str]] = {}
root_path = os.getcwd()
dd = DataDic()
tu = TimeUnit()
log = logging.getLogger(__name__)


def pytest_runtest_makereport(item, call):
    # 判断用例执行失败后是否需要跳过
    if "incremental" in item.keywords:
        # 如果用例失败，添加到全局变量中
        if call.excinfo is not None:
            cls_name = str(item.cls)
            parametrize_index = (
                tuple(item.callspec.indices.values())
                if hasattr(item, "callspec")
                else ()
            )
            test_name = item.originalname or item.name
            _test_failed_incremental.setdefault(cls_name, {}).setdefault(
                parametrize_index, test_name
            )


def pytest_runtest_setup(item):
    # 判断用例执行失败后是否需要跳过
    if "incremental" in item.keywords:
        cls_name = str(item.cls)
        # 判断当前用例的类是否在全局变量中
        if cls_name in _test_failed_incremental:
            parametrize_index = (
                tuple(item.callspec.indices.values())
                if hasattr(item, "callspec")
                else ()
            )
            test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
            # 如果当前类中的用例存在失败用例，就跳过
            if test_name is not None:
                pytest.xfail("前置用例失败 ({})".format(test_name))


@pytest.fixture(scope="session", autouse=True)
def init_test():
    """初始化测试"""
    log.info('清空校验文件......')
    UtilYaml('data/extract.yaml').clean_yaml()
    log.info('清空旧截图......')
    for item in os.listdir(os.path.join(root_path, 'file', 'screenshot')):
        obj = os.path.join(root_path, 'file', 'screenshot', item)
        if os.path.isdir(obj) is True and tu.get_date_str() != item:
            shutil.rmtree(obj)


@pytest.fixture(scope="session", autouse=True)
def init_params(pytestconfig):
    log.info('初始化参数......')
    dd.set_value('root_path', root_path)
    dd.set_value('screenshot_path', os.path.join(root_path, 'file', 'screenshot', tu.get_date_str()))
    dd.set_value('extract_path', os.path.join(root_path, 'data', 'extract.yaml'))
    dd.set_value('element_wait_time', UtilYaml('conf.yaml').load_yaml()['element_wait_time'])
    # 桌面缩放比例
    # rate = WindowsCommon().get_screen_scale_rate()
    dd.set_value('rate', UtilYaml('conf.yaml').load_yaml()['rate'])
