"""
user_space/management/commands/create_app.py
用于在user_space/apps/下创建新的CMS应用包
支持两种模式：模块化目录结构（默认）和传统单文件结构
"""

import os
import re

from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "在user_space/apps/目录下创建新的CMS应用包（支持两种结构模式）"

    def add_arguments(self, parser):
        parser.add_argument("app_name", type=str, help="应用名称")
        parser.add_argument("--description", type=str, default="", help="应用描述")
        parser.add_argument("--no-deps", action="store_true", help="不创建dependencies.txt文件")
        parser.add_argument("--no-reqs", action="store_true", help="不创建requirements.txt文件")
        parser.add_argument(
            "--traditional", action="store_true", help="使用传统单文件结构（而不是模块化目录结构）"
        )
        parser.add_argument(
            "--minimal", action="store_true", help="创建最小化结构（只包含必需文件）"
        )

    def handle(self, *args, **options):
        app_name = options["app_name"]
        description = options["description"]
        create_deps = not options["no_deps"]
        create_reqs = not options["no_reqs"]
        traditional = options["traditional"]
        minimal = options["minimal"]

        # 验证应用名称
        if not re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", app_name):
            raise CommandError(
                f"'{app_name}' 不是有效的Python标识符。"
                "请确保应用名称以字母或下划线开头，且只包含字母、数字和下划线。"
            )

        # 目标路径
        base_dir = os.path.join("user_space", "apps")
        target_dir = os.path.join(base_dir, app_name)

        # 检查目录是否存在
        if os.path.exists(target_dir):
            raise CommandError(f"应用 '{app_name}' 已存在于 {target_dir}")

        # 确保基础目录存在
        os.makedirs(base_dir, exist_ok=True)

        # 选择创建模式
        if traditional:
            self.stdout.write("🔧 使用传统单文件结构...")
            self.create_traditional_structure(
                app_name, target_dir, description, create_deps, create_reqs, minimal
            )
        else:
            self.stdout.write("✨ 使用模块化目录结构...")
            self.create_modular_structure(
                app_name, target_dir, description, create_deps, create_reqs, minimal
            )

        mode_text = "传统单文件" if traditional else "模块化目录"
        self.stdout.write(self.style.SUCCESS(f"✓ 应用 '{app_name}' 创建成功！({mode_text}结构)"))
        self.stdout.write(f"应用路径: {target_dir}")

        if create_deps:
            deps_path = os.path.join(target_dir, "dependencies.txt")
            self.stdout.write(f"✓ dependencies.txt: {deps_path}")

        if create_reqs:
            reqs_path = os.path.join(target_dir, "requirements.txt")
            self.stdout.write(f"✓ requirements.txt: {reqs_path}")

        self.stdout.write("\n📋 使用说明：")
        self.stdout.write(f"1. 在 settings.py 的 INSTALLED_APPS 中添加:")
        self.stdout.write(f"   'user_space.apps.{app_name}',")
        self.stdout.write(f"2. 运行 python manage.py makemigrations {app_name}")
        self.stdout.write(f"3. 运行 python manage.py migrate")

        if traditional:
            self.stdout.write(f"\n📁 应用结构说明（传统模式）:")
            self.stdout.write(f"  - admin.py: 管理后台配置（单文件）")
            self.stdout.write(f"  - models.py: 数据模型（单文件）")
            self.stdout.write(f"  - views.py: 视图函数（单文件）")
        else:
            self.stdout.write(f"\n📁 应用结构说明（模块化模式）:")
            self.stdout.write(f"  - admin/: 后台管理配置目录")
            self.stdout.write(f"  - models/: 数据模型目录")
            self.stdout.write(f"  - views/: 视图目录")
            self.stdout.write(f"  - utils/: 工具函数目录")
            self.stdout.write(f"  - templatetags/: 自定义模板标签")

    def create_modular_structure(
        self, app_name, target_dir, description, create_deps, create_reqs, minimal
    ):
        """创建模块化目录结构"""

        # 创建主目录
        os.makedirs(target_dir, exist_ok=True)

        # 基础子目录
        dirs_to_create = [
            "migrations",
            os.path.join("templates", app_name),
            os.path.join("static", app_name, "css"),
            os.path.join("static", app_name, "js"),
            os.path.join("static", app_name, "images"),
        ]

        # 如果不是最小化模式，创建完整目录结构
        if not minimal:
            dirs_to_create.extend(
                [
                    "models",
                    "admin",
                    "views",
                    "utils",
                    "templatetags",
                ]
            )

        for subdir in dirs_to_create:
            dir_path = os.path.join(target_dir, subdir)
            os.makedirs(dir_path, exist_ok=True)
            # 创建__init__.py文件
            if not subdir.endswith(("css", "js", "images")):
                init_file = os.path.join(dir_path, "__init__.py")
                with open(init_file, "w", encoding="utf-8") as f:
                    f.write("")

        # 创建模板目录
        self.create_template_dirs(app_name, target_dir)

        # 创建静态文件
        self.create_static_files(app_name, target_dir)

        if not minimal:
            # 创建templatetags
            self.create_templatetags_files(app_name, target_dir)

            # 创建模块化的Python文件
            self.create_modular_python_files(app_name, target_dir, description)

        # 创建核心Python文件（两种模式都需要）
        self.create_core_files(
            app_name, target_dir, description, create_deps, create_reqs, modular=True
        )

    def create_traditional_structure(
        self, app_name, target_dir, description, create_deps, create_reqs, minimal
    ):
        """创建传统单文件结构"""

        # 创建主目录
        os.makedirs(target_dir, exist_ok=True)

        # 基础子目录
        dirs_to_create = [
            "migrations",
            os.path.join("templates", app_name),
            os.path.join("static", app_name, "css"),
            os.path.join("static", app_name, "js"),
            os.path.join("static", app_name, "images"),
        ]

        for subdir in dirs_to_create:
            dir_path = os.path.join(target_dir, subdir)
            os.makedirs(dir_path, exist_ok=True)
            # 创建__init__.py文件
            if not subdir.endswith(("css", "js", "images")):
                init_file = os.path.join(dir_path, "__init__.py")
                with open(init_file, "w", encoding="utf-8") as f:
                    f.write("")

        # 创建模板目录
        self.create_template_dirs(app_name, target_dir)

        # 创建静态文件
        self.create_static_files(app_name, target_dir)

        # 创建传统单文件结构的Python文件
        self.create_traditional_python_files(
            app_name, target_dir, description, create_deps, create_reqs, minimal
        )

    def create_template_dirs(self, app_name, target_dir):
        """创建模板目录结构"""
        # 创建admin模板目录
        admin_template_dir = os.path.join(target_dir, "templates", app_name, "admin")
        os.makedirs(admin_template_dir, exist_ok=True)

        # 创建基础模板
        base_template = os.path.join(target_dir, "templates", app_name, "base.html")
        with open(base_template, "w", encoding="utf-8") as f:
            f.write(
                f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{% block title %}}{app_name.title()}{{% endblock %}}</title>
    
    <!-- 加载静态文件 -->
    {{% load static %}}
    
    <!-- CSS 文件 -->
    <link rel="stylesheet" href="{{% static '{app_name}/css/style.css' %}}">
    
    {{% block extra_css %}}
    <!-- 额外的CSS -->
    {{% endblock %}}
