<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>软件升级</h2>
      <div class="header-actions">
        <el-button @click="apiDocVisible = true">
          <el-icon><Document /></el-icon>
          接口说明
        </el-button>
        <el-button type="primary" @click="editRef.open()">
          <el-icon><Plus /></el-icon>
          新增产品
        </el-button>
        <el-button @click="fetchList" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider />

    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="关键词">
        <el-input
          v-model="searchForm.keyword"
          placeholder="名称 / 产品标识"
          clearable
          style="width: 220px"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" v-loading="loading" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="72" align="center" />
      <el-table-column prop="name" label="软件名称" min-width="140" />
      <el-table-column prop="code" label="产品code" width="140" />
      <el-table-column prop="latestVersion" label="最新版本" width="100" align="center" />
      <el-table-column label="文件 ID" width="88" align="center">
        <template #default="{ row }">{{ row.fileId ?? "—" }}</template>
      </el-table-column>
      <el-table-column label="解析下载地址" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <el-link v-if="row.resolvedDownloadUrl" :href="row.resolvedDownloadUrl" type="primary" target="_blank">
            {{ row.resolvedDownloadUrl }}
          </el-link>
          <span v-else class="muted">—</span>
        </template>
      </el-table-column>
      <el-table-column prop="forceUpdate" label="强制更新" width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.forceUpdate ? 'danger' : 'info'">{{ row.forceUpdate ? "是" : "否" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? "启用" : "停用" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="72" align="center" />
      <el-table-column label="操作" width="140" align="center" fixed="right">
        <template #default="{ row }">
          <el-button text type="primary" size="small" @click="editRef.open(row.id)">编辑</el-button>
          <el-button text type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div>

    <SoftwareEdit ref="editRef" @saved="fetchList" />

    <el-drawer v-model="apiDocVisible" title="软件升级 — 接口说明" direction="rtl" size="540px">
      <el-scrollbar max-height="calc(100vh - 120px)">
        <div class="api-doc">
          <p class="lead">客户端启动时调用开放接口比对版本；管理端接口需平台管理员 Token。</p>
          <p><strong>API 根地址</strong></p>
          <pre class="api-pre">{{ apiBase }}</pre>

          <h4>一、客户端检查更新（无需登录）</h4>
          <p><code>GET /api/softwareupgrade/check</code></p>
          <p>Query：</p>
          <ul>
            <li><code>code</code>（必填）：与后台配置的「产品标识」一致</li>
            <li><code>version</code>（可选）：当前客户端版本，缺省按 <code>0.0.0</code></li>
          </ul>
          <p>响应 <code>data</code> 字段说明：</p>
          <ul>
            <li><code>upToDate</code>：是否已是最新（当前版本 ≥ 后台最新版本）</li>
            <li><code>latestVersion</code>：后台配置的最新版本号</li>
            <li><code>downloadUrl</code>：安装包地址（自定义 URL 或由文件 ID 解析）</li>
            <li><code>forceUpdate</code>：是否建议强制更新</li>
            <li><code>releaseNotes</code>：更新说明</li>
          </ul>
          <pre class="api-pre">GET {{ apiBase }}/api/softwareupgrade/check?code=my-app&amp;version=1.0.0</pre>

          <h4>二、版本号规则</h4>
          <p>按 <code>.</code> 分段数字比较（如 <code>1.10.0</code> &gt; <code>1.9.0</code>）。后缀 <code>-beta</code> 等仅截取 <code>-</code> 前参与比较。</p>

          <h4>三、安装包上传</h4>
          <p>在「软件升级」编辑抽屉内点击 <strong>上传安装包</strong>，会调用 <code>POST /platform/uploadfile</code>，并自动归入文件分组 <code>appsupgrade</code>（不存在则自动创建）。保存后会把 <strong>file_id</strong> 与根据 <code>VITE_API_BASE_URL</code> 拼好的 <strong>download_url</strong> 写入数据库。</p>
          <p>静态资源映射：<code>/uploads</code>；生产环境请配置正确的 API 公网地址与反向代理头（<code>X-Forwarded-Proto</code> 等）。</p>

          <h4>四、管理端接口（需 Bearer）</h4>
          <ul>
            <li><code>GET /platform/softwareupgrade/list</code> — <code>page</code>、<code>pageSize</code>、<code>keyword</code></li>
            <li><code>GET /platform/softwareupgrade/:id</code></li>
            <li><code>POST /platform/softwareupgrade</code> — 新增</li>
            <li><code>POST /platform/softwareupgrade/:id</code> — 更新</li>
            <li><code>DELETE /platform/softwareupgrade/:id</code> — 软删</li>
          </ul>
          <p>表：<code>yz_system_software_upgrade</code></p>
        </div>
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh, Document } from "@element-plus/icons-vue";
import { getSoftwareUpgradeList, deleteSoftwareUpgrade } from "@/api/softwareUpgrade";
import SoftwareEdit from "./components/edit.vue";

const editRef = ref(null);
const apiDocVisible = ref(false);
const apiBase = import.meta.env.VITE_API_BASE_URL || "";
const loading = ref(false);
const list = ref([]);

const searchForm = reactive({ keyword: "" });
const pagination = reactive({ page: 1, pageSize: 20, total: 0 });

async function fetchList() {
  loading.value = true;
  try {
    const res = await getSoftwareUpgradeList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
    });
    if (res?.code === 200 && res.data) {
      list.value = res.data.list || [];
      pagination.total = res.data.total ?? 0;
    } else {
      list.value = [];
      ElMessage.error(res?.msg || "加载失败");
    }
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  pagination.page = 1;
  fetchList();
}

function resetSearch() {
  searchForm.keyword = "";
  pagination.page = 1;
  fetchList();
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确定删除「${row.name}」吗？`, "提示", { type: "warning" });
  } catch {
    return;
  }
  const res = await deleteSoftwareUpgrade(row.id);
  if (res?.code === 200) {
    ElMessage.success("已删除");
    fetchList();
  } else {
    ElMessage.error(res?.msg || "删除失败");
  }
}

onMounted(() => {
  fetchList();
});
</script>

<style scoped>
.container-box {
  padding: 16px;
}
.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-actions {
  display: flex;
  gap: 8px;
}
.search-form {
  margin-bottom: 12px;
}
.pager {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.muted {
  color: var(--el-text-color-placeholder);
}
.api-doc {
  padding-right: 12px;
  font-size: 13px;
  line-height: 1.6;
  color: var(--el-text-color-regular);
}
.api-doc h4 {
  margin: 18px 0 8px;
  font-size: 14px;
  color: var(--el-text-color-primary);
}
.api-doc ul {
  margin: 8px 0;
  padding-left: 1.2em;
}
.api-doc code {
  font-size: 12px;
  padding: 0 4px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}
.api-pre {
  margin: 8px 0;
  padding: 10px 12px;
  font-size: 12px;
  line-height: 1.5;
  background: var(--el-fill-color-light);
  border-radius: 6px;
  overflow-x: auto;
  white-space: pre-wrap;
  word-break: break-all;
}
.lead {
  margin: 0 0 12px;
}
</style>
