#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：create_deep_interaction_cases.py
模块描述：创建深层交互测试用例

功能：
1. 登录流程完整测试（包含表单填写、按钮点击、协议确认）
2. 会议预约功能测试（包含表单填写、下拉选择、日期选择）
3. 会议室查询测试（包含搜索、筛选、分页）
4. 数据统计验证测试（包含数据读取、图表验证）

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

import sys
import os
import asyncio
import json
from pathlib import Path

# 添加项目根目录到路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from app.database import async_session_maker, init_db
from app.models.module import Module
from app.models.test_case import TestCase
from app.utils.id_generator import generate_id


# ==================== 深层交互用例定义 ====================

DEEP_INTERACTION_CASES = [
    # ==================== 登录流程测试 ====================
    {
        "module_name": "登录模块",
        "name": "登录流程-完整登录验证",
        "description": "测试完整的登录流程，包括表单填写、按钮点击、协议确认",
        "priority": "high",
        "tags": ["登录", "表单", "核心功能"],
        "steps": [
            {
                "order": 1,
                "name": "访问登录页面",
                "action": "navigate",
                "params": {"url": "https://192.168.5.44/"},
                "expected": "显示登录表单"
            },
            {
                "order": 2,
                "name": "验证登录表单可见",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": "input[type='text'], input[placeholder*='用户']"
                },
                "expected": "用户名输入框可见"
            },
            {
                "order": 3,
                "name": "填写用户名",
                "action": "fill",
                "params": {
                    "selector": "input[type='text']",
                    "value": "admin@xty"
                },
                "expected": "用户名填写成功"
            },
            {
                "order": 4,
                "name": "填写密码",
                "action": "fill",
                "params": {
                    "selector": "input[type='password']",
                    "value": "Ubains@13579"
                },
                "expected": "密码填写成功"
            },
            {
                "order": 5,
                "name": "填写验证码",
                "action": "fill",
                "params": {
                    "selector": "input[placeholder*='验证']",
                    "value": "csba"
                },
                "expected": "验证码填写成功"
            },
            {
                "order": 6,
                "name": "点击登录按钮",
                "action": "click",
                "params": {
                    "selector": "button:has-text('登录')"
                },
                "expected": "点击登录按钮"
            },
            {
                "order": 7,
                "name": "等待页面跳转",
                "action": "wait",
                "params": {
                    "selector": "body",
                    "timeout": 5000
                },
                "expected": "页面跳转完成"
            },
            {
                "order": 8,
                "name": "处理协议弹窗",
                "action": "click",
                "params": {
                    "selector": ".el-dialog button:has-text('确定'), [role='dialog'] button:has-text('确定')"
                },
                "expected": "确认协议弹窗"
            },
            {
                "order": 9,
                "name": "验证登录成功",
                "action": "assert",
                "params": {
                    "type": "url",
                    "expected": "platform"
                },
                "expected": "URL包含platform，登录成功"
            }
        ],
        "config": {
            "timeout": 30000,
            "screenshot": True,
            "auto_login": False  # 登录测试不自动登录
        }
    },

    # ==================== 会议预约测试 ====================
    {
        "module_name": "会议预约",
        "name": "会议预约-新建会议预约",
        "description": "测试新建会议预约的完整流程，包括日期选择、会议室选择、信息填写",
        "priority": "high",
        "tags": ["会议预约", "表单", "核心功能"],
        "steps": [
            {
                "order": 1,
                "name": "导航到会议预约页面",
                "action": "navigate",
                "params": {"url": "https://192.168.5.44/#/meeting/reservation"},
                "expected": "进入会议预约模块"
            },
            {
                "order": 2,
                "name": "验证页面标题",
                "action": "assert",
                "params": {
                    "type": "contains",
                    "selector": "body",
                    "expected": "预约"
                },
                "expected": "页面包含预约相关内容"
            },
            {
                "order": 3,
                "name": "点击新建预约按钮",
                "action": "click",
                "params": {
                    "selector": "button:has-text('新建'), button:has-text('预约')"
                },
                "expected": "打开新建预约表单"
            },
            {
                "order": 4,
                "name": "等待表单加载",
                "action": "wait",
                "params": {
                    "selector": ".el-form, form",
                    "timeout": 5000
                },
                "expected": "表单加载完成"
            },
            {
                "order": 5,
                "name": "验证表单可见",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".el-form-item, form-item"
                },
                "expected": "表单项可见"
            }
        ],
        "config": {
            "timeout": 30000,
            "screenshot": True,
            "auto_login": True  # 需要登录态
        }
    },

    # ==================== 会议室列表测试 ====================
    {
        "module_name": "会议室列表",
        "name": "会议室列表-搜索筛选功能",
        "description": "测试会议室列表的搜索、筛选、分页功能",
        "priority": "high",
        "tags": ["会议室", "搜索", "筛选"],
        "steps": [
            {
                "order": 1,
                "name": "导航到会议室列表",
                "action": "navigate",
                "params": {"url": "https://192.168.5.44/#/meeting/room"},
                "expected": "进入会议室列表页面"
            },
            {
                "order": 2,
                "name": "验证列表加载",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".el-table, table, .list"
                },
                "expected": "列表组件可见"
            },
            {
                "order": 3,
                "name": "验证搜索框",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": "input[placeholder*='搜索'], input[placeholder*='查询'], .el-input"
                },
                "expected": "搜索框可见"
            },
            {
                "order": 4,
                "name": "填写搜索关键词",
                "action": "fill",
                "params": {
                    "selector": "input[placeholder*='搜索'], input[placeholder*='查询']",
                    "value": "会议室"
                },
                "expected": "填写搜索关键词"
            },
            {
                "order": 5,
                "name": "点击搜索按钮",
                "action": "click",
                "params": {
                    "selector": "button:has-text('搜索'), button:has-text('查询')"
                },
                "expected": "执行搜索"
            },
            {
                "order": 6,
                "name": "等待搜索结果",
                "action": "wait",
                "params": {
                    "selector": ".el-table, table",
                    "timeout": 5000
                },
                "expected": "搜索结果加载完成"
            }
        ],
        "config": {
            "timeout": 30000,
            "screenshot": True,
            "auto_login": True
        }
    },

    # ==================== 管理看板测试 ====================
    {
        "module_name": "管理看板",
        "name": "管理看板-数据展示验证",
        "description": "验证管理看板的数据统计和图表展示功能",
        "priority": "medium",
        "tags": ["看板", "数据", "图表"],
        "steps": [
            {
                "order": 1,
                "name": "导航到管理看板",
                "action": "navigate",
                "params": {"url": "https://192.168.5.44/#/dashboard/management"},
                "expected": "进入管理看板"
            },
            {
                "order": 2,
                "name": "验证数据卡片",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".card, .data-card, .stat-card, .el-card"
                },
                "expected": "数据卡片可见"
            },
            {
                "order": 3,
                "name": "验证图表组件",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".chart, .echarts, canvas, [class*='chart']"
                },
                "expected": "图表组件可见"
            },
            {
                "order": 4,
                "name": "验证数据非空",
                "action": "assert",
                "params": {
                    "type": "count",
                    "selector": ".card, .stat-card",
                    "expected": "2"
                },
                "expected": "至少有2个数据卡片"
            }
        ],
        "config": {
            "timeout": 30000,
            "screenshot": True,
            "auto_login": True
        }
    },

    # ==================== 会议列表测试 ====================
    {
        "module_name": "会议列表",
        "name": "会议列表-列表操作验证",
        "description": "测试会议列表的展示、筛选、详情查看功能",
        "priority": "medium",
        "tags": ["会议列表", "筛选", "详情"],
        "steps": [
            {
                "order": 1,
                "name": "导航到会议列表",
                "action": "navigate",
                "params": {"url": "https://192.168.5.44/#/meeting/list"},
                "expected": "进入会议列表页面"
            },
            {
                "order": 2,
                "name": "验证表格加载",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".el-table, table"
                },
                "expected": "表格可见"
            },
            {
                "order": 3,
                "name": "验证筛选区域",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".filter, .search, .el-form"
                },
                "expected": "筛选区域可见"
            },
            {
                "order": 4,
                "name": "滚动查看更多数据",
                "action": "scroll",
                "params": {
                    "direction": "down",
                    "distance": 500
                },
                "expected": "滚动页面"
            }
        ],
        "config": {
            "timeout": 30000,
            "screenshot": True,
            "auto_login": True
        }
    },

    # ==================== 系统设置测试 ====================
    {
        "module_name": "集控控制",
        "name": "集控控制-页面操作验证",
        "description": "验证集控控制页面是否正常加载和操作",
        "priority": "low",
        "tags": ["设置", "系统"],
        "steps": [
            {
                "order": 1,
                "name": "导航到集控控制页面",
                "action": "navigate",
                "params": {"url": "https://192.168.5.44/#/system/control"},
                "expected": "进入集控控制页面"
            },
            {
                "order": 2,
                "name": "验证页面内容",
                "action": "assert",
                "params": {
                    "type": "visible",
                    "selector": ".content, .main, .el-card"
                },
                "expected": "页面内容可见"
            }
        ],
        "config": {
            "timeout": 30000,
            "screenshot": True,
            "auto_login": True
        }
    }
]