</head>
<body>
    <div class="container">
        {{% block content %}}
        <!-- 主要内容区域 -->
        {{% endblock %}}
    </div>
    
    <!-- JavaScript 文件 -->
    <script src="{{% static '{app_name}/js/main.js' %}}"></script>
    
    {{% block extra_js %}}
    <!-- 额外的JavaScript -->
    {{% endblock %}}
</body>
</html>
"""
            )

    def create_static_files(self, app_name, target_dir):
        """创建示例静态文件"""
        # CSS文件
        css_file = os.path.join(target_dir, "static", app_name, "css", "style.css")
        with open(css_file, "w", encoding="utf-8") as f:
            f.write(
                f"""/* {app_name.title()} 应用样式 */
body {{
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 20px;
    background-color: #f5f5f5;
}}

.container {{
    max-width: 1200px;
    margin: 0 auto;
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}}

/* 添加你的自定义样式 */
"""
            )

        # JavaScript文件
        js_file = os.path.join(target_dir, "static", app_name, "js", "main.js")
        with open(js_file, "w", encoding="utf-8") as f:
            f.write(
                f"""// {app_name.title()} 应用JavaScript
console.log('{app_name}应用已加载');

document.addEventListener('DOMContentLoaded', function() {{
    // 页面加载完成后的初始化代码
    console.log('页面已加载');
}});

