import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import FancyBboxPatch
import numpy as np

# 设置中文字体 - 优先使用Microsoft YaHei
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 创建图形 - 调整尺寸和DPI
fig, ax = plt.subplots(1, 1, figsize=(16, 12))

# 定义颜色方案
colors = {
    'presentation': '#E3F2FD',  # 淡蓝色
    'business': '#E8F5E8',      # 淡绿色
    'core': '#FFF3E0',          # 淡橙色
    'data': '#F3E5F5',          # 淡紫色
    'border': '#2C3E50',        # 深灰色边框
    'text': '#2C3E50'           # 深蓝灰色文字
}

# 层级高度和间距 - 增加高度以容纳更多文字
layer_height = 2.2
layer_spacing = 0.4
component_width = 3.8
component_height = 1.4
component_spacing = 0.5

# 总宽度
total_width = 13
start_x = 1

# 绘制四个主要层级
# 调整层级Y位置以适应新的高度
layers = [
    {
        'name': '表现层 (Presentation)',
        'color': colors['presentation'],
        'y': 8.5,
        'components': [
            {'name': 'WPF MVVM\n现代化界面', 'desc': ''},
            {'name': 'WinForms\n传统对话框', 'desc': ''},
            {'name': 'Ribbon UI\n工具栏集成', 'desc': ''}
        ]
    },
    {
        'name': '业务逻辑层 (Business)',
        'color': colors['business'],
        'y': 6.0,
        'components': [
            {'name': '路径规划引擎\nA*算法集成', 'desc': ''},
            {'name': '碰撞检测器\n实时冲突检测', 'desc': ''},
            {'name': '动画管理器\nTimeLiner集成', 'desc': ''}
        ]
    },
    {
        'name': '核心服务层 (Core)',
        'color': colors['core'],
        'y': 3.5,
        'components': [
            {'name': '状态管理器\nUI线程安全', 'desc': ''},
            {'name': '事件总线\n组件通信', 'desc': ''},
            {'name': '日志服务\n异常处理', 'desc': ''}
        ]
    },
    {
        'name': '数据访问层 (Data)',
        'color': colors['data'],
        'y': 1.0,
        'components': [
            {'name': 'JSON序列化\n路径数据', 'desc': ''},
            {'name': 'XML导出\n配置管理', 'desc': ''},
            {'name': 'Navisworks API\nCOM API集成', 'desc': ''}
        ]
    }
]

# 绘制每个层级
for layer in layers:
    # 绘制层级背景
    layer_rect = FancyBboxPatch(
        (start_x, layer['y']), total_width, layer_height,
        boxstyle="round,pad=0.1",
        facecolor=layer['color'],
        edgecolor=colors['border'],
        linewidth=2
    )
    ax.add_patch(layer_rect)
    
    # 绘制层级标题 - 调整位置确保文字在框内正确显示
    ax.text(start_x + total_width/2, layer['y'] + layer_height - 0.4,
            layer['name'],
            ha='center', va='center',
            fontsize=15, fontweight='bold',
            color=colors['text'])
    
    # 计算组件起始位置
    total_components_width = len(layer['components']) * component_width + (len(layer['components']) - 1) * component_spacing
    components_start_x = start_x + (total_width - total_components_width) / 2
    
    # 绘制组件
    for i, component in enumerate(layer['components']):
        comp_x = components_start_x + i * (component_width + component_spacing)
        comp_y = layer['y'] + 0.2
        
        # 绘制组件框
        comp_rect = FancyBboxPatch(
            (comp_x, comp_y), component_width, component_height,
            boxstyle="round,pad=0.05",
            facecolor='white',
            edgecolor=colors['border'],
            linewidth=1.5
        )
        ax.add_patch(comp_rect)
        
        # 绘制组件文字 - 调整字体大小和位置
        ax.text(comp_x + component_width/2, comp_y + component_height/2,
                component['name'],
                ha='center', va='center',
                fontsize=11, fontweight='normal',
                color=colors['text'], 
                linespacing=1.2)

# 绘制层级之间的连接线
for i in range(len(layers) - 1):
    y_start = layers[i]['y']
    y_end = layers[i+1]['y'] + layer_height
    
    # 绘制多条连接线表示数据流
    for j in range(3):
        x_pos = start_x + total_width * (j + 1) / 4
        ax.annotate('', xy=(x_pos, y_start), xytext=(x_pos, y_end),
                   arrowprops=dict(arrowstyle='->', color=colors['border'], 
                                 lw=1.5, alpha=0.7))

# 添加架构说明 - 调整位置和字体
ax.text(start_x + total_width + 0.5, 6.5,
        '特点:\n• 分层解耦\n• 职责清晰\n• 易于维护\n• 支持扩展',
        ha='left', va='center',
        fontsize=12, fontweight='normal',
        bbox=dict(boxstyle="round,pad=0.5", facecolor='#F8F9FA', edgecolor=colors['border']),
        color=colors['text'],
        linespacing=1.3)

# 设置图形属性 - 调整范围以适应新的布局
ax.set_xlim(0, 17)
ax.set_ylim(0, 12)
ax.set_aspect('equal')
ax.axis('off')

# 添加标题
plt.title('NavisworksTransport 分层架构设计', 
         fontsize=18, fontweight='bold', pad=20, color=colors['text'])

# 保存图形
plt.tight_layout()
plt.savefig(r'C:\Users\Tellme\apps\NavisworksTransport\doc\architecture\system_architecture.png', 
            dpi=300, bbox_inches='tight', facecolor='white', edgecolor='none')

print("架构图已生成: system_architecture.png")
plt.show()