// ---------- OA 部门维护 (local_department master-data CRUD) ----------
// Flat table with region filter + search + pagination. Row-level 编辑/删除,
// toolbar-level + 新增 (opens the same modal in "create" mode).

const LOCALDEPTS_STATE = { page: 1, pageSize: 20, rows: [], q: "", region: "" };
let LOCALDEPT_EDITOR = null;

PAGES.localdepts = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  try {
    await loadLocalDepts();
    ws.innerHTML = `
      ${pageBanner({
        title: "OA 部门维护",
        subtitle: "OA 权威部门主数据（含市直 / 县区 / 乡镇 / 虚拟参考），其他模块的部门下拉均来源于此"
      })}
      ${card({
        body: `
          <div class="filter-bar">
            <input id="ld-q" class="filter-grow" placeholder="搜索 部门名称 / 简称 / dept_id…" value="${esc(LOCALDEPTS_STATE.q)}" />
            <select id="ld-region-f" style="width:220px">
              <option value="">区域：全部</option>
              ${DEPT_REGIONS.concat(["其他/虚拟参考"]).map(r => `<option value="${esc(r)}">${esc(r)}</option>`).join("")}
            </select>
            <button class="btn-outline" onclick="resetLocaldeptFilters()">重置</button>
            <div style="flex:1"></div>
            <button class="btn-primary" onclick="openLocaldeptModal()">+ 新增部门</button>
          </div>
          <div id="ld-table"></div>
          <div id="ld-pager"></div>`
      })}`;
    document.getElementById("ld-region-f").value = LOCALDEPTS_STATE.region;
    document.getElementById("ld-q").oninput = (e) => { LOCALDEPTS_STATE.q = e.target.value; LOCALDEPTS_STATE.page = 1; _renderLocaldeptTable(); };
    document.getElementById("ld-region-f").onchange = (e) => { LOCALDEPTS_STATE.region = e.target.value; LOCALDEPTS_STATE.page = 1; _renderLocaldeptTable(); };
    _renderLocaldeptTable();
  } catch (e) {
    ws.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
};

async function loadLocalDepts() {
  const { items } = await api("/api/local-departments?limit=2000");
  LOCALDEPTS_STATE.rows = items;
}

function resetLocaldeptFilters() {
  LOCALDEPTS_STATE.q = ""; LOCALDEPTS_STATE.region = ""; LOCALDEPTS_STATE.page = 1;
  PAGES.localdepts();
}

