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

from playwright.sync_api import Page, Locator
from typing import Optional
from datetime import datetime, timedelta

from ..base_keyword import BaseKeyword
from ...reference import INFO


class ElDatePickerKeyword(BaseKeyword):
    """Element Plus DatePicker 组件关键字

    处理日期选择器、日期时间选择器、日期范围选择器。
    """

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

    def el_datepicker(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """日期选择（直接输入）

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
            content: 日期 (格式: YYYY-MM-DD)
        """
        INFO(f"选择日期: {content}")

        picker = self.locator(targeting, element, index)
        input_el = picker.locator('.el-input__inner')

        # 清除并输入日期
        input_el.click()
        input_el.fill(str(content))
        input_el.press('Enter')

        # 等待面板关闭
        self.page.wait_for_timeout(200)

    def el_datepicker_panel(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """通过面板选择日期

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
            content: 日期 (格式: YYYY-MM-DD 或 YYYY/MM/DD)
        """
        INFO(f"面板选择日期: {content}")

        # 解析日期
        date_str = str(content).replace('/', '-')
        parts = date_str.split('-')
        year = int(parts[0])
        month = int(parts[1])
        day = int(parts[2])

        picker = self.locator(targeting, element, index)
        picker.click()

        # 等待面板出现
        panel = self.page.locator('.el-date-picker:visible, .el-picker-panel:visible')
        panel.wait_for(state='visible', timeout=5000)

        # 导航到目标年月
        self._navigate_to_month(panel, year, month)

        # 点击日期
        day_cells = panel.locator(f'.el-date-table td.available')
        for i in range(day_cells.count()):
            cell = day_cells.nth(i)
            cell_text = cell.locator('span').text_content()
            if cell_text and cell_text.strip() == str(day):
                cell.click()
                break

    def el_datepicker_today(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None
    ) -> None:
        """选择今天

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
        """
        INFO("选择今天")

        picker = self.locator(targeting, element, index)
        picker.click()

        panel = self.page.locator('.el-date-picker:visible, .el-picker-panel:visible')
        panel.wait_for(state='visible', timeout=5000)

        # 点击今天按钮
        today_btn = panel.locator('.el-picker-panel__footer').get_by_text('今天')
        if today_btn.is_visible():
            today_btn.click()
        else:
            # 点击当前日期单元格
            panel.locator('.el-date-table td.today').click()

    def el_datetimepicker(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """日期时间选择

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
            content: 日期时间 (格式: YYYY-MM-DD HH:mm:ss)
        """
        INFO(f"选择日期时间: {content}")

        picker = self.locator(targeting, element, index)
        input_el = picker.locator('.el-input__inner')

        input_el.click()
        input_el.fill(str(content))
        input_el.press('Enter')

        self.page.wait_for_timeout(200)

    def el_daterange(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """日期范围选择

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
            content: 日期范围 (格式: "YYYY-MM-DD,YYYY-MM-DD" 或 "YYYY-MM-DD ~ YYYY-MM-DD")
        """
        # 解析日期范围
        if '~' in str(content):
            dates = str(content).split('~')
        elif ',' in str(content):
            dates = str(content).split(',')
        else:
            dates = [content, content]

        start_date = dates[0].strip()
        end_date = dates[1].strip() if len(dates) > 1 else start_date

        INFO(f"选择日期范围: {start_date} ~ {end_date}")

        picker = self.locator(targeting, element, index)
        picker.click()

        panel = self.page.locator('.el-date-range-picker:visible, .el-picker-panel:visible')
        panel.wait_for(state='visible', timeout=5000)

        # 输入开始和结束日期
        inputs = panel.locator('.el-date-range-picker__editors input, .el-range-input')
        if inputs.count() >= 2:
            inputs.nth(0).fill(start_date)
            inputs.nth(1).fill(end_date)

            # 点击确认
            confirm_btn = panel.locator('.el-picker-panel__footer .el-button--primary, .el-button:has-text("确定")')
            if confirm_btn.is_visible():
                confirm_btn.click()
            else:
                self.page.keyboard.press('Enter')
        else:
            # 直接输入到 range-input
            range_inputs = picker.locator('.el-range-input')
            if range_inputs.count() >= 2:
                range_inputs.nth(0).fill(start_date)
                range_inputs.nth(1).fill(end_date)
                self.page.keyboard.press('Enter')

    def el_datepicker_clear(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None
    ) -> None:
        """清除日期

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
        """
        INFO("清除日期")

        picker = self.locator(targeting, element, index)
        picker.hover()
        self.page.wait_for_timeout(200)

        clear_btn = picker.locator('.el-input__clear, .el-icon-circle-close')
        if clear_btn.is_visible():
            clear_btn.click()

    def el_datepicker_get_value(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None
    ) -> str:
        """获取日期值

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引

        Returns:
            str: 日期值
        """
        picker = self.locator(targeting, element, index)
        input_el = picker.locator('.el-input__inner, .el-range-input')

        if input_el.count() > 1:
            # 范围选择器
            start = input_el.nth(0).input_value() or ''
            end = input_el.nth(1).input_value() or ''
            return f"{start} ~ {end}"
        elif input_el.count() == 1:
            return input_el.first.input_value() or ''

        return ''

    def el_datepicker_shortcut(
        self,
        targeting: str,
        element: str,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """点击快捷选项

        Args:
            targeting: 定位类型
            element: 定位表达式
            index: 索引
            content: 快捷选项文本（如"最近一周"、"最近一个月"）
        """
        INFO(f"点击快捷选项: {content}")

        picker = self.locator(targeting, element, index)
        picker.click()

        panel = self.page.locator('.el-picker-panel:visible')
        panel.wait_for(state='visible', timeout=5000)

        # 点击快捷选项
        shortcut = panel.locator(f'.el-picker-panel__sidebar button:has-text("{content}"), .el-picker-panel__shortcut:has-text("{content}")')
        if shortcut.is_visible():
            shortcut.click()

    def _navigate_to_month(self, panel: Locator, year: int, month: int) -> None:
        """导航到指定年月

        Args:
            panel: 面板 Locator
            year: 年
            month: 月
        """
        # 获取当前显示的年月
        header = panel.locator('.el-date-picker__header')

        # 最多尝试 120 次（10年）
        for _ in range(120):
            # 获取当前年月
            year_label = header.locator('.el-date-picker__header-label').first
            month_label = header.locator('.el-date-picker__header-label').last

            current_year_text = year_label.text_content() or ''
            current_month_text = month_label.text_content() or ''

            # 提取数字
            current_year = int(''.join(filter(str.isdigit, current_year_text)) or '0')
            current_month = int(''.join(filter(str.isdigit, current_month_text)) or '0')

            if current_year == year and current_month == month:
                break

            # 计算差值
            diff = (year - current_year) * 12 + (month - current_month)

            if diff > 0:
                # 往后
                next_btn = header.locator('.el-icon-arrow-right, [class*="arrow-right"]').last
                next_btn.click()
            else:
                # 往前
                prev_btn = header.locator('.el-icon-arrow-left, [class*="arrow-left"]').first
                prev_btn.click()

            self.page.wait_for_timeout(100)
