"""Element Plus 内置插件"""

from pathlib import Path
from playwright.sync_api import Page

from ..plugin_base import PluginBase
from ...action.element_plus import (
    ElSelectKeyword,
    ElDatePickerKeyword,
    ElDialogKeyword,
    ElTableKeyword,
    ElCascaderKeyword,
    ElTreeKeyword,
    ElUploadKeyword,
    ElFormKeyword,
    ElMenuKeyword,
)


class ElementPlusPlugin(PluginBase):
    """Element Plus 组件关键字插件

    提供 Element Plus UI 组件的操作关键字。
    """

    name = "element_plus"
    version = "2.0.0"
    description = "Element Plus UI 组件关键字"
    author = "KDTest Team"

    def __init__(self, page: Page = None):
        super().__init__(page)
        self._el_select: ElSelectKeyword = None
        self._el_datepicker: ElDatePickerKeyword = None
        self._el_dialog: ElDialogKeyword = None
        self._el_table: ElTableKeyword = None
        self._el_cascader: ElCascaderKeyword = None
        self._el_tree: ElTreeKeyword = None
        self._el_upload: ElUploadKeyword = None
        self._el_form: ElFormKeyword = None
        self._el_menu: ElMenuKeyword = None

    def setup(self) -> None:
        """初始化插件"""
        # 加载配置
        config_path = Path(__file__).parent / "my.ini"
        if config_path.exists():
            self.load_config_from_file(str(config_path))

        # 加载元素数据
        element_data_path = Path(__file__).parent / "elementData" / "elementData.yaml"
        if element_data_path.exists():
            self.load_element_data_from_file(str(element_data_path))

        # 初始化关键字类
        if self._page:
            self._init_keyword_classes()

        # 注册关键字
        self._register_keywords()

    def _init_keyword_classes(self) -> None:
        """初始化关键字类实例"""
        self._el_select = ElSelectKeyword(self._page)
        self._el_datepicker = ElDatePickerKeyword(self._page)
        self._el_dialog = ElDialogKeyword(self._page)
        self._el_table = ElTableKeyword(self._page)
        self._el_cascader = ElCascaderKeyword(self._page)
        self._el_tree = ElTreeKeyword(self._page)
        self._el_upload = ElUploadKeyword(self._page)
        self._el_form = ElFormKeyword(self._page)
        self._el_menu = ElMenuKeyword(self._page)

    def _register_keywords(self) -> None:
        """注册所有关键字"""
        # Select 关键字
        self.register_keywords({
            'el_select': self._wrap('_el_select', 'el_select'),
            'el_select_multiple': self._wrap('_el_select', 'el_select_multiple'),
            'el_select_clear': self._wrap('_el_select', 'el_select_clear'),
            'el_select_search': self._wrap('_el_select', 'el_select_search'),
            'el_select_get_value': self._wrap('_el_select', 'el_select_get_value'),
            'el_select_assert': self._wrap('_el_select', 'el_select_assert'),
        })

        # DatePicker 关键字
        self.register_keywords({
            'el_datepicker': self._wrap('_el_datepicker', 'el_datepicker'),
            'el_datepicker_panel': self._wrap('_el_datepicker', 'el_datepicker_panel'),
            'el_datepicker_today': self._wrap('_el_datepicker', 'el_datepicker_today'),
            'el_datetimepicker': self._wrap('_el_datepicker', 'el_datetimepicker'),
            'el_daterange': self._wrap('_el_datepicker', 'el_daterange'),
            'el_datepicker_clear': self._wrap('_el_datepicker', 'el_datepicker_clear'),
            'el_datepicker_get_value': self._wrap('_el_datepicker', 'el_datepicker_get_value'),
        })

        # Dialog 关键字
        self.register_keywords({
            'el_dialog_wait': self._wrap('_el_dialog', 'el_dialog_wait'),
            'el_dialog_close': self._wrap('_el_dialog', 'el_dialog_close'),
            'el_dialog_confirm': self._wrap('_el_dialog', 'el_dialog_confirm'),
            'el_dialog_cancel': self._wrap('_el_dialog', 'el_dialog_cancel'),
            'el_dialog_input': self._wrap('_el_dialog', 'el_dialog_input'),
            'el_message_box_wait': self._wrap('_el_dialog', 'el_message_box_wait'),
            'el_message_box_confirm': self._wrap('_el_dialog', 'el_message_box_confirm'),
            'el_message_box_input': self._wrap('_el_dialog', 'el_message_box_input'),
            'el_message_wait': self._wrap('_el_dialog', 'el_message_wait'),
            'el_message_get_text': self._wrap('_el_dialog', 'el_message_get_text'),
            'el_message_assert': self._wrap('_el_dialog', 'el_message_assert'),
            'el_notification_wait': self._wrap('_el_dialog', 'el_notification_wait'),
            'el_notification_close': self._wrap('_el_dialog', 'el_notification_close'),
            'el_drawer_wait': self._wrap('_el_dialog', 'el_drawer_wait'),
            'el_drawer_close': self._wrap('_el_dialog', 'el_drawer_close'),
        })

        # Table 关键字
        self.register_keywords({
            'el_table_click_row': self._wrap('_el_table', 'el_table_click_row'),
            'el_table_click_cell': self._wrap('_el_table', 'el_table_click_cell'),
            'el_table_get_cell_text': self._wrap('_el_table', 'el_table_get_cell_text'),
            'el_table_get_row_count': self._wrap('_el_table', 'el_table_get_row_count'),
            'el_table_select_row': self._wrap('_el_table', 'el_table_select_row'),
            'el_table_select_rows': self._wrap('_el_table', 'el_table_select_rows'),
            'el_table_sort': self._wrap('_el_table', 'el_table_sort'),
            'el_table_expand_row': self._wrap('_el_table', 'el_table_expand_row'),
            'el_table_click_button': self._wrap('_el_table', 'el_table_click_button'),
            'el_table_search_row': self._wrap('_el_table', 'el_table_search_row'),
            'el_table_assert_cell': self._wrap('_el_table', 'el_table_assert_cell'),
        })

        # Cascader 关键字
        self.register_keywords({
            'el_cascader': self._wrap('_el_cascader', 'el_cascader'),
            'el_cascader_search': self._wrap('_el_cascader', 'el_cascader_search'),
            'el_cascader_clear': self._wrap('_el_cascader', 'el_cascader_clear'),
            'el_cascader_get_value': self._wrap('_el_cascader', 'el_cascader_get_value'),
            'el_cascader_assert': self._wrap('_el_cascader', 'el_cascader_assert'),
        })

        # Tree 关键字
        self.register_keywords({
            'el_tree_click_node': self._wrap('_el_tree', 'el_tree_click_node'),
            'el_tree_expand_node': self._wrap('_el_tree', 'el_tree_expand_node'),
            'el_tree_collapse_node': self._wrap('_el_tree', 'el_tree_collapse_node'),
            'el_tree_check_node': self._wrap('_el_tree', 'el_tree_check_node'),
            'el_tree_check_nodes': self._wrap('_el_tree', 'el_tree_check_nodes'),
            'el_tree_expand_all': self._wrap('_el_tree', 'el_tree_expand_all'),
            'el_tree_collapse_all': self._wrap('_el_tree', 'el_tree_collapse_all'),
            'el_tree_search': self._wrap('_el_tree', 'el_tree_search'),
            'el_tree_assert_node_exists': self._wrap('_el_tree', 'el_tree_assert_node_exists'),
        })

        # Upload 关键字
        self.register_keywords({
            'el_upload': self._wrap('_el_upload', 'el_upload'),
            'el_upload_drag': self._wrap('_el_upload', 'el_upload_drag'),
            'el_upload_remove': self._wrap('_el_upload', 'el_upload_remove'),
            'el_upload_clear': self._wrap('_el_upload', 'el_upload_clear'),
            'el_upload_preview': self._wrap('_el_upload', 'el_upload_preview'),
            'el_upload_get_file_count': self._wrap('_el_upload', 'el_upload_get_file_count'),
            'el_upload_assert_count': self._wrap('_el_upload', 'el_upload_assert_count'),
            'el_upload_wait_success': self._wrap('_el_upload', 'el_upload_wait_success'),
        })

        # Form 关键字
        self.register_keywords({
            'el_form_input': self._wrap('_el_form', 'el_form_input'),
            'el_form_select': self._wrap('_el_form', 'el_form_select'),
            'el_form_date': self._wrap('_el_form', 'el_form_date'),
            'el_form_checkbox': self._wrap('_el_form', 'el_form_checkbox'),
            'el_form_radio': self._wrap('_el_form', 'el_form_radio'),
            'el_form_switch': self._wrap('_el_form', 'el_form_switch'),
            'el_form_submit': self._wrap('_el_form', 'el_form_submit'),
            'el_form_reset': self._wrap('_el_form', 'el_form_reset'),
            'el_form_get_error': self._wrap('_el_form', 'el_form_get_error'),
            'el_form_assert_error': self._wrap('_el_form', 'el_form_assert_error'),
            'el_form_fill': self._wrap('_el_form', 'el_form_fill'),
        })

        # Menu 菜单导航关键字
        self.register_keywords({
            'menu_load_data': self._wrap('_el_menu', 'load_menu_data'),
            'menu_navigate': self._wrap('_el_menu', 'menu_navigate'),
            'menu_click_first': self._wrap('_el_menu', 'menu_click_first'),
            'menu_click_second': self._wrap('_el_menu', 'menu_click_second'),
            'menu_click_third': self._wrap('_el_menu', 'menu_click_third'),
            'menu_click_tag': self._wrap('_el_menu', 'menu_click_tag'),
            'menu_switch_iframe': self._wrap('_el_menu', 'menu_switch_iframe'),
            'menu_exit_iframe': self._wrap('_el_menu', 'menu_exit_iframe'),
            'menu_get_first_menus': self._wrap('_el_menu', 'menu_get_first_menus'),
            'menu_get_second_menus': self._wrap('_el_menu', 'menu_get_second_menus'),
            'menu_get_tag_count': self._wrap('_el_menu', 'menu_get_tag_count'),
            'menu_has_iframe': self._wrap('_el_menu', 'menu_has_iframe'),
            'menu_get_iframe_name': self._wrap('_el_menu', 'menu_get_iframe_name'),
        })

    def _wrap(self, instance_name: str, method_name: str):
        """包装方法调用

        Args:
            instance_name: 实例属性名
            method_name: 方法名

        Returns:
            包装后的函数
        """
        def wrapper(*args, **kwargs):
            instance = getattr(self, instance_name)
            if instance is None:
                if self._page:
                    self._init_keyword_classes()
                    instance = getattr(self, instance_name)
                else:
                    raise RuntimeError("Page 实例未设置")

            method = getattr(instance, method_name)
            return method(*args, **kwargs)

        return wrapper

    def set_page(self, page: Page) -> None:
        """设置 Page 实例"""
        super().set_page(page)
        if page:
            self._init_keyword_classes()

    def load_menu_data(self, file_path: str) -> None:
        """加载菜单配置文件

        Args:
            file_path: modularInformation.json 文件路径
        """
        if self._el_menu:
            self._el_menu.load_menu_data(file_path)
        elif self._page:
            self._init_keyword_classes()
            self._el_menu.load_menu_data(file_path)
