admin-characters.html 17 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>人物库管理</title>
<link rel="stylesheet" href="style.css" />
<style>
  .admin-wrap { padding: 18px 24px; max-width: 1400px; }
  .admin-toolbar { display: flex; gap: 10px; align-items: center; margin-bottom: 14px; flex-wrap: wrap; }
  .admin-toolbar input[type="search"] { flex: 1; min-width: 220px; }
  table.admin-table { width: 100%; border-collapse: collapse; font-size: 13px; background: #fff; }
  table.admin-table th, table.admin-table td { border-bottom: 1px solid var(--border); padding: 8px 10px; text-align: left; vertical-align: top; }
  table.admin-table th { color: var(--muted); font-weight: 600; white-space: nowrap; }
  table.admin-table td.name { max-width: 160px; }
  table.admin-table td.desc { max-width: 320px; color: var(--muted); }
  table.admin-table td input, table.admin-table td textarea { width: 100%; font-size: 12px; }
  table.admin-table td textarea { min-height: 50px; }
  .row-actions { display: flex; gap: 6px; white-space: nowrap; }
  .row-actions button { padding: 3px 8px; font-size: 12px; }
  .thumb { width: 56px; height: 80px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border); cursor: pointer; }
  .add-card { margin-bottom: 16px; }
  .row-4 { display: grid; grid-template-columns: 1fr 1fr 1.6fr 100px; gap: 14px; align-items: start; }
  .count-hint { color: var(--muted); font-size: 12px; margin-bottom: 10px; }
  .default-badge { display: inline-block; padding: 2px 6px; font-size: 11px; border-radius: 4px; background: #eef7ee; color: #2e7d32; }
  .gallery-btn { padding: 3px 8px; font-size: 12px; }

  .gallery-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 100; padding: 24px; }
  .gallery-overlay[hidden] { display: none; }
  .gallery-modal { background: #fff; border-radius: 8px; max-width: 960px; width: 100%; max-height: 90vh; overflow-y: auto; padding: 20px 24px; }
  .gallery-modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; }
  .gallery-modal-head h2 { font-size: 16px; margin: 0; }
  .gallery-modal-sub { color: var(--muted); font-size: 12px; margin-bottom: 14px; }
  .gallery-close { border: none; background: none; font-size: 20px; cursor: pointer; line-height: 1; color: var(--muted); }
  .gallery-add-row { display: flex; gap: 10px; align-items: center; margin-bottom: 16px; flex-wrap: wrap; }
  .gallery-add-row input[type="text"] { flex: 1; min-width: 160px; }
  .gallery-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 14px; }
  .gallery-card { border: 1px solid var(--border); border-radius: 6px; padding: 8px; position: relative; }
  .gallery-card img { width: 100%; height: 190px; object-fit: cover; border-radius: 4px; display: block; margin-bottom: 6px; background: #f2f2f2; }
  .gallery-card input[type="text"] { width: 100%; font-size: 12px; margin-bottom: 6px; }
  .gallery-card-actions { display: flex; gap: 6px; }
  .gallery-card-actions button { flex: 1; padding: 3px 6px; font-size: 11px; }
  .cover-badge { position: absolute; top: 12px; left: 12px; background: #2e7d32; color: #fff; font-size: 11px; padding: 2px 6px; border-radius: 4px; }
</style>
</head>
<body>
<header class="topbar">
  <h1>人物库管理</h1>
  <div class="spacer"></div>
  <a href="admin.html">视频库</a>
  <a href="admin-garments.html">衣服库</a>
  <a href="admin-dance-refs.html">参考跳舞视频库</a>
  <a href="admin-batch-gen.html">批量生成</a>
  <a href="admin-dressgenlist.html">人衣图生成</a>
  <a href="admin-dance-library.html">跳舞直播间片库</a>
  <a href="admin-dance-qc.html">质检</a>
  <a href="live.html">← 返回直播频道</a>
</header>

<main class="admin-wrap">
  <div class="card add-card">
    <div class="field"><label>新增人物</label></div>
    <div class="row-4">
      <input type="text" id="newName" placeholder="名称" />
      <input type="file" id="newImageFile" accept="image/*" />
      <input type="text" id="newTags" placeholder="标签(逗号分隔,可选)" />
      <label style="display:flex;align-items:center;gap:6px;font-size:12px;">
        <input type="checkbox" id="newIsDefault" /> 设为默认
      </label>
    </div>
    <div class="field" style="margin-top:8px;">
      <textarea id="newAppearanceDescriptor" placeholder="人物外观特征(发色/发型/五官/体态,2-3 条具体描述,如:shoulder-length wavy black hair, delicate features, a slender build)" style="min-height:60px;"></textarea>
    </div>
    <button id="addBtn" style="margin-top:8px;">新增</button>
    <div id="addError" class="error-box" hidden></div>
  </div>

  <div class="admin-toolbar">
    <input type="search" id="searchInput" placeholder="搜索名称 / 标签..." />
  </div>
  <div class="count-hint" id="countHint"></div>

  <div style="overflow-x:auto;">
    <table class="admin-table">
      <thead>
        <tr>
          <th>图片</th>
          <th>名称</th>
          <th>外观描述</th>
          <th>标签</th>
          <th>默认</th>
          <th>来源</th>
          <th>状态</th>
          <th>片段配额</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="tbody"></tbody>
    </table>
  </div>
</main>

<div class="gallery-overlay" id="galleryOverlay" hidden>
  <div class="gallery-modal">
    <div class="gallery-modal-head">
      <h2 id="galleryTitle"></h2>
      <button class="gallery-close" id="galleryCloseBtn">×</button>
    </div>
    <div class="gallery-modal-sub" id="galleryCountHint"></div>
    <div class="gallery-add-row">
      <input type="file" id="galleryNewFile" accept="image/*" />
      <input type="text" id="galleryNewLabel" placeholder="角度/说明(如:正面、侧面45°,可选)" />
      <button id="galleryAddBtn">新增图片</button>
    </div>
    <div id="galleryError" class="error-box" hidden></div>
    <div class="gallery-grid" id="galleryGrid"></div>
  </div>
</div>

<script>
const _fetch = window.fetch;
window.fetch = async (...args) => {
  const res = await _fetch(...args);
  if (res.status === 401 && String(args[0]).startsWith("/api/admin/") && !String(args[0]).includes("/login")) {
    location.href = "/admin-login.html?next=" + encodeURIComponent(location.pathname);
  }
  return res;
};

let items = [];
let editingId = null;
let characterImages = [];
let galleryCharacterId = null;

function escapeHtml(s) {
  const div = document.createElement("div");
  div.textContent = s || "";
  return div.innerHTML;
}

// T31: totalSegments/remainingSegments are only ever non-null for
// source:"user_paid" characters (mode 3, T35) — admin_seed characters like
// the default one stay null forever (unlimited plays, not a purchased quota).
function segmentsLabel(c) {
  if (c.totalSegments == null) return "-";
  return `${c.remainingSegments ?? 0}/${c.totalSegments}`;
}

async function uploadImage(file) {
  const fd = new FormData();
  fd.append("file", file);
  const res = await fetch("/api/admin/upload", { method: "POST", body: fd });
  if (!res.ok) throw new Error((await res.json()).error || "上传失败");
  return (await res.json()).url;
}

async function load() {
  const [charsRes, imagesRes] = await Promise.all([fetch("/api/admin/characters"), fetch("/api/admin/character-images")]);
  items = await charsRes.json();
  characterImages = await imagesRes.json();
  render();
  if (galleryCharacterId) renderGallery();
}

function imagesFor(characterId) {
  return characterImages.filter((img) => img.characterId === characterId);
}

function filtered() {
  const q = document.getElementById("searchInput").value.trim().toLowerCase();
  if (!q) return items;
  return items.filter((c) => c.name.toLowerCase().includes(q) || (c.tags || []).join(",").toLowerCase().includes(q));
}

function render() {
  const rows = filtered();
  document.getElementById("countHint").textContent = `共 ${items.length} 条,当前筛选 ${rows.length} 条`;

  const tbody = document.getElementById("tbody");
  tbody.innerHTML = rows
    .map((c) => {
      const imgCount = imagesFor(c.id).length;
      if (c.id === editingId) {
        return `
        <tr data-id="${c.id}">
          <td><img class="thumb" data-gallery="${c.id}" src="${escapeHtml(c.imageUrl)}" /></td>
          <td class="name"><input data-field="name" value="${escapeHtml(c.name)}" /></td>
          <td class="desc"><textarea data-field="appearanceDescriptor">${escapeHtml(c.appearanceDescriptor || "")}</textarea></td>
          <td class="name"><input data-field="tags" value="${escapeHtml((c.tags || []).join(","))}" /></td>
          <td><input type="checkbox" data-field="isDefault" ${c.isDefault ? "checked" : ""} /></td>
          <td>${c.source}</td>
          <td>${c.status}</td>
          <td>${segmentsLabel(c)}</td>
          <td>${new Date(c.createdAt).toLocaleDateString()}</td>
          <td class="row-actions">
            <button data-save="${c.id}">保存</button>
            <button class="secondary" data-cancel="1">取消</button>
          </td>
        </tr>`;
      }
      return `
        <tr data-id="${c.id}">
          <td><img class="thumb" data-gallery="${c.id}" src="${escapeHtml(c.imageUrl)}" /></td>
          <td class="name">${escapeHtml(c.name)}</td>
          <td class="desc" title="${escapeHtml(c.appearanceDescriptor || "")}">${escapeHtml(c.appearanceDescriptor || "")}</td>
          <td class="name">${escapeHtml((c.tags || []).join(", "))}</td>
          <td>${c.isDefault ? '<span class="default-badge">默认</span>' : ""}</td>
          <td>${c.source}</td>
          <td>${c.status}</td>
          <td>${segmentsLabel(c)}</td>
          <td>${new Date(c.createdAt).toLocaleDateString()}</td>
          <td class="row-actions">
            <button class="gallery-btn" data-gallery="${c.id}">图片(${imgCount})</button>
            <button class="secondary" data-edit="${c.id}">编辑</button>
            <button class="danger" data-del="${c.id}">删除</button>
          </td>
        </tr>`;
    })
    .join("");

  tbody.querySelectorAll("[data-gallery]").forEach((b) => b.addEventListener("click", () => openGallery(b.dataset.gallery)));
  tbody.querySelectorAll("[data-edit]").forEach((b) => b.addEventListener("click", () => { editingId = b.dataset.edit; render(); }));
  tbody.querySelectorAll("[data-cancel]").forEach((b) => b.addEventListener("click", () => { editingId = null; render(); }));
  tbody.querySelectorAll("[data-save]").forEach((b) =>
    b.addEventListener("click", async () => {
      const tr = b.closest("tr");
      const body = {};
      tr.querySelectorAll("[data-field]").forEach((el) => {
        if (el.type === "checkbox") body[el.dataset.field] = el.checked;
        else if (el.dataset.field === "tags") body.tags = el.value.split(",").map((s) => s.trim()).filter(Boolean);
        else body[el.dataset.field] = el.value;
      });
      const res = await fetch(`/api/admin/characters/${b.dataset.save}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (res.ok) {
        editingId = null;
        await load();
      }
    })
  );
  tbody.querySelectorAll("[data-del]").forEach((b) =>
    b.addEventListener("click", async () => {
      if (!confirm("确认删除这个人物?")) return;
      const res = await fetch(`/api/admin/characters/${b.dataset.del}`, { method: "DELETE" });
      if (res.ok) await load();
    })
  );
}

function openGallery(characterId) {
  galleryCharacterId = characterId;
  document.getElementById("galleryOverlay").hidden = false;
  document.getElementById("galleryNewFile").value = "";
  document.getElementById("galleryNewLabel").value = "";
  document.getElementById("galleryError").hidden = true;
  renderGallery();
}

function closeGallery() {
  galleryCharacterId = null;
  document.getElementById("galleryOverlay").hidden = true;
}

function renderGallery() {
  const character = items.find((c) => c.id === galleryCharacterId);
  if (!character) { closeGallery(); return; }
  const images = imagesFor(galleryCharacterId);
  document.getElementById("galleryTitle").textContent = `${character.name} · 人物图片`;
  document.getElementById("galleryCountHint").textContent = `共 ${images.length} 张,点“设为封面”切换用于生成的主图`;

  const grid = document.getElementById("galleryGrid");
  grid.innerHTML = images
    .map(
      (img) => `
      <div class="gallery-card" data-img-id="${img.id}">
        ${img.isCover ? '<span class="cover-badge">封面</span>' : ""}
        <img src="${escapeHtml(img.imageUrl)}" />
        <input type="text" data-label="${img.id}" value="${escapeHtml(img.angleLabel || "")}" placeholder="角度/说明" />
        <div class="gallery-card-actions">
          <button data-save-label="${img.id}">保存说明</button>
          ${img.isCover ? "" : `<button data-set-cover="${img.id}">设为封面</button>`}
          <button class="danger" data-del-img="${img.id}">删除</button>
        </div>
      </div>`
    )
    .join("");

  grid.querySelectorAll("[data-save-label]").forEach((b) =>
    b.addEventListener("click", async () => {
      const id = b.dataset.saveLabel;
      const angleLabel = grid.querySelector(`[data-label="${id}"]`).value;
      await fetch(`/api/admin/character-images/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ angleLabel }),
      });
      await load();
    })
  );
  grid.querySelectorAll("[data-set-cover]").forEach((b) =>
    b.addEventListener("click", async () => {
      await fetch(`/api/admin/character-images/${b.dataset.setCover}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isCover: true }),
      });
      await load();
    })
  );
  grid.querySelectorAll("[data-del-img]").forEach((b) =>
    b.addEventListener("click", async () => {
      if (images.length <= 1) {
        alert("至少要保留一张图片,无法删除最后一张");
        return;
      }
      if (!confirm("确认删除这张图片?")) return;
      await fetch(`/api/admin/character-images/${b.dataset.delImg}`, { method: "DELETE" });
      await load();
    })
  );
}

document.getElementById("galleryCloseBtn").addEventListener("click", closeGallery);
document.getElementById("galleryOverlay").addEventListener("click", (e) => {
  if (e.target.id === "galleryOverlay") closeGallery();
});

document.getElementById("galleryAddBtn").addEventListener("click", async () => {
  const errorBox = document.getElementById("galleryError");
  errorBox.hidden = true;
  const file = document.getElementById("galleryNewFile").files[0];
  const angleLabel = document.getElementById("galleryNewLabel").value.trim();
  if (!file) {
    errorBox.hidden = false;
    errorBox.textContent = "请选择图片文件";
    return;
  }
  try {
    const imageUrl = await uploadImage(file);
    const res = await fetch("/api/admin/character-images", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ characterId: galleryCharacterId, imageUrl, angleLabel }),
    });
    if (res.ok) {
      document.getElementById("galleryNewFile").value = "";
      document.getElementById("galleryNewLabel").value = "";
      await load();
    } else {
      errorBox.hidden = false;
      errorBox.textContent = (await res.json()).error || "新增失败";
    }
  } catch (e) {
    errorBox.hidden = false;
    errorBox.textContent = e.message;
  }
});

document.getElementById("searchInput").addEventListener("input", render);

document.getElementById("addBtn").addEventListener("click", async () => {
  const errorBox = document.getElementById("addError");
  errorBox.hidden = true;
  const name = document.getElementById("newName").value.trim();
  const file = document.getElementById("newImageFile").files[0];
  const appearanceDescriptor = document.getElementById("newAppearanceDescriptor").value.trim();
  const tags = document.getElementById("newTags").value.split(",").map((s) => s.trim()).filter(Boolean);
  const isDefault = document.getElementById("newIsDefault").checked;
  if (!name || !file || !appearanceDescriptor) {
    errorBox.hidden = false;
    errorBox.textContent = "名称、图片、外观描述都必填";
    return;
  }
  try {
    const imageUrl = await uploadImage(file);
    const res = await fetch("/api/admin/characters", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, imageUrl, appearanceDescriptor, tags, isDefault }),
    });
    if (res.ok) {
      document.getElementById("newName").value = "";
      document.getElementById("newImageFile").value = "";
      document.getElementById("newTags").value = "";
      document.getElementById("newAppearanceDescriptor").value = "";
      document.getElementById("newIsDefault").checked = false;
      await load();
    } else {
      errorBox.hidden = false;
      errorBox.textContent = (await res.json()).error || "新增失败";
    }
  } catch (e) {
    errorBox.hidden = false;
    errorBox.textContent = e.message;
  }
});

load();
</script>
</body>
</html>