#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：create_analysis_cases.py
模块描述：补充数据分析、运维管理、管理看板模块可执行测试用例

基于对被测系统的实际探索，补充以下功能点：
1. 数据分析模块：图表筛选、日期切换、数据导出、详情查看
2. 运维管理模块：巡检报表筛选、数据统计查看
3. 管理看板模块：看板数据展示、图表交互

作者：czj
创建日期：2026-07-21
"""

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"

# 通用配置
DEFAULT_CONFIG = {
    "timeout": 120000,
    "screenshot": True,
    "auto_login": True,
    "step_retry_count": 2,
}


def build_base_steps():
    """构建基础步骤：登录 + 访问目标页面"""
    return [
        {
            "order": 1,
            "name": "打开被测系统",
            "action": "navigate",
            "params": {"url": TARGET_URL, "timeout": 30000},
        },
        {
            "order": 2,
            "name": "等待登录表单加载",
            "action": "wait",
            "params": {"selector": 'input[placeholder*="手机号"]', "timeout": 10000},
        },
        {
            "order": 3,
            "name": "输入账号",
            "action": "fill",
            "params": {"selector": 'input[placeholder*="手机号"]', "value": USERNAME},
        },
        {
            "order": 4,
            "name": "输入密码",
            "action": "fill",
            "params": {"selector": 'input[placeholder*="密码"]', "value": PASSWORD},
        },
        {
            "order": 5,
            "name": "输入图形验证码",
            "action": "fill",
            "params": {"selector": 'input[placeholder*="图形验证"]', "value": CAPTCHA},
        },
        {
            "order": 6,
            "name": "点击登录按钮",
            "action": "click",
            "params": {"selector": "button.login_btn"},
        },
        {
            "order": 7,
            "name": "确认同意协议弹窗",
            "action": "click",
            "params": {"selector": 'button:has-text("确定")', "timeout": 5000},
        },
        {
            "order": 8,
            "name": "等待登录成功跳转",
            "action": "wait",
            "params": {"selector": "text=admin@xty", "timeout": 15000},
        },
        {
            "order": 9,
            "name": "点击展开功能中心",
            "action": "click",
            "params": {"selector": "#Home > div:nth-child(1) > div:nth-child(1)"},
        },
    ]


def build_navigate_to_menu_steps(menu_name: str, order_start: int = 10):
    """构建导航到指定菜单的步骤"""
    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": "body", "timeout": 10000},
        },
    ]


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

def build_data_analysis_cases():
    """构建数据分析模块深层用例"""
    cases = []

    # 用例1: 会议统计-日期范围筛选
    cases.append({
        "name": "会议统计-日期范围筛选验证",
        "description": "验证会议统计页面日期范围筛选功能",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 100,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("会议统计", 10)
        + [
            {
                "order": 20,
                "name": "点击日期选择器",
                "action": "click",
                "params": {"selector": ".el-date-editor", "timeout": 5000},
            },
            {
                "order": 21,
                "name": "选择日期范围",
                "action": "click",
                "params": {"selector": ".el-date-picker__header button:has-text('本月')"},
            },
            {
                "order": 22,
                "name": "验证筛选结果",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr, .chart-container"},
            },
        ],
    })

    # 用例2: 会议统计-图表交互验证
    cases.append({
        "name": "会议统计-图表交互验证",
        "description": "验证会议统计页面图表鼠标悬停显示数据",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 101,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("会议统计", 10)
        + [
            {
                "order": 20,
                "name": "等待图表加载",
                "action": "wait",
                "params": {"selector": ".chart-container canvas, .echarts", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证图表存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".chart-container"},
            },
        ],
    })

    # 用例3: 使用数据-表格筛选
    cases.append({
        "name": "使用数据-表格筛选验证",
        "description": "验证使用数据页面表格筛选功能",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 110,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("使用数据", 10)
        + [
            {
                "order": 20,
                "name": "等待表格加载",
                "action": "wait",
                "params": {"selector": ".el-table", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证表格数据存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-table__body tr", "min_count": 1},
            },
        ],
    })

    # 用例4: 故障数据-状态筛选
    cases.append({
        "name": "故障数据-状态筛选验证",
        "description": "验证故障数据页面状态筛选下拉框",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 120,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("故障数据", 10)
        + [
            {
                "order": 20,
                "name": "点击状态筛选下拉框",
                "action": "click",
                "params": {"selector": ".el-select:has-text('状态'), .filter-item .el-select"},
            },
            {
                "order": 21,
                "name": "选择状态选项",
                "action": "click",
                "params": {"selector": ".el-select-dropdown__item:first-child"},
            },
            {
                "order": 22,
                "name": "验证筛选结果",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    # 用例5: 通知统计-类型切换
    cases.append({
        "name": "通知统计-类型切换验证",
        "description": "验证通知统计页面统计类型切换",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 130,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("通知统计", 10)
        + [
            {
                "order": 20,
                "name": "等待页面加载",
                "action": "wait",
                "params": {"selector": ".el-tabs, .chart-container", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证统计图表存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".chart-container, .echarts"},
            },
        ],
    })

    # 用例6: 历史记录-WeLink搜索
    cases.append({
        "name": "历史记录-WeLink搜索验证",
        "description": "验证WeLink历史记录页面搜索功能",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 140,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("历史记录-WeLink", 10)
        + [
            {
                "order": 20,
                "name": "等待表格加载",
                "action": "wait",
                "params": {"selector": ".el-table", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "输入搜索关键词",
                "action": "fill",
                "params": {"selector": "input[placeholder*='搜索'], input[placeholder*='查询']", "value": "会议"},
            },
            {
                "order": 22,
                "name": "点击搜索按钮",
                "action": "click",
                "params": {"selector": "button:has-text('搜索'), button:has-text('查询')"},
            },
            {
                "order": 23,
                "name": "验证搜索结果",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    # 用例7: 会议室统计-图表验证
    cases.append({
        "name": "会议室统计-图表验证",
        "description": "验证会议室统计页面图表展示",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "medium",
        "order": 150,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("会议室统计", 10)
        + [
            {
                "order": 20,
                "name": "等待图表加载",
                "action": "wait",
                "params": {"selector": ".chart-container, .echarts", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证图表存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".chart-container"},
            },
        ],
    })

    # 用例8: 预定数据-时间筛选验证
    cases.append({
        "name": "预定数据-时间筛选验证",
        "description": "验证预定数据页面时间范围筛选",
        "module_id": DATA_ANALYSIS_MODULE_ID,
        "priority": "high",
        "order": 160,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("预定数据", 10)
        + [
            {
                "order": 20,
                "name": "点击日期范围选择",
                "action": "click",
                "params": {"selector": ".el-date-editor"},
            },
            {
                "order": 21,
                "name": "验证表格数据",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    return cases


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

def build_ops_management_cases():
    """构建运维管理模块深层用例"""
    cases = []

    # 用例1: 巡检报表-日期筛选
    cases.append({
        "name": "巡检报表-日期筛选验证",
        "description": "验证巡检报表页面日期筛选功能",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "high",
        "order": 100,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("巡检报表", 10)
        + [
            {
                "order": 20,
                "name": "等待表格加载",
                "action": "wait",
                "params": {"selector": ".el-table", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "点击日期筛选",
                "action": "click",
                "params": {"selector": ".el-date-editor"},
            },
            {
                "order": 22,
                "name": "验证表格数据存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".el-table__body tr", "min_count": 1},
            },
        ],
    })

    # 用例2: 运维数据-设备筛选
    cases.append({
        "name": "运维数据-设备筛选验证",
        "description": "验证运维数据页面设备类型筛选",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 110,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("运维数据", 10)
        + [
            {
                "order": 20,
                "name": "等待表格加载",
                "action": "wait",
                "params": {"selector": ".el-table", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "点击设备类型下拉框",
                "action": "click",
                "params": {"selector": ".el-select:has-text('设备类型'), .filter-item .el-select"},
            },
            {
                "order": 22,
                "name": "选择设备类型",
                "action": "click",
                "params": {"selector": ".el-select-dropdown__item:first-child"},
            },
            {
                "order": 23,
                "name": "验证筛选结果",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".el-table__body tr"},
            },
        ],
    })

    # 用例3: 运维统计-图表验证
    cases.append({
        "name": "运维统计-图表展示验证",
        "description": "验证运维统计页面图表展示",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 120,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("运维统计", 10)
        + [
            {
                "order": 20,
                "name": "等待图表加载",
                "action": "wait",
                "params": {"selector": ".chart-container, .echarts", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证图表存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".chart-container"},
            },
        ],
    })

    # 用例4: 巡检报表-导出功能
    cases.append({
        "name": "巡检报表-导出功能验证",
        "description": "验证巡检报表页面导出按钮",
        "module_id": OPS_MANAGEMENT_MODULE_ID,
        "priority": "medium",
        "order": 130,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("巡检报表", 10)
        + [
            {
                "order": 20,
                "name": "等待表格加载",
                "action": "wait",
                "params": {"selector": ".el-table", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证导出按钮存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": "button:has-text('导出'), button:has-text('下载')"},
            },
        ],
    })

    return cases


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

def build_dashboard_cases():
    """构建管理看板模块深层用例"""
    cases = []

    # 用例1: 管理看板-数据刷新
    cases.append({
        "name": "管理看板-数据刷新验证",
        "description": "验证管理看板页面刷新按钮功能",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "high",
        "order": 100,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("管理看板", 10)
        + [
            {
                "order": 20,
                "name": "等待看板加载",
                "action": "wait",
                "params": {"selector": ".dashboard-container, .chart-container", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "点击刷新按钮",
                "action": "click",
                "params": {"selector": "button:has-text('刷新'), .refresh-btn"},
            },
            {
                "order": 22,
                "name": "验证看板数据存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".chart-container, .stat-card"},
            },
        ],
    })

    # 用例2: 会议概览-统计卡片验证
    cases.append({
        "name": "会议概览-统计卡片验证",
        "description": "验证会议概览页面统计卡片展示",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "high",
        "order": 110,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("会议概览", 10)
        + [
            {
                "order": 20,
                "name": "等待统计卡片加载",
                "action": "wait",
                "params": {"selector": ".stat-card, .card-item", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证统计卡片存在",
                "action": "assert",
                "params": {"type": "element_count_min", "selector": ".stat-card, .card-item", "min_count": 1},
            },
        ],
    })

    # 用例3: 会议室概览-图表交互
    cases.append({
        "name": "会议室概览-图表交互验证",
        "description": "验证会议室概览页面图表交互",
        "module_id": DASHBOARD_MODULE_ID,
        "priority": "medium",
        "order": 120,
        "config": DEFAULT_CONFIG,
        "steps": build_base_steps()
        + build_navigate_to_menu_steps("会议室概览", 10)
        + [
            {
                "order": 20,
                "name": "等待图表加载",
                "action": "wait",
                "params": {"selector": ".chart-container, .echarts", "timeout": 10000},
            },
            {
                "order": 21,
                "name": "验证图表存在",
                "action": "assert",
                "params": {"type": "element_exists", "selector": ".chart-container"},
            },
        ],
    })

    return cases


async def create_cases():
    """创建所有补充用例"""
    async with httpx.AsyncClient(timeout=60) as client:
        created_count = 0

        # 数据分析模块用例
        print("=" * 60)
        print("【数据分析模块】补充用例")
        print("=" * 60)
        for case in build_data_analysis_cases():
            r = await client.post(f"{BASE_URL}/api/cases", json=case)
            if r.status_code == 201:
                print(f"  ✅ {case['name']}")
                created_count += 1
            else:
                print(f"  ❌ {case['name']}: {r.status_code} {r.text[:100]}")

        # 运维管理模块用例
        print("\n" + "=" * 60)
        print("【运维管理模块】补充用例")
        print("=" * 60)
        for case in build_ops_management_cases():
            r = await client.post(f"{BASE_URL}/api/cases", json=case)
            if r.status_code == 201:
                print(f"  ✅ {case['name']}")
                created_count += 1
            else:
                print(f"  ❌ {case['name']}: {r.status_code} {r.text[:100]}")

        # 管理看板模块用例
        print("\n" + "=" * 60)
        print("【管理看板模块】补充用例")
        print("=" * 60)
        for case in build_dashboard_cases():
            r = await client.post(f"{BASE_URL}/api/cases", json=case)
            if r.status_code == 201:
                print(f"  ✅ {case['name']}")
                created_count += 1
            else:
                print(f"  ❌ {case['name']}: {r.status_code} {r.text[:100]}")

        print("\n" + "=" * 60)
        print(f"✅ 共创建 {created_count} 个用例")
        print("=" * 60)


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