function _renderLocaldeptTable() {
  const { rows, page, pageSize, q, region } = LOCALDEPTS_STATE;
  const ql = q.trim().toLowerCase();
  const filtered = rows.filter(d => {
    if (region && (_deptRegion(d) || "其他/虚拟参考") !== region) return false;
    if (ql) {
      const hay = `${d.dept_id} ${d.dept_name || ""} ${d.short_name || ""} ${d.full_name || ""}`.toLowerCase();
      if (!hay.includes(ql)) return false;
    }
    return true;
  });
  const total = filtered.length;
  const slice = filtered.slice((page - 1) * pageSize, page * pageSize);
  document.getElementById("ld-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" style="width:110px">dept_id</th>
          <th class="text-left px-4 py-2" style="width:180px">区域</th>
          <th class="text-left px-4 py-2">部门名称</th>
          <th class="text-left px-4 py-2" style="width:160px">简称</th>
          <th class="text-left px-4 py-2" style="width:100px">层级 / 父级</th>
          <th class="text-right px-4 py-2" style="width:180px">操作</th>
        </tr>
      </thead>
      <tbody>
        ${slice.map(d => `
          <tr class="border-t border-slate-100 hover:bg-slate-50/60">
            <td class="px-4 py-2 mono text-xs text-slate-700">${d.dept_id}</td>
            <td class="px-4 py-2 text-xs">${d.region ? pill(d.region, "blue") : pill("未归属", "slate")}</td>
            <td class="px-4 py-2">${esc(d.dept_name || "—")}</td>
            <td class="px-4 py-2 text-xs text-slate-600">${esc(d.short_name || "—")}</td>
            <td class="px-4 py-2 text-xs text-slate-500 mono">L${d.dept_level ?? "?"}${d.parent_dept_id ? " · ↑" + d.parent_dept_id : ""}</td>
            <td class="px-4 py-2 text-right whitespace-nowrap">
              <button onclick="openLocaldeptModal(${d.dept_id})" class="text-xs px-2 py-1 rounded border border-slate-200 text-slate-700 hover:bg-slate-50">编辑</button>
              <button onclick="deleteLocaldept(${d.dept_id}, '${esc(d.dept_name || "")}')" class="text-xs px-2 py-1 rounded border border-red-200 text-red-600 hover:bg-red-50">删除</button>
            </td>
          </tr>`).join("") || `<tr><td colspan="6" class="p-10 text-center text-slate-400 text-sm">无匹配部门</td></tr>`}
      </tbody>
    </table>`;
  renderPager({
    container: document.getElementById("ld-pager"),
    total, page, pageSize,
    summary: `共 ${total} 个部门`,
    onPage: p => { LOCALDEPTS_STATE.page = p; _renderLocaldeptTable(); },
  });
}

function openLocaldeptModal(deptId) {
  const current = deptId != null
    ? (LOCALDEPTS_STATE.rows || []).find(d => d.dept_id === deptId) || null
    : null;
  LOCALDEPT_EDITOR = current;
  const regions = DEPT_REGIONS.concat(["其他/虚拟参考"]);
  const regionOpts = `<option value="">— 未归属 —</option>` +
    regions.map(r => `<option value="${esc(r)}" ${current && current.region === r ? "selected" : ""}>${esc(r)}</option>`).join("");
  openModal({
    title: current ? `编辑部门 · ${current.dept_name || current.dept_id}` : "新增 OA 部门",
    subtitle: "权威部门主数据 — 变更会立即影响所有部门下拉 / 绑定关系",
    body: `
      <div class="grid grid-cols-2 gap-4">
        <div><div class="field-label">dept_id <span class="text-red-500">*</span></div>
          <input id="ld-id" type="number" min="1" value="${current ? current.dept_id : ""}" class="field-input mono" ${current ? "disabled" : ""}/>
          <div class="field-hint">新增虚拟部门建议用 999000+ 以免与 OA 同步冲突</div></div>
        <div><div class="field-label">区域</div>
          <select id="ld-region" class="field-input">${regionOpts}</select></div>
        <div><div class="field-label">部门名称 <span class="text-red-500">*</span></div>
          <input id="ld-name" value="${esc(current?.dept_name || "")}" class="field-input"/></div>
        <div><div class="field-label">简称</div>
          <input id="ld-short" value="${esc(current?.short_name || "")}" class="field-input" placeholder="用于显示名拼接，如 县教育局"/></div>
        <div class="col-span-2"><div class="field-label">全称</div>
          <input id="ld-full" value="${esc(current?.full_name || "")}" class="field-input"/></div>
        <div><div class="field-label">父级 dept_id</div>
          <input id="ld-parent" type="number" min="0" value="${current?.parent_dept_id ?? ""}" class="field-input mono"/></div>
        <div><div class="field-label">层级</div>
          <input id="ld-level" type="number" min="0" value="${current?.dept_level ?? ""}" class="field-input mono"/></div>
      </div>`,
    footer: `
      <button onclick="closeModal()" class="btn-ghost">取消</button>
      <button onclick="saveLocaldept()" class="btn-success">保存</button>`,
    wide: true,
    onClose: () => { LOCALDEPT_EDITOR = null; },
  });
}

async function saveLocaldept() {
  const id = Number(document.getElementById("ld-id").value || 0);
  const payload = {
    dept_id: id,
    dept_name: document.getElementById("ld-name").value.trim(),
    short_name: document.getElementById("ld-short").value.trim(),
    full_name: document.getElementById("ld-full").value.trim(),
    region: document.getElementById("ld-region").value || null,
    parent_dept_id: document.getElementById("ld-parent").value ? Number(document.getElementById("ld-parent").value) : null,
    dept_level: document.getElementById("ld-level").value ? Number(document.getElementById("ld-level").value) : null,
  };
  if (!payload.dept_id || !payload.dept_name) { toast("dept_id 和 部门名称 必填", "err"); return; }
  try {
    if (LOCALDEPT_EDITOR) {
      // dept_id is immutable; strip before PUT
      const { dept_id, ...rest } = payload;
      await api(`/api/local-departments/${dept_id}`, {
        method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(rest),
      });
      toast(`已更新 ${payload.dept_name}`);
    } else {
      await api("/api/local-departments", {
        method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload),
      });
      toast(`已新增 ${payload.dept_name}`);
    }
    closeModal();
    PAGES.localdepts();
  } catch (e) { toast(e.message, "err"); }
}

async function deleteLocaldept(deptId, deptName) {
  if (!confirm(`确认永久删除部门 [${deptId}] ${deptName}？\n关联的采集目标 / 站点部门 映射会被置空，但不会被删除。`)) return;
  try {
    await api(`/api/local-departments/${deptId}`, { method: "DELETE" });
    toast(`已删除 ${deptName}`);
    PAGES.localdepts();
  } catch (e) { toast(e.message, "err"); }
}