// 添加你的自定义JavaScript函数
function showAlert(message) {{
    alert(message);
}}
"""
            )

    def create_templatetags_files(self, app_name, target_dir):
        """创建templatetags文件"""
        # 创建templatetags目录
        templatetags_dir = os.path.join(target_dir, "templatetags")
        os.makedirs(templatetags_dir, exist_ok=True)

        # 示例过滤器
        filters_file = os.path.join(templatetags_dir, f"{app_name}_filters.py")
        with open(filters_file, "w", encoding="utf-8") as f:
            f.write(
                f"""from django import template

register = template.Library()

@register.filter(name='add_class')
def add_class(value, css_class):
    '''添加CSS类到表单字段'''
    return value.as_widget(attrs={{"class": css_class}})

@register.filter(name='truncate_chars')
def truncate_chars(value, max_length):
    '''截断字符串，并添加省略号'''
    if len(value) <= max_length:
        return value
    return value[:max_length] + '...'

@register.filter(name='format_date')
def format_date(value, format_string='Y-m-d'):
    '''格式化日期'''
    from django.template.defaultfilters import date
    return date(value, format_string)
"""
            )

    def create_modular_python_files(self, app_name, target_dir, description):
        """创建模块化结构的Python文件"""

        # 创建admin.py（统一入口）
        admin_content = f"""# {app_name} 应用的管理后台统一入口
# 从admin/目录导入所有配置
from django.contrib import admin
from .admin import *
"""
        self.write_file(target_dir, "admin.py", admin_content)

        # 创建models.py（统一入口）
        models_content = f"""# {app_name} 应用的模型统一入口
# 从models/目录导入所有模型
from .models import *
"""
        self.write_file(target_dir, "models.py", models_content)

        # 1. models/ 目录
        models_dir = os.path.join(target_dir, "models")

        # models/__init__.py
        models_init_content = """# 在此导入所有模型
# 示例：
# from .example import ExampleModel
# from .user import User
# 
# __all__ = ['ExampleModel', 'User']

# 注意：Django会自动发现所有模型
"""
        self.write_file(models_dir, "__init__.py", models_init_content)

        # 示例模型文件
        example_model = os.path.join(models_dir, "example.py")
        with open(example_model, "w", encoding="utf-8") as f:
            f.write(
                f'''from django.db import models


class ExampleModel(models.Model):
    """示例模型"""
    name = models.CharField('名称', max_length=100)
    description = models.TextField('描述', blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '示例模型'
        verbose_name_plural = '示例模型'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
'''
            )

        # 2. admin/ 目录
        admin_dir = os.path.join(target_dir, "admin")

        # admin/__init__.py
        admin_init_content = """# 在此导入所有admin配置
# 示例：
# from .example import *
# from .user import *

# 注意：在admin/example.py中注册的模型会自动生效
"""
        self.write_file(admin_dir, "__init__.py", admin_init_content)

        # 示例admin配置
        example_admin = os.path.join(admin_dir, "example.py")
        with open(example_admin, "w", encoding="utf-8") as f:
            f.write(
                f'''from django.contrib import admin
from ..models.example import ExampleModel


@admin.register(ExampleModel)
class ExampleModelAdmin(admin.ModelAdmin):
    """示例模型管理"""
    list_display = ['id', 'name', 'created_at', 'updated_at']
    list_display_links = ['id', 'name']
    search_fields = ['name', 'description']
    list_filter = ['created_at']
    ordering = ['-created_at']
    
    fieldsets = (
        ('基本信息', {{
            'fields': ('name', 'description')
        }}),
        ('时间信息', {{
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }}),
    )
    
    readonly_fields = ['created_at', 'updated_at']
'''
            )

        # 3. views/ 目录
        views_dir = os.path.join(target_dir, "views")

        # views/__init__.py
        views_init_content = """# 在此导入所有视图
# 示例：
# from .example import example_list, ExampleListView
# 
# __all__ = ['example_list', 'ExampleListView']

