<% @page_title = '升级管理' %>
<% @active_page = 'upgrade' %>

<div id="app">
  <div class="page-header">
    <h1>升级管理</h1>
  </div>

  <el-row :gutter="20">
    <el-col :span="12">
      <el-card class="card">
        <template #header>
          <h3 style="margin: 0; font-size: 16px; font-weight: 600;">上传升级包</h3>
        </template>

        <div class="upload-section" @click="triggerUpload">
          <div class="upload-icon">+</div>
          <p style="color: #606266;">点击上传升级包（ZIP格式）</p>
          <p style="color: #909399; font-size: 12px; margin-top: 8px;">
            使用 update.rb 工具制作的升级包，上传后自动部署
          </p>
          <input type="file" ref="fileInput" @change="handleFileChange" accept=".zip" style="display: none;">
        </div>

        <div v-if="uploading" class="file-info">
          <p><strong>上传中...</strong></p>
        </div>

        <div v-if="deployed" class="file-info">
          <p><strong>文件名：</strong>{{ deployedFileName }}</p>
          <p style="margin-top: 8px;">
            <el-tag :type="deploySuccess ? 'success' : 'danger'">
              {{ deploySuccess ? '部署成功' : '部署失败' }}
            </el-tag>
            <el-button size="small" @click="resetUpload" style="margin-left: 8px;">继续上传</el-button>
          </p>
        </div>
      </el-card>
    </el-col>

    <el-col :span="12">
      <el-card class="card">
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0; font-size: 16px; font-weight: 600;">升级记录</h3>
            <el-button size="small" @click="fetchRecords">刷新</el-button>
          </div>
        </template>

        <div v-if="records.length === 0" style="text-align: center; padding: 40px; color: #909399;">
          暂无升级记录
        </div>

        <div v-else style="max-height: 400px; overflow-y: auto;">
          <div v-for="record in records" :key="record.id"
               class="record-item"
               :class="getRecordClass(record.status)">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <div>
                <strong>{{ record.package_name }}</strong>
                <span style="margin-left: 8px; color: #909399; font-size: 12px;">
                  v{{ record.package_version }}
                </span>
              </div>
              <el-tag :type="getStatusType(record.status)" size="small">
                {{ record.status_text }}
              </el-tag>
            </div>
            <div v-if="record.deployment_result" style="margin-top: 8px; font-size: 13px; color: #606266;">
              {{ record.deployment_result.message }}
            </div>
            <div style="margin-top: 8px; font-size: 12px; color: #909399;">
              {{ formatTime(record.created_at) }}
            </div>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
</div>

<% content_for :xxx do %>
<style>
  .upload-section {
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    padding: 40px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    margin-bottom: 24px;
  }
  .upload-section:hover {
    border-color: #409eff;
    background: #f5f7fa;
  }
  .upload-icon {
    font-size: 48px;
    color: #909399;
    margin-bottom: 16px;
  }
  .file-info {
    background: #f5f7fa;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
  }
  .deploy-btn {
    width: 100%;
    padding: 12px;
    font-size: 16px;
  }
  .record-item {
    background: white;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }
  .record-success { border-left: 4px solid #67c23a; }
  .record-failed { border-left: 4px solid #f56c6c; }
  .record-partial { border-left: 4px solid #e6a23c; }
  .record-deploying { border-left: 4px solid #409eff; }
</style>
<script>
  const { createApp, ref, reactive, onMounted } = Vue;
  const ElementPlus = window.ElementPlus;

  const app = createApp({
    setup() {
      const fileInput = ref(null);
      const uploading = ref(false);
      const deployed = ref(false);
      const deploySuccess = ref(false);
      const deployedFileName = ref('');
      const records = ref([]);

      const triggerUpload = () => {
        fileInput.value.click();
      };

      const handleFileChange = async (event) => {
        const file = event.target.files[0];
        if (!file) return;

        uploading.value = true;
        deployed.value = false;

        const formData = new FormData();
        formData.append('file', file);

        try {
          // 1. 上传文件
          const uploadResponse = await fetch('/api/v1/upgrade-packages/upload', {
            method: 'POST',
            body: formData
          });

          const uploadResult = await uploadResponse.json();

          if (!uploadResult.success) {
            ElementPlus.ElMessage.error(uploadResult.error || '上传失败');
            uploading.value = false;
            return;
          }

          deployedFileName.value = uploadResult.filename;

          // 2. 直接部署
          const deployResponse = await fetch('/api/v1/upgrade-packages/deploy', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ temp_path: uploadResult.temp_path })
          });

          const deployResult = await deployResponse.json();

          deploySuccess.value = deployResult.success;
          deployed.value = true;

          if (deployResult.success) {
            ElementPlus.ElMessage.success('部署成功');
            fetchRecords();
          } else {
            ElementPlus.ElMessage.error(deployResult.error || '部署失败');
          }
        } catch (e) {
          ElementPlus.ElMessage.error('网络错误');
        } finally {
          uploading.value = false;
          if (fileInput.value) {
            fileInput.value.value = '';
          }
        }
      };

      const resetUpload = () => {
        deployed.value = false;
        deployedFileName.value = '';
        deploySuccess.value = false;
      };

      const fetchRecords = async () => {
        try {
          const response = await fetch('/api/v1/upgrade-records');
          records.value = await response.json();
        } catch (e) {
          console.error('获取记录失败', e);
        }
      };

      const getRecordClass = (status) => {
        const map = {
          'success': 'record-success',
          'failed': 'record-failed',
          'partial': 'record-partial',
          'deploying': 'record-deploying'
        };
        return map[status] || '';
      };

      const getStatusType = (status) => {
        const map = {
          'success': 'success',
          'failed': 'danger',
          'partial': 'warning',
          'deploying': 'primary',
          'pending': 'info'
        };
        return map[status] || 'info';
      };

      const formatTime = (timestamp) => {
        if (!timestamp) return '';
        return new Date(timestamp).toLocaleString('zh-CN');
      };

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

      return {
        fileInput, uploading, deployed, deploySuccess, deployedFileName, records,
        triggerUpload, handleFileChange, resetUpload,
        fetchRecords, getRecordClass, getStatusType, formatTime
      };
    }
  });

  app.use(ElementPlus);
  app.mount('#app');
</script>
<% end %>
