<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>升级包制作工具</title>
  <link rel="stylesheet" href="https://unpkg.com/element-plus@2.3.14/dist/index.css">
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      padding: 40px 20px;
    }
    .container {
      max-width: 1100px;
      margin: 0 auto;
    }
    .card {
      background: white;
      border-radius: 16px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.2);
      overflow: hidden;
    }
    .header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 30px;
      text-align: center;
    }
    .header h1 { font-size: 28px; margin-bottom: 8px; }
    .header p { opacity: 0.9; font-size: 14px; }
    .body { padding: 30px; }
    .form-row {
      display: flex;
      gap: 16px;
      margin-bottom: 24px;
    }
    .form-row .el-input { flex: 1; }
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 12px;
    }
    .file-icon { color: #409eff; }
    .folder-icon { color: #e6a23c; }
    .btn-create {
      width: 100%;
      padding: 16px;
      font-size: 18px;
      margin-top: 24px;
    }
    .selected-count {
      color: #909399;
      font-size: 13px;
      margin-bottom: 12px;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="container">
      <div class="card">
        <div class="header">
          <h1>升级包制作工具</h1>
          <p>选择项目文件，配置目标路径，一键打包下载</p>
        </div>
        <div class="body">
          <div class="form-row">
            <el-input v-model="form.name" placeholder="升级包名称，如: 固件升级包"></el-input>
            <el-input v-model="form.version" placeholder="版本号，如: 1.0.0" style="width: 150px;"></el-input>
          </div>

          <div style="display: flex; gap: 24px;">
            <!-- 左侧：可选择文件列表 -->
            <div style="flex: 1;">
              <div class="section-title">可选文件/目录</div>
              <el-table :data="directoryEntries" border stripe v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column prop="name" label="名称" min-width="150">
                  <template #default="scope">
                    <span :class="scope.row.type === 'directory' ? 'folder-icon' : 'file-icon'">
                      {{ scope.row.type === 'directory' ? '📁' : '📄' }}
                    </span>
                    {{ scope.row.name }}
                  </template>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="80">
                  <template #default="scope">
                    {{ scope.row.type === 'directory' ? '目录' : '文件' }}
                  </template>
                </el-table-column>
                <el-table-column prop="size" label="大小" width="100">
                  <template #default="scope">
                    {{ scope.row.type === 'directory' ? '-' : formatSize(scope.row.size) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 右侧：已选文件列表 -->
            <div style="flex: 1;">
              <div class="section-title">已选择 ({{ selectedFiles.length }} 项)</div>
              <div v-if="selectedFiles.length === 0" style="color: #909399; text-align: center; padding: 40px;">
                请从左侧列表中选择文件或目录
              </div>
              <el-table v-else :data="selectedFiles" border stripe>
                <el-table-column prop="name" label="名称" width="120">
                  <template #default="scope">
                    <span :class="scope.row.type === 'directory' ? 'folder-icon' : 'file-icon'">
                      {{ scope.row.type === 'directory' ? '📁' : '📄' }}
                    </span>
                    {{ scope.row.name }}
                  </template>
                </el-table-column>
                <el-table-column label="目标路径" min-width="180">
                  <template #default="scope">
                    <code>{{ scope.row.target }}</code>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60" align="center">
                  <template #default="scope">
                    <el-button type="danger" size="small" link @click="removeFile(scope.$index)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <el-button type="primary" class="btn-create" :loading="creating" :disabled="selectedFiles.length === 0" @click="createPackage">
            {{ creating ? '创建中...' : '创建并下载升级包' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>

  <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
  <script src="https://unpkg.com/element-plus@2.3.14/dist/index.full.js"></script>
  <script>
    const { createApp, ref, reactive, onMounted } = Vue;
    const ElementPlus = window.ElementPlus;

    const app = createApp({
      setup() {
        const form = reactive({
          name: '升级包',
          version: '1.0.0'
        });
        const directoryEntries = ref([]);
        const selectedFiles = ref([]);
        const loading = ref(false);
        const creating = ref(false);

        // 加载根目录内容
        const loadDirectory = async () => {
          loading.value = true;
          try {
            const response = await fetch('/api/root-directory');
            directoryEntries.value = await response.json();
          } catch (e) {
            ElementPlus.ElMessage.error('加载目录失败');
          } finally {
            loading.value = false;
          }
        };

        // 格式化文件大小
        const formatSize = (bytes) => {
          if (bytes === 0) return '0 B';
          const k = 1024;
          const sizes = ['B', 'KB', 'MB', 'GB'];
          const i = Math.floor(Math.log(bytes) / Math.log(k));
          return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        };

        // 选择变化时
        const handleSelectionChange = (selection) => {
          // 清空已选列表，重新添加
          const newSelected = [];
          selection.forEach(item => {
            newSelected.push({
              name: item.name,
              path: item.name,
              type: item.type,
              target: `/app/code/${item.name}`
            });
          });
          selectedFiles.value = newSelected;
        };

        // 移除文件
        const removeFile = (index) => {
          selectedFiles.value.splice(index, 1);
        };

        // 创建升级包
        const createPackage = async () => {
          if (selectedFiles.value.length === 0) {
            ElementPlus.ElMessage.error('请至少选择一个文件或目录');
            return;
          }

          creating.value = true;
          try {
            const files = selectedFiles.value.map(f => ({
              source_path: f.path,
              source: f.path,
              target: f.target,
              description: f.type === 'directory' ? '目录' : '文件'
            }));

            const response = await fetch('/api/create', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                name: form.name,
                version: form.version,
                files: files
              })
            });

            const result = await response.json();

            if (result.success) {
              ElementPlus.ElMessage.success('升级包创建成功，开始下载');
              window.location.href = result.download_url;
            } else {
              ElementPlus.ElMessage.error(result.error || '创建失败');
            }
          } catch (e) {
            ElementPlus.ElMessage.error('网络错误');
          } finally {
            creating.value = false;
          }
        };

        onMounted(() => {
          loadDirectory();
        });

        return {
          form,
          directoryEntries,
          selectedFiles,
          loading,
          creating,
          formatSize,
          handleSelectionChange,
          removeFile,
          createPackage
        };
      }
    });

    app.use(ElementPlus);
    app.mount('#app');
  </script>
</body>
</html>