# 注意：需要在urls.py中配置这些视图的路由
"""
        self.write_file(views_dir, "__init__.py", views_init_content)

        # 示例视图文件
        example_view = os.path.join(views_dir, "example.py")
        with open(example_view, "w", encoding="utf-8") as f:
            f.write(
                f'''from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView
from ..models.example import ExampleModel


def example_list(request):
    """示例视图函数"""
    examples = ExampleModel.objects.all()[:10]
    context = {{
        'examples': examples,
        'title': '示例列表'
    }}
    return render(request, '{app_name}/example_list.html', context)


class ExampleListView(ListView):
    """示例列表视图（类视图）"""
    model = ExampleModel
    template_name = '{app_name}/example_list.html'
    context_object_name = 'examples'
    paginate_by = 20
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '示例列表（类视图）'
        return context
'''
            )

        # 4. utils/ 目录
        utils_dir = os.path.join(target_dir, "utils")

        # utils/__init__.py
        utils_init_content = """# 工具函数模块
# 在此导入所有工具函数
# 示例：
# from .helpers import format_datetime, generate_code
# 
# __all__ = ['format_datetime', 'generate_code']
"""
        self.write_file(utils_dir, "__init__.py", utils_init_content)

        # 示例工具函数
        example_utils = os.path.join(utils_dir, "helpers.py")
        with open(example_utils, "w", encoding="utf-8") as f:
            f.write(
                f'''import random
import string
from datetime import datetime


def generate_random_code(length=8):
    """生成随机代码"""
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(length))


def format_datetime(dt, format_str='%Y-%m-%d %H:%M:%S'):
    """格式化日期时间"""
    if dt is None:
        return ''
    if isinstance(dt, str):
        return dt
    return dt.strftime(format_str)
'''
            )

    def create_traditional_python_files(
        self, app_name, target_dir, description, create_deps, create_reqs, minimal
    ):
        """创建传统单文件结构的Python文件"""

        # 1. __init__.py
        init_content = self.generate_init_file(app_name, description, traditional=True)
        self.write_file(target_dir, "__init__.py", init_content)

        # 2. apps.py
        apps_content = self.generate_apps_file(app_name)
        self.write_file(target_dir, "apps.py", apps_content)

        # 3. admin.py
        admin_content = self.generate_traditional_admin_file(app_name)
        self.write_file(target_dir, "admin.py", admin_content)

        # 4. models.py
        models_content = self.generate_traditional_models_file(app_name)
        self.write_file(target_dir, "models.py", models_content)

        # 5. views.py
        views_content = self.generate_traditional_views_file(app_name)
        self.write_file(target_dir, "views.py", views_content)

        # 6. urls.py
        urls_content = self.generate_traditional_urls_file(app_name)
        self.write_file(target_dir, "urls.py", urls_content)

        # 7. tests.py
        tests_content = self.generate_tests_file()
        self.write_file(target_dir, "tests.py", tests_content)

        if not minimal:
            # 8. forms.py
            forms_content = '''# 表单文件
from django import forms
from django.core.exceptions import ValidationError


class ExampleForm(forms.Form):
    """示例表单"""
    name = forms.CharField(label='名称', max_length=100)
    description = forms.CharField(label='描述', widget=forms.Textarea, required=False)
    
    def clean_name(self):
        name = self.cleaned_data.get('name')
        if len(name) < 3:
            raise ValidationError('名称至少需要3个字符')
        return name
'''
            self.write_file(target_dir, "forms.py", forms_content)

            # 9. serializers.py
            serializers_content = """# 序列化器文件（如果需要DRF）
# from rest_framework import serializers
# from .models import ExampleModel
# 
# class ExampleModelSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = ExampleModel
#         fields = '__all__'
"""
            self.write_file(target_dir, "serializers.py", serializers_content)

            # 10. 创建templatetags目录
            templatetags_dir = os.path.join(target_dir, "templatetags")
            os.makedirs(templatetags_dir, exist_ok=True)

            # templatetags/__init__.py
            self.write_file(templatetags_dir, "__init__.py", "")

            # 示例模板标签
            filters_file = os.path.join(templatetags_dir, f"{app_name}_filters.py")
            with open(filters_file, "w", encoding="utf-8") as f:
                f.write(
                    f"""from django import template

register = template.Library()

