"""
联系表单测试模块
测试联系表单的各项功能和验证
"""

import pytest
from typing import Dict, Any

from pages.contact_page import ContactPage


class TestContactForm:
    """联系表单测试类"""
    
    @pytest.mark.smoke
    @pytest.mark.form
    def test_contact_page_loads(self, contact_page: ContactPage):
        """测试联系页面加载"""
        contact_page.navigate()
        contact_page.verify_page_loaded()
    
    @pytest.mark.smoke
    def test_contact_page_title(self, contact_page: ContactPage):
        """测试联系页面标题"""
        contact_page.navigate()
        contact_page.assert_title_contains("四川睿新致远")
    
    @pytest.mark.regression
    @pytest.mark.form
    def test_contact_page_structure(self, contact_page: ContactPage):
        """测试联系页面结构"""
        contact_page.navigate()
        contact_page.verify_page_structure()
    
    @pytest.mark.regression
    def test_contact_page_company_info(self, contact_page: ContactPage):
        """测试公司信息显示"""
        contact_page.navigate()
        contact_page.verify_company_info()
    
    @pytest.mark.regression
    def test_contact_page_form_fields(self, contact_page: ContactPage):
        """测试表单字段"""
        contact_page.navigate()
        contact_page.verify_form_fields()
    
    @pytest.mark.form
    def test_form_validation_required_fields(self, contact_page: ContactPage):
        """测试必填字段验证"""
        contact_page.navigate()
        contact_page.verify_form_validation()
    
    @pytest.mark.form
    def test_form_submission_success(self, contact_page: ContactPage, test_data_generator):
        """测试表单提交成功"""
        contact_page.navigate()
        
        # 生成测试数据
        data = test_data_generator.generate_contact_form_data(use_valid=True)
        
        # 填写并提交表单
        contact_page.fill_contact_form(data)
        contact_page.submit_form()
        
        # 验证成功
        contact_page.verify_form_submission_success()
    
    @pytest.mark.form
    def test_form_submission_with_minimal_data(self, contact_page: ContactPage):
        """测试表单提交（最小数据）"""
        contact_page.navigate()
        
        # 最小数据
        data = {
            "name": "测试用户",
            "email": "test@example.com",
            "subject": "测试主题",
            "message": "这是一条测试消息。"
        }
        
        # 填写并提交表单
        contact_page.fill_contact_form(data)
        contact_page.submit_form()
        
        # 验证成功
        contact_page.verify_form_submission_success()
    
    @pytest.mark.form
    def test_form_with_empty_name(self, contact_page: ContactPage):
        """测试姓名为空的表单验证"""
        contact_page.navigate()
        
        data = {
            "name": "",
            "email": "test@example.com",
            "subject": "测试主题",
            "message": "这是一条测试消息。"
        }
        
        contact_page.fill_contact_form(data)
        
        # 点击提交按钮
        contact_page._click("form_submit_button")
        
        # 应该显示验证错误
        try:
            contact_page.assert_element_visible("form_name_input:invalid", timeout=2000)
        except Exception:
            # 可能通过后端验证
            pass
    
    @pytest.mark.form
    def test_form_with_invalid_email(self, contact_page: ContactPage):
        """测试无效邮箱验证"""
        contact_page.navigate()
        
        data = {
            "name": "测试用户",
            "email": "invalid-email",
            "subject": "测试主题",
            "message": "这是一条测试消息。"
        }
        
        contact_page.fill_contact_form(data)
        
        # 检查邮箱字段
        email_input = contact_page._find("form_email_input")
        validity = email_input.evaluate("""
            el => ({
                valid: el.validity.valid,
                typeMismatch: el.validity.typeMismatch
            })
        """)
        
        # 验证邮箱格式
        assert not validity["valid"] or validity["typeMismatch"], \
            "无效邮箱应该被标记为无效"
    
    @pytest.mark.form
    def test_form_submission_performance(self, contact_page: ContactPage, test_data_generator):
        """测试表单提交性能"""
        contact_page.navigate()
        
        data = test_data_generator.generate_contact_form_data(use_valid=True)
        
        result = contact_page.test_form_submission_performance(data, max_duration=5.0)
        
        assert result["passed"], f"表单提交耗时 {result['duration']:.2f}s 超过5秒阈值"
    
    @pytest.mark.responsive
    def test_contact_page_mobile_layout(self, contact_page: ContactPage):
        """测试联系页面移动端布局"""
        contact_page.verify_responsive_layout(375)
    
    @pytest.mark.responsive
    def test_contact_page_tablet_layout(self, contact_page: ContactPage):
        """测试联系页面平板端布局"""
        contact_page.verify_responsive_layout(768)
    
    @pytest.mark.responsive
    def test_contact_page_desktop_layout(self, contact_page: ContactPage):
        """测试联系页面桌面端布局"""
        contact_page.verify_responsive_layout(1920)
    
    @pytest.mark.interactive
    def test_extract_contact_details(self, contact_page: ContactPage):
        """测试提取联系详情"""
        contact_page.navigate()
        details = contact_page.extract_contact_details()
        
        assert "phone" in details or "email" in details or "address" in details
    
    @pytest.mark.interactive
    def test_get_working_hours(self, contact_page: ContactPage):
        """测试获取工作时间"""
        contact_page.navigate()
        hours = contact_page.get_working_hours()
        
        assert isinstance(hours, dict)
    
    @pytest.mark.regression
    def test_form_reset_after_submission(self, contact_page: ContactPage, test_data_generator):
        """测试提交后表单重置"""
        contact_page.navigate()
        
        data = test_data_generator.generate_contact_form_data(use_valid=True)
        
        # 第一次提交
        contact_page.fill_contact_form(data)
        contact_page.submit_form()
        contact_page.verify_form_submission_success()
        
        # 刷新页面后表单应该重置
        contact_page.reload()
        contact_page.assert_element_visible("contact_form", timeout=5000)
    
    @pytest.mark.form
    @pytest.mark.performance
    def test_form_typing_performance(self, contact_page: ContactPage, test_data_generator):
        """测试表单输入性能"""
        import time
        
        contact_page.navigate()
        
        data = test_data_generator.generate_contact_form_data(use_valid=True)
        
        # 测量填充时间
        start_time = time.time()
        
        contact_page.fill_contact_form(data)
        
        end_time = time.time()
        fill_time = (end_time - start_time) * 1000
        
        # 填充时间应该在5秒内
        assert fill_time < 5000, f"表单填充时间 {fill_time:.2f}ms 超过5秒阈值"
    
    @pytest.mark.regression
    def test_form_with_special_characters(self, contact_page: ContactPage):
        """测试包含特殊字符的表单提交"""
        contact_page.navigate()
        
        data = {
            "name": "测试用户-Name",
            "email": "test+special@example.com",
            "subject": "特殊字符测试: @#$%",
            "message": "这是一条包含特殊字符的消息！测试...end"
        }
        
        contact_page.fill_contact_form(data)
        contact_page.submit_form()
        
        # 验证成功
        try:
            contact_page.verify_form_submission_success()
        except Exception:
            # 可能需要等待
            contact_page.page.wait_for_timeout(2000)
    
    @pytest.mark.regression
    def test_form_with_long_content(self, contact_page: ContactPage):
        """测试长内容表单提交"""
        contact_page.navigate()
        
        # 生成长内容
        long_message = "这是一条很长的消息。" * 50
        
        data = {
            "name": "长内容测试用户",
            "email": "longtest@example.com",
            "subject": "长内容测试主题" * 10,
            "message": long_message
        }
        
        contact_page.fill_contact_form(data)
        contact_page.submit_form()
        
        # 验证成功
        try:
            contact_page.verify_form_submission_success()
        except Exception:
            contact_page.page.wait_for_timeout(2000)
