(() => {
  "use strict";
  const API = "/api/supplier-collaboration";
  const token = localStorage.getItem("formal_api_token") || "";
  const state = { suppliers: [], orders: [], statements: [], costs: [], summary: {}, collaboration: null };
  const statusGroups = [
    ["draft", "草稿"],
    ["sent", "待接单"],
    ["accepted,producing", "加工中"],
    ["delivered", "待验收"],
    ["accepted_delivery", "已验收"]
  ];
  const money = value => Number(value || 0).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const safe = value => String(value ?? "").replace(/[&<>"']/g, char => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[char]));
  const friendlyError = error => {
    const raw = String(error?.message || error || "").trim();
    if (/not found|404|找不到/i.test(raw)) return "没有找到对应资料，可能已被删除或链接已经失效。";
    if (/unauthorized|401|登录|token|认证/i.test(raw)) return "登录状态已失效，请返回主工作台重新登录后再试。";
    if (/forbidden|403|permission|权限/i.test(raw)) return "当前账号没有这项操作权限，请联系管理员。";
    if (/timeout|timed out|超时|abort/i.test(raw)) return "服务响应较慢，当前资料已保留，可以直接重试。";
    if (/failed to fetch|network|connection|连接|网络/i.test(raw)) return "当前网络连接不稳定，请检查网络后重试。";
    if (/undefined|can't find variable|is not defined|null/i.test(raw)) return "页面状态没有正确加载，请刷新页面后重试。";
    if (/server|500|502|503|504|服务/i.test(raw)) return "服务暂时繁忙，当前资料已保留，请稍后重试。";
    return raw || "请求没有完成，请稍后重试。";
  };
  const today = () => new Date().toISOString().slice(0, 10);
  const toast = message => {
    const element = document.getElementById("toast");
    element.textContent = message;
    element.classList.add("show");
    clearTimeout(toast.timer);
    toast.timer = setTimeout(() => element.classList.remove("show"), 2600);
  };
  async function api(path, options = {}) {
    const headers = { "Content-Type":"application/json", ...(options.headers || {}) };
    if (token) headers.Authorization = `Bearer ${token}`;
    let response;
    try { response = await fetch(path, { ...options, headers }); }
    catch (error) { throw new Error(friendlyError(error)); }
    let data = {};
    try { data = await response.json(); } catch { throw new Error("服务返回格式不完整"); }
    if (!response.ok || data.ok === false) {
      if (response.status === 401) {
        document.getElementById("cloudState").innerHTML = "<i></i>请先登录";
      }
      throw new Error(friendlyError(data.error || "请求没有完成"));
    }
    return data;
  }
  const formData = form => Object.fromEntries(new FormData(form).entries());
  function supplierOptions() {
    const options = state.suppliers.filter(item => item.status === "active").map(item => `<option value="${item.id}">${safe(item.name)} · ${safe((item.categories || []).join("/"))}</option>`).join("");
    ["orderSupplier", "statementSupplier"].forEach(id => {
      const select = document.getElementById(id);
      if (select) select.innerHTML = options || '<option value="">请先添加供应商</option>';
    });
  }
  function renderMetrics() {
    const orders = state.summary.orders || {};
    const working = ["sent","accepted","producing","delivered"].reduce((sum, key) => sum + Number(orders[key]?.count || 0), 0);
    const accepted = Number(orders.accepted_delivery?.amount || 0);
    const items = [
      ["合作供应商", state.summary.suppliers || 0, "已启用档案"],
      ["进行中外协", working, "待接单至待验收"],
      ["逾期任务", state.summary.overdue || 0, "需要优先处理"],
      ["已验收应付", `¥${money(accepted)}`, "按验收数量计算"],
      ["月结待付", `¥${money(state.summary.unpaid)}`, "已确认未付清"]
    ];
    document.getElementById("metrics").innerHTML = items.map(item => `<article class="metric"><span>${item[0]}</span><strong>${item[1]}</strong><em>${item[2]}</em></article>`).join("");
  }
  function orderActions(order) {
    const actions = [];
    if (["draft","sent"].includes(order.status)) actions.push(`<button class="strong" data-action="send" data-id="${order.id}">${order.status === "sent" ? "重新生成链接" : "发给供应商"}</button>`);
    if (order.status === "delivered") actions.push(`<button class="strong" data-action="accept" data-id="${order.id}">交付验收</button>`);
    if (!["rejected","cancelled"].includes(order.status)) actions.push(`<button data-action="collaboration" data-id="${order.id}">发料 / 返工</button>`);
    actions.push(`<button data-action="events" data-id="${order.id}">查看记录</button>`);
    return actions.join("");
  }
  const responsibilityLabel = value => ({
    supplier:"供应商", factory:"本厂", customer:"客户变更", shared:"共同承担", pending:"待确认"
  })[value] || value || "待确认";
  function renderCollaboration(order, data) {
    state.collaboration = { order, ...data };
    const balances = data.material_balances || [];
    document.getElementById("collaborationOrderName").textContent = `${order.order_no} · ${order.supplier_name}`;
    document.getElementById("materialSummary").innerHTML = balances.map(item => `<article><span>${safe(item.material_name)} · 在外</span><strong>${Number(item.balance || 0).toLocaleString()} ${safe(item.unit)}</strong><small>发 ${Number(item.issue || 0).toLocaleString()} · 耗 ${Number(item.consume || 0).toLocaleString()} · 退 ${Number(item.return || 0).toLocaleString()} · 损 ${Number(item.scrap || 0).toLocaleString()}</small></article>`).join("") || "<article><span>尚未发料</span><strong>0</strong></article>";
    document.getElementById("materialTable").innerHTML = (data.materials || []).map(item => `<tr>
      <td>${safe(item.created_at || "-")}</td><td>${safe(item.movement_label)}</td>
      <td>${safe(item.material_name)}<br><small>${safe(item.specification || "")}</small></td>
      <td>${Number(item.quantity || 0).toLocaleString()} ${safe(item.unit)}</td><td>${safe(item.note || "-")}</td>
    </tr>`).join("") || '<tr><td colspan="5" class="empty">尚未登记发料。来料加工时建议先登记发料，再记录实际耗用、退料和损耗。</td></tr>';
    document.getElementById("reworkList").innerHTML = (data.reworks || []).map(item => `<article class="rework-item">
      <header><strong>#${item.id} · ${safe(item.status_label)}</strong><span>${safe(item.due_at || "未设补交日")}</span></header>
      <p>${safe(item.reason)}<br>数量 ${Number(item.quantity || 0).toLocaleString()} ${safe(item.unit)} · 责任 ${safe(responsibilityLabel(item.responsibility))}${item.resolution ? `<br>处理：${safe(item.resolution)}` : ""}</p>
      ${["open","accepted","in_progress"].includes(item.status) ? `<footer><button type="button" data-action="complete-rework" data-order-id="${order.id}" data-id="${item.id}">本厂确认返工完成</button><button type="button" data-action="cancel-rework" data-order-id="${order.id}" data-id="${item.id}">取消返工</button></footer>` : ""}
    </article>`).join("") || '<div class="empty">暂无返工任务</div>';
    ["materialForm","reworkForm"].forEach(id => document.getElementById(id).elements.order_id.value = order.id);
  }
  async function openCollaboration(order) {
    const data = await api(`${API}/orders/${order.id}/collaboration`);
    renderCollaboration(order, data);
    document.getElementById("collaborationDialog").showModal();
  }
  function renderOrders() {
    const query = document.getElementById("orderSearch").value.trim().toLowerCase();
    const status = document.getElementById("orderStatus").value;
    const orders = state.orders.filter(order => {
      if (status && order.status !== status) return false;
      return !query || [order.order_no, order.title, order.product, order.process, order.supplier_name].some(value => String(value || "").toLowerCase().includes(query));
    });
    document.getElementById("orderBoard").innerHTML = statusGroups.map(([keys, label]) => {
      const values = keys.split(",");
      const cards = orders.filter(item => values.includes(item.status)).map(order => {
        const overdue = order.due_at && order.due_at < today() && !["accepted_delivery","rejected","cancelled"].includes(order.status);
        const quantityLine = order.status === "delivered"
          ? `交付 ${Number(order.delivered_quantity || 0).toLocaleString()} ${safe(order.unit)}`
          : `${Number(order.quantity || 0).toLocaleString()} ${safe(order.unit)}`;
        return `<article class="order-card${overdue ? " overdue" : ""}" data-order-id="${order.id}">
          <div class="top"><span class="order-no">${safe(order.order_no)}</span><span class="status">${safe(order.status_label)}</span></div>
          <h3>${safe(order.title)}</h3>
          <p>${safe(order.supplier_name)} · ${safe(order.process)}</p>
          <p>${safe(quantityLine)} · 交期 ${safe(order.due_at || "待确认")}${overdue ? " · 已逾期" : ""}</p>
          <p class="money">约定 ¥${money(order.quoted_amount)}${order.status === "accepted_delivery" ? ` · 应付 ¥${money(order.payable)}` : ""}</p>
          <footer>${orderActions(order)}</footer>
        </article>`;
      }).join("");
      return `<section class="lane"><div class="lane-head">${label}<span>${cards ? orders.filter(item => values.includes(item.status)).length : 0}</span></div>${cards || '<div class="empty">暂无任务</div>'}</section>`;
    }).join("");
  }
  function renderSuppliers() {
    document.getElementById("supplierGrid").innerHTML = state.suppliers.map(item => `<article class="supplier-card">
      <header><h3>${safe(item.name)}</h3><span class="state">${item.status === "active" ? "合作中" : "已停用"}</span></header>
      <p>${safe(item.contact || "未填联系人")} · ${safe(item.phone || "未填电话")} · ${safe(item.region || "未填区域")}</p>
      <div class="chips">${(item.categories || []).map(value => `<span>${safe(value)}</span>`).join("") || "<span>未设置工序</span>"}</div>
      <p>${safe(item.note || "暂无合作备注")}</p>
      <footer><strong>${safe(item.settlement_type)} · ${Number(item.payment_days || 0)}天 · ${safe(item.delivery_mode)}</strong><button data-action="edit-supplier" data-id="${item.id}">编辑</button></footer>
    </article>`).join("") || '<div class="empty"><strong>还没有供应商档案</strong>先添加常用覆膜、模切、印刷或材料合作方。</div>';
  }
  function renderStatements() {
    document.getElementById("statementList").innerHTML = state.statements.map(item => {
      const ratio = item.total ? Math.min(100, Number(item.paid || 0) / Number(item.total) * 100) : 0;
      const items = item.items.map(line => `<tr><td>${safe(line.order_no)}</td><td>${safe(line.title)}</td><td>¥${money(line.amount)}</td></tr>`).join("");
      const payments = item.payments.map(payment => `<tr><td>${safe(payment.created_at)}</td><td>${safe(payment.payment_method)} ${safe(payment.reference_no)}</td><td>${payment.amount < 0 ? "冲销 " : ""}¥${money(Math.abs(payment.amount))}</td></tr>`).join("");
      return `<article class="statement">
        <header><div><h3>${safe(item.supplier_name)} · ${safe(item.period)}</h3><p>${safe(item.statement_no)} · ${safe(item.status_label)}</p></div><div class="amount"><strong>¥${money(item.total)}</strong><span>已付 ¥${money(item.paid)} · 待付 ¥${money(item.unpaid)}</span></div></header>
        <div class="progress"><i style="width:${ratio}%"></i></div>
        <details><summary>查看 ${item.items.length} 笔外协与付款记录</summary><table><tbody>${items}${payments}</tbody></table></details>
        <footer>${item.status === "draft" ? `<button data-action="confirm-statement" data-id="${item.id}">确认锁定</button>` : ""}${item.unpaid > 0 && item.status !== "draft" ? `<button data-action="pay" data-id="${item.id}">登记付款</button>` : ""}</footer>
      </article>`;
    }).join("") || '<div class="empty"><strong>还没有月结单</strong>外协单完成验收后，可按供应商和月份汇总生成。</div>';
  }
  function renderCosts() {
    document.getElementById("costTable").innerHTML = state.costs.map(item => `<tr>
      <td>${safe(item.accepted_at || "-")}</td><td>${safe(item.supplier_name)}</td>
      <td>${safe(item.product || item.order_no)}<br><small>${safe(item.process)}</small></td>
      <td>${safe(item.specification || "-")}</td><td>${Number(item.accepted_quantity || 0).toLocaleString()} ${safe(item.unit)}</td>
      <td>¥${money(item.unit_price)}</td><td><strong>¥${money(item.actual_amount)}</strong></td>
    </tr>`).join("") || '<tr><td colspan="7" class="empty">完成第一笔交付验收后，这里会出现真实成本。</td></tr>';
  }
  function render() {
    renderMetrics(); supplierOptions(); renderOrders(); renderSuppliers(); renderStatements(); renderCosts();
  }
  async function load() {
    document.getElementById("refreshButton").disabled = true;
    try {
      const [summary, suppliers, orders, statements, costs] = await Promise.all([
        api(`${API}/summary`), api(`${API}/suppliers`), api(`${API}/orders`),
        api(`${API}/statements`), api(`${API}/actual-cost-feedback`)
      ]);
      state.summary = summary.summary || {};
      state.suppliers = suppliers.suppliers || [];
      state.orders = orders.orders || [];
      state.statements = statements.statements || [];
      state.costs = costs.items || [];
      render();
      document.getElementById("cloudState").innerHTML = "<i></i>云端协作正常";
      const parameters = new URLSearchParams(location.search);
      if (parameters.get("create") === "order" && !load.prefilled) {
        load.prefilled = true;
        const form = document.getElementById("orderForm");
        ["source_task_ref","source_step_ref","title","product","process","quantity","unit","due_at"].forEach(key => {
          if (parameters.has(key) && form.elements[key]) form.elements[key].value = parameters.get(key);
        });
        document.getElementById("orderDialog").showModal();
      } else if (parameters.get("order_id") && !load.focused) {
        load.focused = true;
        const target = document.querySelector(`[data-order-id="${CSS.escape(parameters.get("order_id"))}"]`);
        if (target) {
          target.classList.add("is-focused");
          target.scrollIntoView({ behavior:"smooth", block:"center" });
        }
      }
    } catch (error) {
      document.getElementById("orderBoard").innerHTML = `<div class="empty"><strong>外协数据暂时没有读取成功</strong>${safe(error.message)}<br><br><a class="secondary button-link" href="/">返回登录后重试</a></div>`;
      toast(error.message);
    } finally {
      document.getElementById("refreshButton").disabled = false;
    }
  }
  async function post(path, body) {
    const data = await api(path, { method:"POST", body:JSON.stringify(body || {}) });
    await load();
    return data;
  }
  document.addEventListener("click", async event => {
    const open = event.target.closest("[data-open]");
    if (open) {
      const dialog = document.getElementById(open.dataset.open);
      if (dialog.id === "statementDialog") dialog.querySelector('[name="period"]').value = new Date().toISOString().slice(0, 7);
      dialog.showModal();
      return;
    }
    const tab = event.target.closest("[data-tab]");
    if (tab) {
      document.querySelectorAll("[data-tab]").forEach(item => item.classList.toggle("active", item === tab));
      document.querySelectorAll("[data-panel]").forEach(item => item.classList.toggle("active", item.dataset.panel === tab.dataset.tab));
      document.getElementById("orderFilters").style.display = tab.dataset.tab === "orders" ? "" : "none";
      return;
    }
    const action = event.target.closest("[data-action]");
    if (!action) return;
    const id = Number(action.dataset.id);
    try {
      if (action.dataset.action === "send") {
        const data = await post(`${API}/orders/${id}/send`, {});
        await navigator.clipboard.writeText(data.share_url);
        toast("供应商接单链接已复制，可直接发微信");
      } else if (action.dataset.action === "accept") {
        const order = state.orders.find(item => Number(item.id) === id);
        const form = document.getElementById("acceptanceForm");
        form.order_id.value = id;
        form.accepted_quantity.value = Number(order.delivered_quantity || order.quantity || 0);
        form.rejected_quantity.value = 0;
        document.getElementById("acceptanceOrderName").textContent = `${order.order_no} · 交付 ${order.delivered_quantity}${order.unit}`;
        document.getElementById("acceptanceDialog").showModal();
      } else if (action.dataset.action === "events") {
        const data = await api(`${API}/orders/${id}/events`);
        alert((data.events || []).map(item => `${item.created_at}  ${item.actor_name || item.actor_type}：${item.action}${item.detail ? `\n${item.detail}` : ""}`).join("\n\n") || "暂无流转记录");
      } else if (action.dataset.action === "collaboration") {
        const order = state.orders.find(item => Number(item.id) === id);
        if (order) await openCollaboration(order);
      } else if (["complete-rework","cancel-rework"].includes(action.dataset.action)) {
        const orderId = Number(action.dataset.orderId);
        const resolution = action.dataset.action === "complete-rework"
          ? prompt("填写返工验收结果（可选）", "补交数量和质量已核对")
          : prompt("填写取消原因（可选）", "");
        if (resolution === null) return;
        const data = await api(`${API}/orders/${orderId}/reworks/${id}`, {
          method:"POST",
          body:JSON.stringify({
            status:action.dataset.action === "complete-rework" ? "completed" : "cancelled",
            resolution
          })
        });
        const order = state.orders.find(item => Number(item.id) === orderId);
        renderCollaboration(order, data);
        toast("返工状态已更新");
      } else if (action.dataset.action === "edit-supplier") {
        const item = state.suppliers.find(row => Number(row.id) === id);
        const form = document.getElementById("supplierForm");
        Object.entries({ ...item, categories:(item.categories || []).join("、") }).forEach(([key,value]) => { if (form.elements[key]) form.elements[key].value = value ?? ""; });
        document.getElementById("supplierDialog").showModal();
      } else if (action.dataset.action === "confirm-statement") {
        if (confirm("确认后对账单金额将锁定，是否继续？")) await post(`${API}/statements/${id}/confirm`, {});
      } else if (action.dataset.action === "pay") {
        const item = state.statements.find(row => Number(row.id) === id);
        const form = document.getElementById("paymentForm");
        form.statement_id.value = id;
        form.amount.value = item.unpaid;
        document.getElementById("paymentStatementName").textContent = `${item.statement_no} · 待付 ¥${money(item.unpaid)}`;
        document.getElementById("paymentDialog").showModal();
      }
    } catch (error) { toast(error.message); }
  });
  document.getElementById("supplierForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    data.categories = data.categories.split(/[,，、]/).map(value => value.trim()).filter(Boolean);
    try { await post(`${API}/suppliers`, data); event.currentTarget.closest("dialog").close(); event.currentTarget.reset(); toast("供应商档案已保存"); } catch (error) { toast(error.message); }
  });
  document.getElementById("orderForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    data.tax_included = data.tax_included === "true";
    data.color_proof_required = data.color_proof_required === "true";
    data.production_files = String(data.production_files || "")
      .split(/\n/)
      .map(line => {
        const [name, url] = line.split("|").map(value => value.trim());
        return name && url ? { name, url, category:"production" } : null;
      })
      .filter(Boolean);
    data.logistics = {
      mode:data.logistics_mode,
      pickup_address:data.pickup_address,
      delivery_address:data.delivery_address,
      contact:data.logistics_contact,
      next_process:data.next_process
    };
    data.quality = {
      standard:data.quality_standard,
      sample_count:Number(data.quality_sample_count || 0),
      evidence_required:true
    };
    try { await post(`${API}/orders`, data); event.currentTarget.closest("dialog").close(); event.currentTarget.reset(); toast("外协单草稿已创建"); } catch (error) { toast(error.message); }
  });
  document.getElementById("acceptanceForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    try { await post(`${API}/orders/${data.order_id}/acceptance`, data); event.currentTarget.closest("dialog").close(); toast("交付已验收，应付已更新"); } catch (error) { toast(error.message); }
  });
  document.getElementById("materialForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    try {
      const result = await api(`${API}/orders/${data.order_id}/materials`, { method:"POST", body:JSON.stringify(data) });
      renderCollaboration(state.collaboration.order, result);
      event.currentTarget.reset();
      event.currentTarget.elements.order_id.value = state.collaboration.order.id;
      event.currentTarget.elements.unit.value = "张";
      event.currentTarget.elements.unit_cost.value = 0;
      toast("物料流水已登记");
    } catch (error) { toast(error.message); }
  });
  document.getElementById("reworkForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    try {
      const result = await api(`${API}/orders/${data.order_id}/reworks`, { method:"POST", body:JSON.stringify(data) });
      renderCollaboration(state.collaboration.order, result);
      event.currentTarget.reset();
      event.currentTarget.elements.order_id.value = state.collaboration.order.id;
      event.currentTarget.elements.unit.value = state.collaboration.order.unit || "件";
      event.currentTarget.elements.quantity.value = 0;
      event.currentTarget.elements.adjustment.value = 0;
      toast("返工任务已发起，供应商接单页会同步显示");
    } catch (error) { toast(error.message); }
  });
  document.getElementById("statementForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    try { await post(`${API}/statements/generate`, data); event.currentTarget.closest("dialog").close(); toast("月结单已生成，核对后再确认锁定"); } catch (error) { toast(error.message); }
  });
  document.getElementById("paymentForm").addEventListener("submit", async event => {
    event.preventDefault();
    const data = formData(event.currentTarget);
    try { await post(`${API}/statements/${data.statement_id}/payments`, data); event.currentTarget.closest("dialog").close(); toast("付款记录已保存"); } catch (error) { toast(error.message); }
  });
  document.getElementById("orderSearch").addEventListener("input", renderOrders);
  document.getElementById("orderStatus").addEventListener("change", renderOrders);
  document.getElementById("refreshButton").addEventListener("click", load);
  document.querySelectorAll("[data-close-dialog]").forEach(button => button.addEventListener("click", () => button.closest("dialog").close()));
  document.querySelectorAll("dialog").forEach(dialog => dialog.addEventListener("click", event => {
    if (event.target === dialog) dialog.close();
  }));
  load();
})();
