#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
扫描website目录下的所有数字人，生成静态HTML文件
"""
import os
import re
from pathlib import Path

def scan_and_generate_html():
    """扫描数字人目录并生成静态HTML"""
    website_dir = Path(__file__).parent
    digital_humans = []
    
    # UUID正则表达式
    uuid_pattern = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.IGNORECASE)
    
    print(f"正在扫描目录: {website_dir}")
    
    # 扫描所有UUID格式的目录
    try:
        for item in os.listdir(website_dir):
            item_path = website_dir / item
            
            if item_path.is_dir() and uuid_pattern.match(item):
                index_file = item_path / "index.html"
                image_file = item_path / "image" / "bg.jpg"
                
                if index_file.exists():
                    # 从 index.html 读取标题
                    name = "数字人"
                    try:
                        with open(index_file, 'r', encoding='utf-8') as f:
                            content = f.read()
                            title_match = re.search(r'<title>(.*?)</title>', content)
                            if title_match:
                                name = title_match.group(1)
                    except:
                        pass
                    
                    mtime = item_path.stat().st_mtime
                    
                    digital_humans.append({
                        "id": item,
                        "name": name,
                        "image": f"{item}/image/bg.jpg",
                        "url": f"{item}/index.html",
                        "mtime": mtime
                    })
                    print(f"  找到: {item} - {name}")
        
        # 按时间倒序排序（最新的在前）
        digital_humans.sort(key=lambda x: x['mtime'], reverse=True)
        
        print(f"总共找到 {len(digital_humans)} 个数字人")
        
    except Exception as e:
        print(f"扫描失败: {e}")
        import traceback
        traceback.print_exc()
    
    # 生成HTML内容
    html_cards = ""
    if digital_humans:
        for i, dh in enumerate(digital_humans, 1):
            html_cards += f"""
      <div class="human-card">
        <div class="human-index">{i}</div>
        <div class="human-image-container" onclick="window.location.href='{dh['url']}'">
          <img 
            src="{dh['image']}" 
            alt="{dh['name']}" 
            class="human-image"
            onerror="this.src='https://via.placeholder.com/250x200?text=N/A'; this.alt='暂无头像';"
          >
        </div>
        <div class="human-name">{dh['name']}</div>
        <div class="checkbox-container">
          <input 
            type="checkbox" 
            class="checkbox" 
            value="{dh['id']}" 
            data-url="https://szr.hzforwin.com/{dh['url']}"
            data-name="{dh['name']}"
            id="checkbox-{dh['id']}"
          >
        </div>
        <button class="delete-btn" 
                data-folder="{dh['id']}" 
                data-name="{dh['name']}"
                onclick="deleteHuman(this, event)">
          删除
        </button>
      </div>
"""
    else:
        html_cards = """
      <div class="empty-state">暂无可用的数字人</div>
