"""
快捷操作模块
提供常用的快捷操作方法
"""
from typing import Optional, List, Dict, Any
from playwright.async_api import Page
from loguru import logger


class QuickActions:
    """
    快捷操作类
    提供常用操作的快捷方法
    """
    
    def __init__(self, page: Page):
        self.page = page
    
    # ==================== 导航快捷操作 ====================
    
    async def goto(self, url: str, wait: bool = True) -> None:
        """快速导航"""
        await self.page.goto(url, wait_until="load" if wait else "domcontentloaded")
        logger.info(f"导航: {url}")
    
    async def go_back(self) -> None:
        """快速后退"""
        await self.page.go_back()
        logger.info("后退")
    
    async def go_forward(self) -> None:
        """快速前进"""
        await self.page.go_forward()
        logger.info("前进")
    
    async def refresh(self) -> None:
        """快速刷新"""
        await self.page.reload()
        logger.info("刷新")
    
    # ==================== 点击快捷操作 ====================
    
    async def click(self, selector: str) -> None:
        """快速点击"""
        await self.page.click(selector)
        logger.debug(f"点击: {selector}")
    
    async def click_text(self, text: str) -> None:
        """点击包含文本的元素"""
        await self.page.get_by_text(text).click()
        logger.debug(f"点击文本: {text}")
    
    async def click_button(self, text: str = None) -> None:
        """点击按钮"""
        if text:
            await self.page.get_by_role("button", name=text).click()
        else:
            await self.page.locator("button").first.click()
        logger.debug(f"点击按钮: {text or '第一个'}")
    
    async def click_link(self, text: str = None) -> None:
        """点击链接"""
        if text:
            await self.page.get_by_role("link", name=text).click()
        else:
            await self.page.locator("a").first.click()
        logger.debug(f"点击链接: {text or '第一个'}")
    
    async def double_click(self, selector: str) -> None:
        """双击"""
        await self.page.dblclick(selector)
        logger.debug(f"双击: {selector}")
    
    async def right_click(self, selector: str) -> None:
        """右键点击"""
        await self.page.click(selector, button="right")
        logger.debug(f"右键点击: {selector}")
    
    # ==================== 输入快捷操作 ====================
    
    async def type_text(self, selector: str, text: str, clear: bool = True) -> None:
        """输入文本"""
        if clear:
            await self.page.fill(selector, text)
        else:
            await self.page.type(selector, text)
        logger.debug(f"输入: {selector} = {text[:20]}...")
    
    async def fill_by_label(self, label: str, value: str) -> None:
        """通过标签填充"""
        await self.page.get_by_label(label).fill(value)
        logger.debug(f"填充标签 '{label}': {value}")
    
    async def fill_by_placeholder(self, placeholder: str, value: str) -> None:
        """通过占位符填充"""
        await self.page.get_by_placeholder(placeholder).fill(value)
        logger.debug(f"填充占位符 '{placeholder}': {value}")
    
    async def clear(self, selector: str) -> None:
        """清空输入框"""
        await self.page.fill(selector, "")
        logger.debug(f"清空: {selector}")
    
    # ==================== 选择快捷操作 ====================
    
    async def select(self, selector: str, value: str) -> None:
        """选择下拉选项"""
        await self.page.select_option(selector, value)
        logger.debug(f"选择: {selector} = {value}")
    
    async def select_by_label(self, selector: str, label: str) -> None:
        """通过标签选择"""
        await self.page.select_option(selector, label=label)
        logger.debug(f"选择标签: {selector} = {label}")
    
    async def check(self, selector: str) -> None:
        """勾选复选框"""
        await self.page.check(selector)
        logger.debug(f"勾选: {selector}")
    
    async def uncheck(self, selector: str) -> None:
        """取消勾选"""
        await self.page.uncheck(selector)
        logger.debug(f"取消勾选: {selector}")
    
    # ==================== 获取快捷操作 ====================
    
    async def get_text(self, selector: str) -> str:
        """获取文本"""
        text = await self.page.locator(selector).text_content()
        return text or ""
    
    async def get_value(self, selector: str) -> str:
        """获取输入值"""
        return await self.page.locator(selector).input_value()
    
    async def get_attribute(self, selector: str, attribute: str) -> Optional[str]:
        """获取属性"""
        return await self.page.locator(selector).get_attribute(attribute)
    
    async def get_href(self, selector: str) -> Optional[str]:
        """获取链接地址"""
        return await self.get_attribute(selector, "href")
    
    async def get_src(self, selector: str) -> Optional[str]:
        """获取图片地址"""
        return await self.get_attribute(selector, "src")
    
    # ==================== 等待快捷操作 ====================
    
    async def wait(self, seconds: float) -> None:
        """等待秒数"""
        import asyncio
        await asyncio.sleep(seconds)
        logger.debug(f"等待 {seconds}s")
    
    async def wait_for_selector(self, selector: str, timeout: float = 30) -> None:
        """等待元素出现"""
        await self.page.wait_for_selector(selector, timeout=timeout * 1000)
        logger.debug(f"等待元素: {selector}")
    
    async def wait_for_text(self, text: str, timeout: float = 30) -> None:
        """等待文本出现"""
        await self.page.get_by_text(text).wait_for(timeout=timeout * 1000)
        logger.debug(f"等待文本: {text}")
    
    async def wait_for_url(self, url: str, timeout: float = 30) -> None:
        """等待URL变化"""
        await self.page.wait_for_url(f"**/{url}**", timeout=timeout * 1000)
        logger.debug(f"等待URL: {url}")
    
    # ==================== 滚动快捷操作 ====================
    
    async def scroll_to_bottom(self) -> None:
        """滚动到底部"""
        await self.page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
        logger.debug("滚动到底部")
    
    async def scroll_to_top(self) -> None:
        """滚动到顶部"""
        await self.page.evaluate("window.scrollTo(0, 0)")
        logger.debug("滚动到顶部")
    
    async def scroll_to_element(self, selector: str) -> None:
        """滚动到元素"""
        await self.page.locator(selector).scroll_into_view_if_needed()
        logger.debug(f"滚动到元素: {selector}")
    
    async def scroll_by(self, x: int = 0, y: int = 500) -> None:
        """滚动指定距离"""
        await self.page.mouse.wheel(x, y)
        logger.debug(f"滚动: x={x}, y={y}")
    
    # ==================== 截图快捷操作 ====================
    
    async def screenshot(self, path: str, full_page: bool = False) -> None:
        """截图"""
        await self.page.screenshot(path=path, full_page=full_page)
        logger.info(f"截图: {path}")
    
    async def screenshot_element(self, selector: str, path: str) -> None:
        """元素截图"""
        await self.page.locator(selector).screenshot(path=path)
        logger.info(f"元素截图: {path}")
    
    # ==================== 文件快捷操作 ====================
    
    async def upload_file(self, selector: str, file_path: str) -> None:
        """上传文件"""
        await self.page.set_input_files(selector, file_path)
        logger.info(f"上传文件: {file_path}")
    
    async def upload_files(self, selector: str, file_paths: List[str]) -> None:
        """上传多个文件"""
        await self.page.set_input_files(selector, file_paths)
        logger.info(f"上传 {len(file_paths)} 个文件")
    
    # ==================== 弹窗快捷操作 ====================
    
    async def accept_dialog(self) -> None:
        """接受对话框"""
        self.page.on("dialog", lambda dialog: dialog.accept())
        logger.debug("接受对话框")
    
    async def dismiss_dialog(self) -> None:
        """取消对话框"""
        self.page.on("dialog", lambda dialog: dialog.dismiss())
        logger.debug("取消对话框")
    
    # ==================== 常用组合操作 ====================
    
    async def login(
        self,
        username_selector: str,
        password_selector: str,
        submit_selector: str,
        username: str,
        password: str,
    ) -> None:
        """登录操作"""
        await self.type_text(username_selector, username)
        await self.type_text(password_selector, password)
        await self.click(submit_selector)
        logger.info(f"登录: {username}")
    
    async def search(
        self,
        search_selector: str,
        submit_selector: str,
        query: str,
    ) -> None:
        """搜索操作"""
        await self.type_text(search_selector, query)
        await self.click(submit_selector)
        logger.info(f"搜索: {query}")
    
    async def fill_form(self, data: Dict[str, str]) -> None:
        """填充表单"""
        for selector, value in data.items():
            await self.type_text(selector, value)
        logger.info(f"填充表单: {len(data)} 个字段")


# 全局快捷函数
async def quick_goto(page: Page, url: str) -> None:
    """快速导航"""
    actions = QuickActions(page)
    await actions.goto(url)


async def quick_click(page: Page, selector: str) -> None:
    """快速点击"""
    actions = QuickActions(page)
    await actions.click(selector)


async def quick_type(page: Page, selector: str, text: str) -> None:
    """快速输入"""
    actions = QuickActions(page)
    await actions.type_text(selector, text)


async def quick_screenshot(page: Page, path: str) -> None:
    """快速截图"""
    actions = QuickActions(page)
    await actions.screenshot(path)