@register.filter(name='add_class')
def add_class(value, css_class):
    '''添加CSS类到表单字段'''
    return value.as_widget(attrs={{"class": css_class}})"""
                )

        # 11. 创建dependencies.txt
        if create_deps:
            deps_content = self.generate_dependencies_content(app_name)
            deps_file = os.path.join(target_dir, "dependencies.txt")
            with open(deps_file, "w", encoding="utf-8") as f:
                f.write(deps_content)

        # 12. 创建requirements.txt
        if create_reqs:
            reqs_content = self.generate_requirements_content()
            reqs_file = os.path.join(target_dir, "requirements.txt")
            with open(reqs_file, "w", encoding="utf-8") as f:
                f.write(reqs_content)

    def create_core_files(
        self, app_name, target_dir, description, create_deps, create_reqs, modular=False
    ):
        """创建核心文件（两种模式都需要）"""

        # 1. __init__.py
        init_content = self.generate_init_file(app_name, description, traditional=not modular)
        self.write_file(target_dir, "__init__.py", init_content)

        # 2. apps.py
        apps_content = self.generate_apps_file(app_name)
        self.write_file(target_dir, "apps.py", apps_content)

        # 3. urls.py
        if modular:
            urls_content = self.generate_modular_urls_file(app_name)
        else:
            urls_content = self.generate_traditional_urls_file(app_name)
        self.write_file(target_dir, "urls.py", urls_content)

        # 4. tests.py
        tests_content = self.generate_tests_file()
        self.write_file(target_dir, "tests.py", tests_content)

        if not modular:
            # 5. forms.py
            forms_content = "# 表单文件\nfrom django import forms\n\n# 在此定义你的表单\n"
            self.write_file(target_dir, "forms.py", forms_content)

            # 6. serializers.py
            serializers_content = "# 序列化器文件（如果需要DRF）\n# from rest_framework import serializers\n\n# 在此定义序列化器\n"
            self.write_file(target_dir, "serializers.py", serializers_content)

        # 7. 创建dependencies.txt
        if create_deps:
            deps_content = self.generate_dependencies_content(app_name)
            deps_file = os.path.join(target_dir, "dependencies.txt")
            with open(deps_file, "w", encoding="utf-8") as f:
                f.write(deps_content)

        # 8. 创建requirements.txt
        if create_reqs:
            reqs_content = self.generate_requirements_content()
            reqs_file = os.path.join(target_dir, "requirements.txt")
            with open(reqs_file, "w", encoding="utf-8") as f:
                f.write(reqs_content)

    def write_file(self, directory, filename, content):
        """写入文件"""
        filepath = os.path.join(directory, filename)
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(content)

    def generate_dependencies_content(self, app_name):
        """生成应用内的dependencies.txt内容"""
        app_module = f"user_space.apps.{app_name}"

        return f"""# {app_name} 应用的依赖声明文件
# 此文件列出了此应用需要在settings.py的INSTALLED_APPS中注册的模块
# 格式：每行一个模块路径
# 注意：此应用本身必须添加到INSTALLED_APPS

# 应用自身（必须添加）
{app_module}

# 依赖的其他应用（如果需要）
# django.contrib.auth
# django.contrib.admin
# rest_framework
# your_other_app.apps.YourOtherAppConfig
"""

    def generate_requirements_content(self):
        """生成应用内的requirements.txt内容"""
        return """# 此应用需要的Python依赖包
# 格式：每行一个包名，可指定版本
# 示例：
# Django>=4.0
# djangorestframework>=3.13
# django-filter>=22.0
# pillow>=9.0
"""

    def generate_init_file(self, app_name, description, traditional=False):
        """生成__init__.py文件"""
        app_title = app_name.replace("_", " ").title()
        if not description:
            description = f"{app_title} 应用"

        mode = "传统单文件结构" if traditional else "模块化目录结构"

        return f'''"""
{description}

应用名称: {app_name}
模块路径: user_space.apps.{app_name}
结构模式: {mode}
创建时间: {self.get_current_time()}
"""

# 默认导出
__version__ = "1.0.0"
__author__ = "Your Name"
__description__ = "{description}"

# 应用配置
default_app_config = 'user_space.apps.{app_name}.apps.{self.to_camel_case(app_name)}Config'

# 在此可以定义应用级别的变量或函数
'''

    def generate_apps_file(self, app_name):
        """生成apps.py文件"""
        app_name_title = app_name.replace("_", " ").title()
        return f"""from django.apps import AppConfig
