// ---------- Standard Attachment Downloader ----------
const STD_DL_STATE = { q: "", rows: [], total: 0, limit: 100, offset: 0 };

PAGES.standardDownloads = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `
    <div class="card p-4">
      <div class="flex gap-2 items-center">
        <input id="std-dl-q" placeholder="搜索标题/标准号" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-72"/>
        <button class="btn-primary" onclick="loadStandardDownloads()">搜索</button>
        <button class="btn-outline" onclick="document.getElementById('std-dl-q').value=''; loadStandardDownloads()">清空</button>
      </div>
    </div>
    <div class="card">
      <div class="px-5 py-3 border-b border-slate-100 flex justify-between items-center">
        <div class="font-semibold text-slate-900">未下载附件的标准</div>
        <div id="std-dl-count" class="text-xs text-slate-500"></div>
      </div>
      <div id="std-dl-table" class="overflow-x-auto"></div>
    </div>`;
  document.getElementById("std-dl-q").value = STD_DL_STATE.q || "";
  await loadStandardDownloads();
};

async function loadStandardDownloads() {
  STD_DL_STATE.q = document.getElementById("std-dl-q")?.value?.trim() || "";
  const params = new URLSearchParams({
    limit: String(STD_DL_STATE.limit),
    offset: String(STD_DL_STATE.offset),
  });
  if (STD_DL_STATE.q) params.set("q", STD_DL_STATE.q);
  try {
    const r = await api(`/api/standard-attachments/pending?${params}`);
    STD_DL_STATE.rows = r.items || [];
    STD_DL_STATE.total = r.total || 0;
    _renderStandardDownloads();
  } catch (e) {
    document.getElementById("std-dl-table").innerHTML =
      `<div class="p-8 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}

function _renderStandardDownloads() {
  document.getElementById("std-dl-count").textContent = `共 ${STD_DL_STATE.total} 条`;
  const rows = STD_DL_STATE.rows.map(a => {
    const meta = a.standard_meta || {};
    return `
      <tr class="border-t border-slate-100">
        <td class="px-4 py-3 text-xs mono whitespace-nowrap">a_${esc(a.id)}</td>
        <td class="px-4 py-3 text-sm font-medium text-slate-900 min-w-[260px]">${esc(a.title || "—")}</td>
        <td class="px-4 py-3 text-xs mono whitespace-nowrap">${esc(meta.standard_no || a.doc_no || "—")}</td>
        <td class="px-4 py-3 text-xs">${esc(meta.standard_status || a.open_category || "—")}</td>
        <td class="px-4 py-3 text-xs whitespace-nowrap">${esc(meta.publish_date || a.publish_date || "—")}</td>
        <td class="px-4 py-3 text-xs whitespace-nowrap">${esc(meta.implementation_date || a.effective_date || "—")}</td>
        <td class="px-4 py-3 text-right">
          <button class="btn-primary" onclick="_startStdDownload(${a.id})">下载附件</button>
        </td>
      </tr>`;
  }).join("") || `<tr><td colspan="7" class="p-10 text-center text-slate-400 text-sm">暂无待下载附件</td></tr>`;
  document.getElementById("std-dl-table").innerHTML = `
    <table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs">
        <tr>
          <th class="text-left px-4 py-2">article</th>
          <th class="text-left px-4 py-2">标题</th>
          <th class="text-left px-4 py-2">标准号</th>
          <th class="text-left px-4 py-2">状态</th>
          <th class="text-left px-4 py-2">发布日期</th>
          <th class="text-left px-4 py-2">实施日期</th>
          <th class="text-right px-4 py-2">操作</th>
        </tr>
      </thead>
      <tbody>${rows}</tbody>
    </table>`;
}

async function _startStdDownload(articleId) {
  try {
    const r = await api(`/api/articles/${articleId}/openstd-download/start`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: "{}",
    });
    _showStdCaptchaModal(articleId, r.session_id, r.captcha_url);
  } catch (e) {
    toast(e.message || "创建下载会话失败", "err");
  }
}

function _showStdCaptchaModal(articleId, sessionId, captchaUrl) {
  openModal({
    title: "下载标准附件",
    subtitle: `article_id = a_${articleId}`,
    body: `
      <div class="p-5 space-y-4">
        <div class="text-sm text-slate-600">输入验证码后，系统会自动下载附件到服务器。</div>
        <div class="flex items-center gap-3">
          <input id="std-captcha-input" maxlength="4" autocomplete="off"
                 class="border border-slate-300 rounded px-3 py-2 text-lg tracking-[0.25em] w-32 text-center"
                 onkeydown="if(event.key==='Enter'){_submitStdCaptcha(${articleId}, '${esc(sessionId)}', '${esc(captchaUrl)}')}"/>
          <img id="std-captcha-img" src="${esc(captchaUrl)}?_=${Date.now()}" class="border border-slate-200 rounded h-12 bg-white cursor-pointer"
               onclick="this.src='${esc(captchaUrl)}?_='+Date.now()" title="点击换一张"/>
          <button class="btn-outline" onclick="document.getElementById('std-captcha-img').src='${esc(captchaUrl)}?_='+Date.now()">换一张</button>
        </div>
        <div id="std-captcha-error" class="text-xs text-red-600"></div>
      </div>`,
    footer: `
      <button class="btn-ghost" onclick="closeModal()">取消</button>
      <button class="btn-primary" onclick="_submitStdCaptcha(${articleId}, '${esc(sessionId)}', '${esc(captchaUrl)}')">提交并下载</button>`,
  });
  setTimeout(() => document.getElementById("std-captcha-input")?.focus(), 50);
}

async function _submitStdCaptcha(articleId, sessionId, captchaUrl) {
  const input = document.getElementById("std-captcha-input");
  const err = document.getElementById("std-captcha-error");
  const img = document.getElementById("std-captcha-img");
  const captcha = (input?.value || "").trim();
  if (!captcha) {
    if (err) err.textContent = "请输入验证码";
    return;
  }
  try {
    const resp = await fetch(`/admin/api/openstd-download-sessions/${sessionId}/submit`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ captcha }),
    });
    if (resp.status === 409) {
      if (err) err.textContent = "验证码不正确，请重新输入";
      if (input) input.value = "";
      if (img) img.src = `${captchaUrl}?_=${Date.now()}`;
      input?.focus();
      return;
    }
    if (!resp.ok) {
      const body = await resp.text().catch(() => "");
      throw new Error(`${resp.status} ${resp.statusText} — ${body.slice(0, 160)}`);
    }
    const r = await resp.json();
    toast(`已下载：${r.attachment?.file_name || "附件"}`, "ok");
    closeModal();
    await loadStandardDownloads();
  } catch (e) {
    if (err) err.textContent = e.message || "下载失败";
    toast(e.message || "下载失败", "err");
  }
}