"""
    
    # 生成完整的HTML文件
    html_content = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数字人列表</title>
  <style>
    * {{
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    }}

    body {{
      background-color: #f5f5f5;
      padding: 20px;
    }}

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

    h1 {{
      text-align: center;
      color: #333;
      margin-bottom: 30px;
      font-size: 28px;
      font-weight: 600;
    }}

    .grid-container {{
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      margin-bottom: 30px;
    }}

    .human-card {{
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      padding: 15px;
      background-color: #fff;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;
    }}

    .human-card:hover {{
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }}

    .human-index {{
      position: absolute;
      top: 10px;
      left: 10px;
      background-color: #1890ff;
      color: white;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 600;
      z-index: 1;
    }}

    .human-image-container {{
      position: relative;
      width: 100%;
      height: 200px;
      margin-bottom: 15px;
      overflow: hidden;
      border-radius: 6px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f0f0f0;
    }}

    .human-image {{
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
      transition: transform 0.3s ease;
    }}

    .human-image-container:hover .human-image {{
      transform: scale(1.05);
    }}

    .human-name {{
      text-align: center;
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 15px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }}

    .checkbox-container {{
      text-align: center;
    }}

    .checkbox {{
      width: 20px;
      height: 20px;
      cursor: pointer;
      accent-color: #1890ff;
    }}

    .submit-container {{
      text-align: center;
      margin-top: 30px;
    }}

    .submit-btn {{
      background-color: #1890ff;
      color: white;
      border: none;
      padding: 12px 40px;
      font-size: 16px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s ease;
      font-weight: 500;
    }}

    .submit-btn:hover {{
      background-color: #40a9ff;
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
    }}

    .submit-btn:disabled {{
      background-color: #d9d9d9;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }}

    .empty-state {{
      grid-column: 1 / -1;
      text-align: center;
      padding: 60px 20px;
      color: #999;
      font-size: 16px;
    }}

    /* 删除按钮样式 */
    .delete-btn {{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(255, 77, 79, 0.95);
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
      z-index: 10;
      box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    }}

    .human-card:hover .delete-btn {{
      opacity: 1;
      visibility: visible;
    }}

    .delete-btn:hover {{
      background-color: #ff3232;
      transform: translate(-50%, -50%) scale(1.05);
    }}

    .delete-btn:disabled {{
      background-color: #ccc;
      cursor: not-allowed;
    }}

    /* 删除动画 */
    @keyframes fadeOut {{
      from {{ opacity: 1; transform: scale(1); }}
      to {{ opacity: 0; transform: scale(0.8); }}
    }}

    .human-card.deleting {{
      animation: fadeOut 0.3s ease forwards;
      pointer-events: none;
    }}

    @media (max-width: 1200px) {{
      .grid-container {{
        grid-template-columns: repeat(3, 1fr);
      }}
    }}

    @media (max-width: 768px) {{
      .container {{
        padding: 20px;
      }}
      
      .grid-container {{
        grid-template-columns: repeat(2, 1fr);
      }}
      
      h1 {{
        font-size: 24px;
      }}
    }}

    @media (max-width: 480px) {{
      body {{
        padding: 10px;
      }}
      
      .container {{
        padding: 15px;
      }}
      
      .grid-container {{
        grid-template-columns: 1fr;
      }}
    }}
  </style>
</head>
<body>
  <div class="container">
    <h1>数字人列表</h1>
    
    <div class="grid-container" id="digitalHumanGrid">
{html_cards}
    </div>

    <div class="submit-container">
      <button id="submitBtn" class="submit-btn" disabled>确定</button>
    </div>
  </div>

  <script>
    // 避免变量重复声明：如果原页面已有submitBtn，这里改用新变量名（如digitalHumanSubmitBtn）
    const digitalHumanSubmitBtn = document.getElementById('submitBtn');
    const checkboxes = document.querySelectorAll('.checkbox');

    // 更新按钮状态函数
    function updateSubmitButton() {{
      const hasChecked = Array.from(checkboxes).some(cb => cb.checked);
      digitalHumanSubmitBtn.disabled = !hasChecked; // 使用新变量名
    }}

    // 监听复选框变化
    checkboxes.forEach(checkbox => {{
      checkbox.addEventListener('change', updateSubmitButton);
    }});

    // 提交选中的数字人并发送消息给父页面
    digitalHumanSubmitBtn.addEventListener('click', function() {{ // 使用新变量名
      const selectedHumans = Array.from(checkboxes)
        .filter(cb => cb.checked)
        .map(cb => ({{
          id: cb.value,
          name: cb.dataset.name,
          url: cb.dataset.url
        }}));
      
      if (selectedHumans.length === 0) return;
      
      // 控制台打印和提示（保留原逻辑）
      console.log('选中的数字人:', selectedHumans);
      alert('已选择 ' + selectedHumans.length + ' 个数字人');
      
      // 发送消息给父页面
      const messageData = {{
        status: "success",
        total: selectedHumans.length,
        digitalHumans: selectedHumans,
        message: `已确认选择 ${{selectedHumans.length}} 个数字人`
      }};
      
      // 注意：生产环境建议将"*"改为父页面实际域名（如"http://your-parent-domain.com"）
      window.parent.postMessage(messageData, "*");
    }});

    // 删除数字人功能
    function deleteHuman(button, event) {{
      event.stopPropagation();
      
      const card = button.closest('.human-card');
      const folderId = button.dataset.folder;
      const humanName = button.dataset.name;
      
      if (!confirm(`确定要删除"${{humanName}}"吗？\\n\\n此操作将删除服务器上的文件夹，无法撤销。`)) {{
        return;
      }}
      
      // 添加删除动画
      card.classList.add('deleting');
      button.disabled = true;
      button.textContent = '删除中...';
      
      // 调用删除API（通过HTTPS代理）
      fetch('https://szr.hzforwin.com/api/delete_human', {{
        method: 'POST',
        headers: {{ 'Content-Type': 'application/json' }},
        body: JSON.stringify({{ folder_id: folderId }})
      }})
      .then(response => response.json())
      .then(data => {{
        if (data.success) {{
          // 延迟移除DOM
          setTimeout(() => {{
            card.remove();
            updateCardIndexes();
            checkEmptyState();
            alert('删除成功！页面将刷新更新列表。');
            location.reload(); // 刷新页面，加载新生成的列表
          }}, 300);
        }} else {{
          card.classList.remove('deleting');
          button.disabled = false;
          button.textContent = '删除';
          alert('删除失败：' + data.message);
        }}
      }})
      .catch(error => {{
        card.classList.remove('deleting');
        button.disabled = false;
        button.textContent = '删除';
        console.error('删除出错:', error);
        alert('删除失败，请检查网络连接或查看控制台');
      }});
    }}

    // 更新卡片序号
    function updateCardIndexes() {{
      const cards = document.querySelectorAll('.human-card');
      cards.forEach((card, index) => {{
        const indexEl = card.querySelector('.human-index');
        if (indexEl) indexEl.textContent = index + 1;
      }});
    }}

    // 检查空状态
    function checkEmptyState() {{
      const grid = document.getElementById('digitalHumanGrid');
      const cards = grid.querySelectorAll('.human-card');
      
      if (cards.length === 0) {{
        grid.innerHTML = '<div class="empty-state">暂无数字人数据</div>';
      }}
    }}
  </script>
</body>
</html>"""
    
    # 写入文件
    output_file = website_dir / "digital_human_list.html"
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    print(f"\n已生成静态HTML文件: {output_file}")
    print(f"包含 {len(digital_humans)} 个数字人")

if __name__ == "__main__":
    scan_and_generate_html()

