"""Element Plus Table 组件关键字"""

from playwright.sync_api import Page, Locator
from typing import Optional, List, Dict, Any

from ..base_keyword import BaseKeyword
from ...reference import INFO, set_element_value


class ElTableKeyword(BaseKeyword):
    """Element Plus Table 组件关键字

    处理表格的行列操作、数据获取、排序、筛选等。
    """

    def __init__(self, page: Page):
        super().__init__(page)

    def el_table_click_row(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """点击表格行

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行号（从0开始）
        """
        row_index = int(content)
        INFO(f"点击表格第 {row_index} 行")

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')
        rows.nth(row_index).click()

    def el_table_click_cell(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """点击表格单元格

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行列号 (格式: "row,col" 从0开始)
        """
        parts = str(content).split(',')
        row_index = int(parts[0])
        col_index = int(parts[1]) if len(parts) > 1 else 0

        INFO(f"点击表格单元格: ({row_index}, {col_index})")

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')
        cells = rows.nth(row_index).locator('td')
        cells.nth(col_index).click()

    def el_table_get_cell_text(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str,
        key: str = None
    ) -> str:
        """获取单元格文本

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行列号 (格式: "row,col")
            key: 缓存键名

        Returns:
            str: 单元格文本
        """
        parts = str(content).split(',')
        row_index = int(parts[0])
        col_index = int(parts[1]) if len(parts) > 1 else 0

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')
        cells = rows.nth(row_index).locator('td')
        text = cells.nth(col_index).text_content() or ''
        text = text.strip()

        INFO(f"单元格 ({row_index}, {col_index}) 文本: {text}")

        if key:
            set_element_value(key, text)

        return text

    def el_table_get_row_count(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str = None
    ) -> int:
        """获取表格行数

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 缓存键名

        Returns:
            int: 行数
        """
        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')
        count = rows.count()

        INFO(f"表格行数: {count}")

        if content:
            set_element_value(content, count)

        return count

    def el_table_get_column_data(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str,
        key: str = None
    ) -> List[str]:
        """获取某一列的所有数据

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 列号（从0开始）
            key: 缓存键名

        Returns:
            List[str]: 列数据列表
        """
        col_index = int(content)

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')

        data = []
        for i in range(rows.count()):
            cells = rows.nth(i).locator('td')
            if cells.count() > col_index:
                text = cells.nth(col_index).text_content() or ''
                data.append(text.strip())

        INFO(f"列 {col_index} 数据: {data}")

        if key:
            set_element_value(key, data)

        return data

    def el_table_select_row(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """选择表格行（复选框）

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行号或 "all"
        """
        table = self.locator(targeting, element, index)

        if str(content).lower() == 'all':
            # 全选
            INFO("全选表格")
            header_checkbox = table.locator('.el-table__header-wrapper .el-checkbox')
            header_checkbox.click()
        else:
            row_index = int(content)
            INFO(f"选择表格第 {row_index} 行")
            rows = table.locator('.el-table__body-wrapper .el-table__row')
            checkbox = rows.nth(row_index).locator('.el-checkbox')
            checkbox.click()

    def el_table_select_rows(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """选择多行

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行号列表 (格式: "0,1,2" 或 "0-5")
        """
        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')

        # 解析行号
        row_indices = []
        if '-' in str(content):
            parts = str(content).split('-')
            row_indices = list(range(int(parts[0]), int(parts[1]) + 1))
        else:
            row_indices = [int(i.strip()) for i in str(content).split(',')]

        INFO(f"选择表格行: {row_indices}")

        for row_idx in row_indices:
            checkbox = rows.nth(row_idx).locator('.el-checkbox')
            checkbox.click()

    def el_table_sort(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """点击列头排序

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 列号或列名
        """
        INFO(f"表格排序: {content}")

        table = self.locator(targeting, element, index)
        header_cells = table.locator('.el-table__header-wrapper th')

        if content.isdigit():
            # 列号
            col_index = int(content)
            header_cells.nth(col_index).click()
        else:
            # 列名
            header_cell = table.locator(f'.el-table__header-wrapper th:has-text("{content}")')
            header_cell.click()

    def el_table_filter(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str,
        column: str
    ) -> None:
        """表格筛选

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 筛选值
            column: 列号或列名
        """
        INFO(f"表格筛选列 {column}: {content}")

        table = self.locator(targeting, element, index)

        # 找到筛选按钮
        if column.isdigit():
            header_cell = table.locator('.el-table__header-wrapper th').nth(int(column))
        else:
            header_cell = table.locator(f'.el-table__header-wrapper th:has-text("{column}")')

        filter_btn = header_cell.locator('.el-table__column-filter-trigger')
        filter_btn.click()

        # 等待筛选面板
        self.page.wait_for_timeout(200)

        # 选择筛选值
        filter_panel = self.page.locator('.el-table-filter:visible')
        checkbox = filter_panel.locator(f'.el-checkbox:has-text("{content}")')
        checkbox.click()

        # 确认筛选
        confirm_btn = filter_panel.locator('.el-table-filter__bottom button:has-text("筛选")')
        confirm_btn.click()

    def el_table_expand_row(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """展开表格行

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行号
        """
        row_index = int(content)
        INFO(f"展开表格第 {row_index} 行")

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')
        expand_btn = rows.nth(row_index).locator('.el-table__expand-icon')
        expand_btn.click()

    def el_table_click_button(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str,
        row: str,
        column: str = None
    ) -> None:
        """点击行内按钮

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 按钮文本
            row: 行号
            column: 列号（可选）
        """
        row_index = int(row)
        INFO(f"点击第 {row_index} 行的 '{content}' 按钮")

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')
        row_el = rows.nth(row_index)

        if column:
            cell = row_el.locator('td').nth(int(column))
            btn = cell.locator(f'.el-button:has-text("{content}"), a:has-text("{content}")')
        else:
            btn = row_el.locator(f'.el-button:has-text("{content}"), a:has-text("{content}")')

        btn.first.click()

    def el_table_search_row(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str,
        column: str
    ) -> int:
        """搜索包含指定文本的行

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 搜索文本
            column: 搜索列号

        Returns:
            int: 找到的行号，未找到返回 -1
        """
        col_index = int(column)

        table = self.locator(targeting, element, index)
        rows = table.locator('.el-table__body-wrapper .el-table__row')

        for i in range(rows.count()):
            cells = rows.nth(i).locator('td')
            if cells.count() > col_index:
                text = cells.nth(col_index).text_content() or ''
                if content in text:
                    INFO(f"找到包含 '{content}' 的行: {i}")
                    return i

        INFO(f"未找到包含 '{content}' 的行", "WARNING")
        return -1

    def el_table_assert_cell(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str,
        expected: str,
        mode: str = 'equals'
    ) -> bool:
        """断言单元格内容

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 表格索引
            content: 行列号 (格式: "row,col")
            expected: 期望值
            mode: 断言模式

        Returns:
            bool: 断言结果
        """
        actual = self.el_table_get_cell_text(targeting, element, index, content=content)

        if mode == 'equals':
            result = actual == expected
        elif mode == 'contains':
            result = expected in actual
        else:
            result = actual == expected

        INFO(f"单元格断言: '{actual}' {mode} '{expected}' -> {result}")
        return result