async def create_deep_cases():
    """创建深层交互测试用例"""

    print("=" * 60)
    print("Creating deep interaction test cases...")
    print("=" * 60)

    # 初始化数据库
    await init_db()

    async with async_session_maker() as db:
        created_count = 0
        skipped_count = 0
        updated_count = 0

        for case_data in DEEP_INTERACTION_CASES:
            module_name = case_data["module_name"]
            case_name = case_data["name"]

            # 查找模块（使用名称模糊匹配）
            query = select(Module).where(Module.name.contains(module_name))
            result = await db.execute(query)
            module = result.scalar_one_or_none()

            if not module:
                print(f"[WARN] Module not found, skip: {module_name}")
                skipped_count += 1
                continue

            # 检查用例是否已存在
            existing_query = select(TestCase).where(
                TestCase.module_id == module.id,
                TestCase.name == case_name
            )
            existing_result = await db.execute(existing_query)
            existing_case = existing_result.scalar_one_or_none()

            if existing_case:
                # 更新现有用例
                existing_case.steps = case_data["steps"]
                existing_case.config = case_data["config"]
                existing_case.description = case_data["description"]
                existing_case.priority = case_data["priority"]
                existing_case.tags = case_data["tags"]
                print(f"[UPDATE] Update case: {case_name} (module: {module.name})")
                updated_count += 1
            else:
                # 创建新用例
                new_case = TestCase(
                    id=generate_id("case"),
                    module_id=module.id,
                    name=case_name,
                    description=case_data.get("description", ""),
                    status="active",
                    priority=case_data.get("priority", "medium"),
                    tags=case_data.get("tags", []),
                    steps=case_data["steps"],
                    config=case_data.get("config", {}),
                )
                db.add(new_case)
                print(f"[CREATE] Create case: {case_name} (module: {module.name})")
                created_count += 1

        await db.commit()

    print("\n" + "=" * 60)
    print("Creation completed")
    print(f"  - Created: {created_count}")
    print(f"  - Updated: {updated_count}")
    print(f"  - Skipped: {skipped_count}")
    print("=" * 60)


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