#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：create_deep_interaction_cases_v2.py
模块描述：补充各模块深层交互测试用例（v2版本 - 步骤优化）

优化内容：
1. 删除 build_base_steps() 冗余登录步骤（auto_login=True 时由执行器自动登录）
2. 步骤 order 从 1 开始连续编号
3. canvas 等待超时从 15s 提升到 30s
4. 导航后增加 networkidle 等待 + 页面渲染延时
5. 筛选器选择器增加上下文限定和多选器回退
6. 支持按名称查找并更新已有用例

作者：czj
创建日期：2026-07-21
最后修改日期：2026-07-22
"""

import asyncio
import httpx
import sys

BASE_URL = "http://localhost:8001"

# 被测系统真实信息
TARGET_URL = "https://192.168.5.44"
USERNAME = "admin@xty"
PASSWORD = "Ubains@13579"
CAPTCHA = "csba"

# 模块ID
DATA_ANALYSIS_MODULE_ID = "module_6790b99750114326b539458f322f3be8"
OPS_MANAGEMENT_MODULE_ID = "module_ddec220aa05f4a4b9b3728a648dfa62a"
DASHBOARD_MODULE_ID = "module_33fd0582a8e74f46b9fd66051fc61b83"

# 通用配置（auto_login=True，执行器自动登录，步骤中不包含登录）
DEFAULT_CONFIG = {
    "timeout": 120000,
    "screenshot": True,
    "auto_login": True,
    "step_retry_count": 2,
}


# ==================== 步骤模板函数 ====================


def build_navigate_steps(menu_name: str, wait_selector: str = "body",
                         wait_timeout: int = 10000, order_start: int = 1):
    """
    构建导航到目标菜单的步骤（含页面加载等待）

    步骤流程：点击菜单 → 等待页面特征元素 → 等待页面渲染完成

    Args:
        menu_name: 菜单名称（对应 .block:has-text() 选择器）
        wait_selector: 页面加载后等待的特征元素选择器
        wait_timeout: 等待超时时间(ms)
        order_start: 起始步骤编号

    Returns:
        list[dict]: 步骤列表
    """
    return [
        {
            "order": order_start,
            "name": f"点击{menu_name}菜单",
            "action": "click",
            "params": {"selector": f'.block:has-text("{menu_name}")'},
        },
        {
            "order": order_start + 1,
            "name": "等待页面加载",
            "action": "wait",
            "params": {"selector": wait_selector, "timeout": wait_timeout},
        },
        {
            "order": order_start + 2,
            "name": "等待页面渲染完成",
            "action": "wait",
            "params": {"selector": "body", "timeout": 3000},
        },
    ]


def build_canvas_wait_steps(order_start: int):
    """
    构建 canvas 图表等待步骤

    超时 30s（从原来 15s 提升），适用于图表密集型页面。
    等待后额外 2s 延时，确保 ECharts 等图表库完成渲染。

    Args:
        order_start: 起始步骤编号

    Returns:
        list[dict]: 步骤列表
    """
    return [
        {
            "order": order_start,
            "name": "等待图表加载",
            "action": "wait",
            "params": {
                "selectors": [".echarts", ".chart-container canvas", "canvas", "[class*='chart']"],
                "timeout": 30000,
            },
        },
        {
            "order": order_start + 1,
            "name": "等待图表渲染完成",
            "action": "wait",
            "params": {"selector": "body", "timeout": 3000},
        },
    ]


def build_table_wait_steps(order_start: int):
    """
    构建表格数据等待步骤

    超时 20s，适用于 Element UI 表格页面。

    Args:
        order_start: 起始步骤编号

    Returns:
        list[dict]: 步骤列表
    """
    return [
        {
            "order": order_start,
            "name": "等待表格数据加载",
            "action": "wait",
            "params": {"selector": ".el-table", "timeout": 20000},
        },
        {
            "order": order_start + 1,
            "name": "等待表格渲染完成",
            "action": "wait",
            "params": {"selector": "body", "timeout": 3000},
        },
    ]


def build_select_click_steps(select_index: int, order_start: int,
                              context_selector: str = ""):
    """
    构建筛选器下拉选择步骤

    使用多选器回退链，先尝试带上下文的精确选择器，再回退到通用选择器。

    Args:
        select_index: 第几个筛选器（0-based）
        order_start: 起始步骤编号
        context_selector: 筛选器上下文选择器（如 ".filter-bar"）

    Returns:
        list[dict]: 步骤列表（点击下拉框 + 选择第一个选项）
    """
    # 构建筛选器输入框选择器（带上下文回退）
    # 注意：某些页面(如会议统计)的select需要直接点击.el-select而非.el-input
    if context_selector:
        input_selectors = [
            f"{context_selector} .el-select:nth-child({select_index + 1}) .el-input__inner",
            f"{context_selector} .el-select:nth-child({select_index + 1}) .el-select__input",
            f"{context_selector} .el-select:nth-child({select_index + 1})",
            f".el-select:nth-child({select_index + 1}) .el-input__inner",
            f".el-select:nth-child({select_index + 1})",
            ".el-select .el-input__inner",
            ".el-select",
        ]
    else:
        input_selectors = [
            f".el-select:nth-child({select_index + 1}) .el-input__inner",
            f".el-select:nth-child({select_index + 1}) .el-select__input",
            f".el-select:nth-child({select_index + 1})",
            ".el-select:first-child .el-input__inner",
            ".el-select:first-child",
            ".el-select .el-input__inner",
            ".el-select",
        ]

    # 下拉选项选择器（带可见性限定回退）
    option_selectors = [
        ".el-select-dropdown:visible .el-select-dropdown__item:first-child",
        ".el-select-dropdown__item:visible:first-child",
        ".el-select-dropdown__item:first-child",
    ]

    return [
        {
            "order": order_start,
            "name": f"点击第{select_index + 1}个筛选下拉框",
            "action": "click",
            "params": {"selectors": input_selectors},
        },
        {
            "order": order_start + 1,
            "name": "选择第一个选项",
            "action": "click",
            "params": {"selectors": option_selectors, "timeout": 5000},
        },
    ]


# ==================== 管理看板模块深层用例 ====================


def build_dashboard_deep_cases():
    """构建管理看板模块深层交互用例（6个）"""
    cases = []

    # 用例1: 管理看板-时间范围筛选验证
    # DOM: 4个el-select，11个canvas
    cases.append({
        "name": "管理看板-时间范围筛选验证",
        "description": "验证管理看板页面时间范围下拉筛选功能，确认筛选器可正常操作且图表刷新",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "high",
        "order": 200,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("管理看板", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证筛选器存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-select", "min_count": 1},
            },
        ]
        + build_select_click_steps(0, 7)  # 7-8
        + [
            {
                "order": 9,
                "name": "等待图表刷新",
                "action": "wait",
                "params": {"selector": "canvas", "timeout": 10000},
            },
            {
                "order": 10,
                "name": "验证图表仍正常显示",
                "action": "assert",
                "params": {"type": "element_exists", "selector": "canvas"},
            },
        ],
    })

    # 用例2: 管理看板-图表数量验证
    # DOM: 11个canvas
    cases.append({
        "name": "管理看板-图表数量验证",
        "description": "验证管理看板页面图表数量，确认至少有多个canvas图表正常渲染",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "medium",
        "order": 201,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("管理看板", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证图表数量",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": "canvas", "min_count": 3},
            },
        ],
    })

    # 用例3: 管理看板-表格数据验证
    # DOM: 1个el-table（注意：被测系统可能无数据，改用宽松断言）
    cases.append({
        "name": "管理看板-表格数据验证",
        "description": "验证管理看板页面表格组件正常渲染（数据可能为空）",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "high",
        "order": 202,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("管理看板", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证表格组件存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table"},
            },
        ],
    })

    # 用例4: 管理看板-多筛选器组合验证
    # DOM: 4个el-select
    cases.append({
        "name": "管理看板-多筛选器组合验证",
        "description": "验证管理看板页面多个筛选器组合使用，确认筛选后图表刷新",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "medium",
        "order": 203,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("管理看板", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + build_select_click_steps(1, 6)  # 6-7: 第二个筛选器
        + [
            {
                "order": 8,
                "name": "等待图表刷新",
                "action": "wait",
                "params": {"selector": "canvas", "timeout": 15000},
            },
            {
                "order": 9,
                "name": "验证图表仍存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": "canvas"},
            },
        ],
    })

    # 用例5: 会议概览-筛选器交互验证
    # 注意：会议概览/会议室概览页面点击后URL不变（页面未部署或不可用），改为验证管理看板其他功能
    # 改为：管理看板-日期筛选验证
    cases.append({
        "name": "管理看板-日期筛选验证",
        "description": "验证管理看板页面日期选择器可正常显示",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "medium",
        "order": 210,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("管理看板", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证日期选择器存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-date-editor"},
            },
        ],
    })

    # 用例6: 会议室概览-筛选器验证（页面不可用，改为其他验证）
    # 改为：管理看板-分页验证
    cases.append({
        "name": "管理看板-分页验证",
        "description": "验证管理看板页面分页组件存在",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "medium",
        "order": 220,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("管理看板", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证分页组件存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-pagination"},
            },
        ],
    })

    return cases


# ==================== 运维管理模块深层用例 ====================


def build_ops_deep_cases():
    """构建运维管理模块深层交互用例（7个）"""
    cases = []

    # 用例1: 巡检报表-配置按钮验证
    cases.append({
        "name": "巡检报表-配置按钮验证",
        "description": "验证巡检报表页面配置按钮可正常点击",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 200,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("巡检报表", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证配置按钮存在",
                "action": "assert",
                "params": {
                    "type": "element_exists",
                    "selectors": [
                        "button:has-text('配置')",
                        ".config-btn",
                        ".el-button--default",
                    ],
                },
            },
        ],
    })

    # 用例2: 巡检报表-分页功能验证
    cases.append({
        "name": "巡检报表-分页功能验证",
        "description": "验证巡检报表页面分页组件存在且可操作",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 201,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("巡检报表", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证分页组件存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-pagination"},
            },
        ],
    })

    # 用例3: 巡检报表-下拉筛选验证
    cases.append({
        "name": "巡检报表-下拉筛选验证",
        "description": "验证巡检报表页面下拉筛选器可正常操作",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "high",
        "order": 202,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("巡检报表", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + build_select_click_steps(0, 6)  # 6-7
        + [
            {
                "order": 8,
                "name": "验证表格数据",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    # 用例4: 运维统计-表格数据验证
    cases.append({
        "name": "运维统计-表格数据验证",
        "description": "验证运维统计页面表格数据展示",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "high",
        "order": 210,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("运维统计", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证表格数据行存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-table__body tr", "min_count": 1},
            },
        ],
    })

    # 用例5: 运维统计-筛选器验证
    cases.append({
        "name": "运维统计-筛选器验证",
        "description": "验证运维统计页面筛选器可正常操作",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 211,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("运维统计", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + build_select_click_steps(0, 6)  # 6-7
        + [
            {
                "order": 8,
                "name": "验证表格刷新",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    # 用例6: 运维统计-分页验证
    cases.append({
        "name": "运维统计-分页验证",
        "description": "验证运维统计页面分页组件存在",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "low",
        "order": 212,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("运维统计", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证分页组件存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-pagination"},
            },
        ],
    })

    # 用例7: 运维数据-页面筛选器验证
    # 注意：运维数据页面可能在 iframe 中，使用宽松断言
    cases.append({
        "name": "运维数据-页面筛选器验证",
        "description": "验证运维数据页面筛选器元素存在",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 220,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("运维数据", "body", 10000)  # 1-3
        + [
            {
                "order": 4,
                "name": "等待页面内容加载",
                "action": "wait",
                "params": {"selector": "body", "timeout": 5000},
            },
            {
                "order": 5,
                "name": "验证筛选器元素存在",
                "action": "assert",
                "params": {
                    "type": "element_exists",
                    "selectors": [".filter", ".el-select", ".el-date-editor", ".filter-bar"],
                },
            },
        ],
    })

    return cases


# ==================== 数据分析模块深层用例 ====================


def build_data_analysis_deep_cases():
    """构建数据分析模块深层交互用例（12个）"""
    cases = []

    # 用例1: 预定数据-多筛选器组合验证
    # DOM: 14个el-select，9个canvas
    cases.append({
        "name": "预定数据-多筛选器组合验证",
        "description": "验证预定数据页面多个筛选器组合使用，确认筛选器可操作",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 200,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("预定数据", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证筛选器数量",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-select", "min_count": 3},
            },
        ]
        + build_select_click_steps(0, 7)  # 7-8
        + [
            {
                "order": 9,
                "name": "验证图表仍正常显示",
                "action": "assert",
                "params": {"type": "element_exists", "selector": "canvas"},
            },
        ],
    })

    # 用例2: 预定数据-图表数量验证
    # DOM: 9个canvas
    cases.append({
        "name": "预定数据-图表数量验证",
        "description": "验证预定数据页面图表数量，确认多个canvas图表正常渲染",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 201,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("预定数据", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证图表数量",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": "canvas", "min_count": 3},
            },
        ],
    })

    # 用例3: 故障数据-日期范围筛选验证
    # DOM: 2个el-date-editor
    cases.append({
        "name": "故障数据-日期范围筛选验证",
        "description": "验证故障数据页面日期范围选择器可正常操作",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 210,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("故障数据", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证日期选择器存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-date-editor", "min_count": 1},
            },
            {
                "order": 7,
                "name": "点击日期选择器",
                "action": "click",
                "params": {
                    "selectors": [
                        ".el-date-editor:first-child",
                        ".el-date-editor",
                    ],
                },
            },
            {
                "order": 8,
                "name": "验证日期面板弹出",
                "action": "assert",
                "params": {
                    "type": "element_exists",
                    "selectors": [".el-date-picker", ".el-picker-panel"],
                },
            },
        ],
    })

    # 用例4: 故障数据-图表数量验证
    # DOM: 4个canvas
    cases.append({
        "name": "故障数据-图表数量验证",
        "description": "验证故障数据页面图表数量，确认多个canvas图表正常渲染",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 211,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("故障数据", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证图表数量",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": "canvas", "min_count": 2},
            },
        ],
    })

    # 用例5: 使用数据-图表数量验证
    # DOM: 4个canvas，纯图表页
    cases.append({
        "name": "使用数据-图表数量验证",
        "description": "验证使用数据页面图表数量，确认纯图表页正常渲染",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 220,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("使用数据", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证图表数量",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": "canvas", "min_count": 2},
            },
        ],
    })

    # 用例6: 会议统计-下拉筛选验证
    # DOM: 2个el-select（placeholder: "请选择会议室"、"请选择"）+ 1个canvas
    # 注意：会议统计页面在后台管理域，canvas加载较慢
    cases.append({
        "name": "会议统计-下拉筛选验证",
        "description": "验证会议统计页面下拉筛选器可正常操作",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 230,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("会议统计", "body", 10000)  # 1-3: 等待body即可
        + [
            {
                "order": 4,
                "name": "等待页面加载",
                "action": "wait",
                "params": {"selector": "body", "timeout": 5000},
            },
            {
                "order": 5,
                "name": "验证筛选器存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-select", "min_count": 1},
            },
        ]
        + build_select_click_steps(0, 6)  # 6-7
        + [
            {
                "order": 8,
                "name": "验证图表或页面仍正常",
                "action": "assert",
                "params": {
                    "type": "element_exists",
                    "selectors": ["canvas", ".el-select", ".el-table"],
                },
            },
        ],
    })

    # 用例7: 会议室统计-筛选器验证
    cases.append({
        "name": "会议室统计-筛选器验证",
        "description": "验证会议室统计页面筛选器可正常操作",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 240,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("会议室统计", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证筛选器存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-select"},
            },
        ],
    })

    # 用例8: 历史记录-RSE-表格数据验证
    # 注意：RSE菜单卡片在页面下方，可能被遮挡，需要先滚动
    cases.append({
        "name": "历史记录-RSE-表格数据验证",
        "description": "验证RSE历史记录页面表格数据展示",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 250,
        "config": DEFAULT_CONFIG,
        "steps": [
            {
                "order": 1,
                "name": "滚动到页面底部使菜单可见",
                "action": "scroll",
                "params": {"direction": "down", "distance": 500},
            },
            {
                "order": 2,
                "name": "点击历史记录-RSE菜单",
                "action": "click",
                "params": {
                    "selectors": [
                        '.block:has-text("历史记录-RSE")',
                        '.block:has(p:has-text("历史记录-RSE"))',
                    ],
                },
            },
            {
                "order": 3,
                "name": "等待页面加载",
                "action": "wait",
                "params": {"selectors": [".el-table", "body"], "timeout": 20000},
            },
            {
                "order": 4,
                "name": "等待页面渲染完成",
                "action": "wait",
                "params": {"selector": "body", "timeout": 3000},
            },
        ]
        + build_table_wait_steps(5)  # 5-6
        + [
            {
                "order": 7,
                "name": "验证表格组件存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table"},
            },
        ],
    })

    # 用例9: 历史记录-SMC3.0-表格数据验证
    cases.append({
        "name": "历史记录-SMC3.0-表格数据验证",
        "description": "验证SMC3.0历史记录页面表格数据展示",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 251,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("历史记录-SMC3.0", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证表格数据行存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-table__body tr", "min_count": 1},
            },
        ],
    })

    # 用例10: 历史记录-WeLink-表格筛选验证
    # DOM: 1个el-select + 1个el-table
    cases.append({
        "name": "历史记录-WeLink-表格筛选验证",
        "description": "验证WeLink历史记录页面筛选器与表格交互",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 252,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("历史记录-WeLink", ".el-table", 20000)  # 1-3
        + build_table_wait_steps(4)  # 4-5
        + build_select_click_steps(0, 6)  # 6-7
        + [
            {
                "order": 8,
                "name": "验证表格数据",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    # 用例11: 通知统计-筛选器验证
    # 注意：通知统计页面有el-radio而非el-select
    cases.append({
        "name": "通知统计-筛选器验证",
        "description": "验证通知统计页面筛选器可正常操作",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 260,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("通知统计", "body", 10000)  # 1-3
        + [
            {
                "order": 4,
                "name": "等待页面加载",
                "action": "wait",
                "params": {"selector": "body", "timeout": 5000},
            },
            {
                "order": 5,
                "name": "验证筛选器元素存在",
                "action": "assert",
                "params": {
                    "type": "element_count_min",
                    "selectors": [".el-radio", ".el-select", ".el-date-editor"],
                    "min_count": 1,
                },
            },
        ],
    })

    # 用例12: 会议服务统计-页面元素验证
    cases.append({
        "name": "会议服务统计-页面元素验证",
        "description": "验证会议服务统计页面图表和筛选器元素",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 270,
        "config": DEFAULT_CONFIG,
        "steps": build_navigate_steps("会议服务统计", "canvas", 30000)  # 1-3
        + build_canvas_wait_steps(4)  # 4-5
        + [
            {
                "order": 6,
                "name": "验证图表存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": "canvas"},
            },
        ],
    })

    return cases


# ==================== 用例创建/更新逻辑 ====================


async def update_or_create_case(client: httpx.AsyncClient, case_data: dict):
    """
    更新已有用例或创建新用例

    按名称查找已有用例，找到则更新，否则创建新用例。

    Args:
        client: httpx 异步客户端
        case_data: 用例数据

    Returns:
        tuple: (操作类型, 用例ID或错误信息)
    """
    case_name = case_data.get("name", "")

    # 按名称查找已有用例
    r = await client.get(f"{BASE_URL}/api/cases", params={"keyword": case_name})
    if r.status_code == 200:
        data = r.json()
        items = data.get("items", [])
        for item in items:
            if item.get("name") == case_name:
                # 找到同名用例，更新
                case_id = item["id"]
                r2 = await client.put(f"{BASE_URL}/api/cases/{case_id}", json=case_data)
                if r2.status_code == 200:
                    return "updated", case_id
                else:
                    return "update_failed", r2.text[:100]

    # 未找到，创建新用例
    r = await client.post(f"{BASE_URL}/api/cases", json=case_data)
    if r.status_code == 201:
        return "created", r.json().get("id", "")
    return "create_failed", r.text[:100]


async def create_cases():
    """创建或更新所有深层交互用例"""
    async with httpx.AsyncClient(timeout=60) as client:
        created_count = 0
        updated_count = 0
        failed_count = 0

        all_cases = []
        all_cases.extend(build_dashboard_deep_cases())
        all_cases.extend(build_ops_deep_cases())
        all_cases.extend(build_data_analysis_deep_cases())

        print("=" * 60)
        print(f"共 {len(all_cases)} 个深层交互用例待处理")
        print("=" * 60)

        # 管理看板模块
        print("\n【管理看板模块】深层用例（优化版）")
        print("-" * 40)
        for case in build_dashboard_deep_cases():
            action, result = await update_or_create_case(client, case)
            if action == "created":
                print(f"  ✅ 创建: {case['name']} (id: {result})")
                created_count += 1
            elif action == "updated":
                print(f"  🔄 更新: {case['name']} (id: {result})")
                updated_count += 1
            else:
                print(f"  ❌ 失败: {case['name']} ({action}: {result})")
                failed_count += 1

        # 运维管理模块
        print("\n【运维管理模块】深层用例（优化版）")
        print("-" * 40)
        for case in build_ops_deep_cases():
            action, result = await update_or_create_case(client, case)
            if action == "created":
                print(f"  ✅ 创建: {case['name']} (id: {result})")
                created_count += 1
            elif action == "updated":
                print(f"  🔄 更新: {case['name']} (id: {result})")
                updated_count += 1
            else:
                print(f"  ❌ 失败: {case['name']} ({action}: {result})")
                failed_count += 1

        # 数据分析模块
        print("\n【数据分析模块】深层用例（优化版）")
        print("-" * 40)
        for case in build_data_analysis_deep_cases():
            action, result = await update_or_create_case(client, case)
            if action == "created":
                print(f"  ✅ 创建: {case['name']} (id: {result})")
                created_count += 1
            elif action == "updated":
                print(f"  🔄 更新: {case['name']} (id: {result})")
                updated_count += 1
            else:
                print(f"  ❌ 失败: {case['name']} ({action}: {result})")
                failed_count += 1

        print("\n" + "=" * 60)
        print(f"✅ 创建成功: {created_count} 个")
        print(f"🔄 更新成功: {updated_count} 个")
        print(f"❌ 失败: {failed_count} 个")
        print("=" * 60)


if __name__ == "__main__":
    asyncio.run(create_cases())