from apps.core.services.route_service import register_app_urls


class {self.to_camel_case(app_name)}Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'user_space.apps.{app_name}'
    verbose_name = '{app_name_title}管理'

    def ready(self):
        # 自动注册路由
        register_app_urls(
            prefix="{app_name}",  # URL前缀
            app_name=self.name  # 应用命名空间
        )
"""

    def generate_traditional_admin_file(self, app_name):
        """生成传统结构的admin.py文件"""
        return f'''# {app_name} 管理后台配置
from django.contrib import admin
from .models import ExampleModel


@admin.register(ExampleModel)
class ExampleModelAdmin(admin.ModelAdmin):
    """示例模型管理"""
    list_display = ['id', 'name', 'created_at', 'updated_at']
    list_display_links = ['id', 'name']
    search_fields = ['name', 'description']
    list_filter = ['created_at']
    ordering = ['-created_at']
    
    fieldsets = (
        ('基本信息', {{
            'fields': ('name', 'description')
        }}),
        ('时间信息', {{
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }}),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    
    
# 在此注册更多模型
# from .models import YourModel
# 
# @admin.register(YourModel)
# class YourModelAdmin(admin.ModelAdmin):
#     pass
'''

    def generate_traditional_models_file(self, app_name):
        """生成传统结构的models.py文件"""
        return f'''from django.db import models


class ExampleModel(models.Model):
    """示例模型"""
    name = models.CharField('名称', max_length=100)
    description = models.TextField('描述', blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '示例模型'
        verbose_name_plural = '示例模型'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
    
    
# 在此定义更多模型
# class YourModel(models.Model):
#     name = models.CharField('名称', max_length=100)
#     # ... 其他字段
#     
#     def __str__(self):
#         return self.name
'''

    def generate_traditional_views_file(self, app_name):
        """生成传统结构的views.py文件"""
        return f'''from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView
from .models import ExampleModel


def example_list(request):
    """示例视图函数"""
    examples = ExampleModel.objects.all()[:10]
    context = {{
        'examples': examples,
        'title': '示例列表'
    }}
    return render(request, '{app_name}/example_list.html', context)


class ExampleListView(ListView):
    """示例列表视图（类视图）"""
    model = ExampleModel
    template_name = '{app_name}/example_list.html'
    context_object_name = 'examples'
    paginate_by = 20
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '示例列表（类视图）'
        return context
    
    
# 在此定义更多视图
# def your_view(request):
#     return HttpResponse("你的视图")
'''

    def generate_traditional_urls_file(self, app_name):
        """生成传统结构的urls.py文件"""
        return f"""# {app_name} 应用路由配置
from django.urls import path
from . import views


app_name = "{app_name}"

urlpatterns = [
    # 在此添加你的路由
    # 示例：
    # path('', views.example_list, name='index'),
    # path('list/', views.ExampleListView.as_view(), name='list'),
]
"""

    def generate_modular_urls_file(self, app_name):
        """生成模块化结构的urls.py文件"""
        return f"""# {app_name} 应用路由配置
from django.urls import path, include


app_name = "{app_name}"

urlpatterns = [
    # 在此添加你的路由
    # 示例（取消注释并使用）:
    # path('', include('.views.example', namespace='example')),
    # 
    # 或者直接导入视图:
    # from .views.example import example_list, ExampleListView
    # path('', example_list, name='index'),
    # path('list/', ExampleListView.as_view(), name='list'),
]
"""

    def generate_tests_file(self):
        """生成tests.py文件"""
        return '''# 测试文件
from django.test import TestCase
from django.urls import reverse


class ExampleTests(TestCase):
    """示例测试类"""
    
    def test_example(self):
        """示例测试"""
        self.assertEqual(1 + 1, 2)
    
    # 在此编写你的测试用例
    # def test_home_page(self):
    #     response = self.client.get(reverse('yourapp:index'))
    #     self.assertEqual(response.status_code, 200)
'''

    def to_camel_case(self, snake_str):
        """将snake_case转换为CamelCase"""
        components = snake_str.split("_")
        return "".join(x.title() for x in components)

    def get_current_time(self):
        """获取当前时间字符串"""
        from datetime import datetime

        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
