(function () {
  "use strict";

  const PURCHASE_STATUSES = ["待采购", "已下单", "已到货"];
  const PURCHASE_UNITS = ["待确认", "kg", "吨", "张", "卷", "米", "个", "套", "箱"];
  const purchaseAddBusy = new Set();

  function purchaseMaterialKey(value) {
    return String(value || "").trim().normalize("NFKC").toLocaleLowerCase();
  }

  function purchaseEscape(value) {
    return String(value ?? "").replace(/[&<>"']/g, character => ({
      "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
    })[character]);
  }

  function purchaseOrdersForTask(task) {
    const source = Array.isArray(task?.purchaseOrders)
      ? task.purchaseOrders
      : Array.isArray(task?.purchase_orders) ? task.purchase_orders : [];
    task.purchaseOrders = source.map((item, index) => ({
      id: String(item?.id || `local-purchase-${Date.now()}-${index}`),
      material: String(item?.material || "").trim(),
      supplier: String(item?.supplier || "").trim(),
      quantity: Math.max(0, Number(item?.quantity || 0)),
      actual_quantity: Math.max(0, Number(item?.actual_quantity || 0)),
      required_quantity: Math.max(0, Number(item?.required_quantity || 0)),
      on_hand_quantity: Math.max(0, Number(item?.on_hand_quantity || 0)),
      reserved_quantity: Math.max(0, Number(item?.reserved_quantity || 0)),
      issued_quantity: Math.max(0, Number(item?.issued_quantity || 0)),
      returned_quantity: Math.max(0, Number(item?.returned_quantity || 0)),
      leftover_quantity: Math.max(0, Number(item?.leftover_quantity || 0)),
      unit: PURCHASE_UNITS.includes(item?.unit) ? item.unit : "待确认",
      unit_price: Math.max(0, Number(item?.unit_price || 0)),
      delivery_mode: ["送货", "自提", "待确认"].includes(item?.delivery_mode) ? item.delivery_mode : "待确认",
      expected_at: String(item?.expected_at || ""),
      status: PURCHASE_STATUSES.includes(item?.status) ? item.status : "待采购",
      payment_status: ["未付款", "已付款", "月结"].includes(item?.payment_status) ? item.payment_status : "未付款",
      note: String(item?.note || "").trim(),
      ordered_at: String(item?.ordered_at || ""),
      arrived_at: String(item?.arrived_at || ""),
      inventory_state: item?.inventory_state && typeof item.inventory_state === "object" ? item.inventory_state : null
    })).filter(item => item.material);
    delete task.purchase_orders;
    return task.purchaseOrders;
  }

  function purchaseInventoryState(item) {
    if (item?.inventory_state && typeof item.inventory_state === "object") return item.inventory_state;
    const required = Math.max(0, Number(item?.required_quantity || 0));
    const onHand = Math.max(0, Number(item?.on_hand_quantity || 0));
    const reserved = Math.min(onHand, Math.max(0, Number(item?.reserved_quantity || 0)));
    const arrived = item?.status === "已到货" ? Math.max(0, Number(item?.actual_quantity || item?.quantity || 0)) : 0;
    const issued = Math.max(0, Number(item?.issued_quantity || 0));
    const returned = Math.min(issued, Math.max(0, Number(item?.returned_quantity || 0)));
    const shortage = Math.max(0, required - reserved - arrived);
    const planned = Math.max(0, Number(item?.quantity || 0));
    return {
      required, on_hand:onHand, reserved, shortage,
      to_purchase:item?.status === "待采购" ? (planned || shortage) : 0,
      in_transit:item?.status === "已下单" ? planned : 0,
      arrived, issued, returned,
      remaining:Math.max(0, Number(item?.leftover_quantity || 0) || reserved + arrived - issued + returned),
      ready:required > 0 && shortage <= 0
    };
  }

  function purchaseSummaryForTask(task) {
    const items = purchaseOrdersForTask(task);
    const arrived = items.filter(item => item.status === "已到货").length;
    const requirements = items.filter(item => purchaseInventoryState(item).required > 0);
    const shortages = requirements.filter(item => purchaseInventoryState(item).shortage > 0);
    return {
      total: items.length,
      arrived,
      pending: items.length - arrived,
      shortage: shortages.length,
      ready: requirements.length ? shortages.length === 0 : items.length > 0 && arrived === items.length
    };
  }

  function purchaseQuantityText(item) {
    const quantity = item.actual_quantity || item.quantity;
    return quantity > 0 ? `${quantity}${item.unit === "待确认" ? "" : item.unit}` : "数量待补";
  }

  function purchaseItemActionHtml(task, item) {
    const taskId = purchaseEscape(task.id);
    const itemId = purchaseEscape(item.id);
    if (item.status === "待采购") {
      return `<div class="order-purchase-order-action"><input id="purchase-supplier-${itemId}" value="${purchaseEscape(item.supplier)}" placeholder="材料店名称"><button class="btn" type="button" onclick="markPurchaseOrdered('${taskId}','${itemId}')">确认下单</button></div>`;
    }
    if (item.status === "已下单") {
      return `<button class="btn" type="button" onclick="markPurchaseArrived('${taskId}','${itemId}')">确认已到货</button>`;
    }
    return `<div class="order-purchase-arrived-action"><strong>已到货</strong><button type="button" onclick="undoPurchaseStatus('${taskId}','${itemId}')">撤回</button></div>`;
  }

  function purchaseItemHtml(task, item) {
    const taskId = purchaseEscape(task.id);
    const itemId = purchaseEscape(item.id);
    const supplier = item.supplier || "材料店待填";
    const inventory = purchaseInventoryState(item);
    const inventoryUnit = item.unit === "待确认" ? "" : item.unit;
    const inventoryText = inventory.required > 0
      ? inventory.shortage > 0 ? `缺 ${inventory.shortage}${inventoryUnit}` : "本单需求已备齐"
      : "本单需求量待填";
    return `<article class="order-purchase-item is-${item.status === "已到货" ? "arrived" : item.status === "已下单" ? "ordered" : "pending"}">
      <div class="order-purchase-status-dot" aria-hidden="true">${item.status === "已到货" ? "✓" : item.status === "已下单" ? "2" : "1"}</div>
      <div class="order-purchase-main">
        <div class="order-purchase-name"><strong>${purchaseEscape(item.material)}</strong><span class="order-purchase-badge">${purchaseEscape(item.status)}</span></div>
        <div class="order-purchase-meta"><span>${purchaseEscape(supplier)}</span><span>${purchaseEscape(purchaseQuantityText(item))}</span>${item.unit_price > 0 ? `<span>¥${purchaseEscape(item.unit_price)}/${purchaseEscape(item.unit === "待确认" ? "单位" : item.unit)}</span>` : ""}<span class="${inventory.shortage > 0 ? "is-risk" : ""}">${purchaseEscape(inventoryText)}</span></div>
        ${inventory.required > 0 ? `<div class="order-inventory-strip"><span>需求 ${inventory.required}${purchaseEscape(inventoryUnit)}</span><span>库存 ${inventory.on_hand}${purchaseEscape(inventoryUnit)}</span><span>预留 ${inventory.reserved}${purchaseEscape(inventoryUnit)}</span><span>采购中 ${inventory.in_transit}${purchaseEscape(inventoryUnit)}</span><span>到货 ${inventory.arrived}${purchaseEscape(inventoryUnit)}</span><span>领料 ${inventory.issued}${purchaseEscape(inventoryUnit)}</span><span>余料 ${inventory.remaining}${purchaseEscape(inventoryUnit)}</span></div>` : ""}
      </div>
      <div class="order-purchase-primary">${purchaseItemActionHtml(task, item)}<button class="order-purchase-delete" type="button" aria-label="删除${purchaseEscape(item.material)}" onclick="deletePurchaseItem('${taskId}','${itemId}')">删除</button></div>
      <details class="order-purchase-details"><summary>库存、采购和领料</summary>
        <div class="order-purchase-edit-grid">
          <label>材料名称<input id="purchase-material-${itemId}" value="${purchaseEscape(item.material)}"></label>
          <label>材料店<input id="purchase-edit-supplier-${itemId}" value="${purchaseEscape(item.supplier)}" placeholder="例如：城东纸张店"></label>
          <label>本单需要多少<input id="purchase-required-${itemId}" type="number" min="0" step="0.01" value="${item.required_quantity || ""}" placeholder="例如：500"></label>
          <label>仓库现有<input id="purchase-on-hand-${itemId}" type="number" min="0" step="0.01" value="${item.on_hand_quantity || ""}" placeholder="没有就填0"></label>
          <label>为本单预留<input id="purchase-reserved-${itemId}" type="number" min="0" step="0.01" value="${item.reserved_quantity || ""}" placeholder="从库存占用"></label>
          <label>计划采购<input id="purchase-quantity-${itemId}" type="number" min="0" step="0.01" value="${item.quantity || ""}" placeholder="可参考缺料数"></label>
          <label>实际到货<input id="purchase-actual-${itemId}" type="number" min="0" step="0.01" value="${item.actual_quantity || ""}" placeholder="到货后填写"></label>
          <label>已领料<input id="purchase-issued-${itemId}" type="number" min="0" step="0.01" value="${item.issued_quantity || ""}" placeholder="车间领用"></label>
          <label>已退料<input id="purchase-returned-${itemId}" type="number" min="0" step="0.01" value="${item.returned_quantity || ""}" placeholder="车间退回"></label>
          <label>盘点余料<input id="purchase-leftover-${itemId}" type="number" min="0" step="0.01" value="${item.leftover_quantity || ""}" placeholder="完工后盘点"></label>
          <label>单位<select id="purchase-unit-${itemId}">${PURCHASE_UNITS.map(unit => `<option${unit === item.unit ? " selected" : ""}>${unit}</option>`).join("")}</select></label>
          <label>单价<input id="purchase-price-${itemId}" type="number" min="0" step="0.01" value="${item.unit_price || ""}" placeholder="可稍后填"></label>
          <label>到货方式<select id="purchase-delivery-${itemId}">${["待确认", "送货", "自提"].map(value => `<option${value === item.delivery_mode ? " selected" : ""}>${value}</option>`).join("")}</select></label>
        </div>
        <div class="order-purchase-edit-actions"><button class="btn light" type="button" onclick="savePurchaseDetails('${taskId}','${itemId}')">保存补充信息</button></div>
      </details>
    </article>`;
  }

  function quoteMaterialSuggestion(task) {
    if (!Number(task?.quoteId || task?.quote_id || 0)) return "";
    const quote = typeof relatedQuoteForTask === "function" ? relatedQuoteForTask(task) : null;
    const material = String(quote?.material || "").trim();
    return ["", "待确认", "材料待确认", "材质待确认"].includes(material) ? "" : material;
  }

  function purchaseCardHtml(task) {
    if (!task || (typeof taskPhase === "function" && taskPhase(task) !== "生产中" && !purchaseOrdersForTask(task).length)) return "";
    const items = purchaseOrdersForTask(task);
    const summary = purchaseSummaryForTask(task);
    const taskId = purchaseEscape(task.id);
    const suggestion = quoteMaterialSuggestion(task);
    const summaryText = !summary.total
      ? "还没有采购材料"
      : summary.ready ? `${summary.total} 项材料已备齐` : `${summary.shortage ? `${summary.shortage} 项缺料` : `${summary.arrived}/${summary.total} 项已到货`} · ${summary.pending} 项采购待处理`;
    const empty = `<div class="order-purchase-empty"><strong>把本单需要的材料加进来</strong><span>填写需求量和仓库库存，系统会自动算缺多少、买多少。</span>${suggestion ? `<button class="btn light" type="button" onclick="addPurchaseSuggestion('${taskId}')">从报价带入：${purchaseEscape(suggestion)}</button>` : ""}</div>`;
    return `<section class="order-purchase-card${summary.ready ? " is-ready" : ""}" data-order-purchase-card>
      <header class="order-purchase-head"><div><span class="order-purchase-eyebrow">本单材料</span><h3>库存与采购</h3><p>报价确认后记录本单需求，自动看库存、缺料、采购、到货、领料和余料。</p></div><div class="order-purchase-summary"><strong>${purchaseEscape(summaryText)}</strong><span>${summary.ready ? "材料已就绪" : "看清缺什么、订了没有、到了没有"}</span></div></header>
      <div class="order-purchase-list">${items.length ? items.map(item => purchaseItemHtml(task, item)).join("") : empty}</div>
      <details class="order-purchase-add"><summary>＋ 添加材料</summary><div class="order-purchase-add-row"><input id="purchase-new-material-${taskId}" placeholder="材料名称，例如：300g白卡"><input id="purchase-new-supplier-${taskId}" placeholder="材料店（可以稍后填）"><button class="btn" type="button" onclick="addPurchaseItem('${taskId}')">添加</button></div></details>
    </section>`;
  }

  function taskByPurchaseId(taskId) {
    return typeof businessTasks === "function" ? businessTasks().find(item => String(item.id) === String(taskId)) : null;
  }

  function purchaseInput(id) {
    return String(document.getElementById(id)?.value || "").trim();
  }

  function localPurchaseAction(task, action, payload) {
    const items = purchaseOrdersForTask(task);
    if (action === "add") {
      if (items.some(item => purchaseMaterialKey(item.material) === purchaseMaterialKey(payload.material))) {
        throw new Error("本单已经有这项材料，请直接编辑原来的记录");
      }
      items.push({
        id: `local-purchase-${Date.now()}-${Math.random().toString(16).slice(2, 7)}`,
        material: String(payload.material || "").trim(), supplier: String(payload.supplier || "").trim(),
        quantity: 0, actual_quantity: 0, required_quantity:0, on_hand_quantity:0,
        reserved_quantity:0, issued_quantity:0, returned_quantity:0, leftover_quantity:0,
        unit: "待确认", unit_price: 0,
        delivery_mode: "待确认", expected_at: "", status: "待采购", payment_status: "未付款",
        note: "", ordered_at: "", arrived_at: ""
      });
    } else {
      const index = items.findIndex(item => item.id === payload.purchase_id);
      if (index < 0) throw new Error("没有找到这项采购材料");
      const item = items[index];
      if (action === "update") Object.assign(item, payload, { id: item.id, status: item.status });
      if (action === "order") Object.assign(item, { supplier: payload.supplier, status: "已下单", ordered_at: new Date().toISOString(), arrived_at: "" });
      if (action === "arrive") Object.assign(item, { status: "已到货", arrived_at: new Date().toISOString() });
      if (action === "undo") Object.assign(item, item.status === "已到货" ? { status: "已下单", arrived_at: "" } : { status: "待采购", ordered_at: "" });
      if (action === "delete") items.splice(index, 1);
    }
    task.purchaseOrders = items;
    task.logs = [`${new Date().toLocaleString("zh-CN", { hour12: false })} 更新按单采购`, ...(task.logs || [])].slice(0, 20);
    if (typeof saveState === "function") saveState();
    if (typeof renderTasks === "function") renderTasks();
    if (typeof renderDashboard === "function") renderDashboard();
    if (typeof showTaskDetail === "function") showTaskDetail(task.id);
  }

  async function runPurchaseAction(taskId, action, payload = {}) {
    const task = taskByPurchaseId(taskId);
    if (!task) return;
    try {
      if (task.serverId && typeof window.__updateFormalTaskPurchase === "function") {
        await window.__updateFormalTaskPurchase(task, action, payload);
      } else {
        localPurchaseAction(task, action, payload);
      }
    } catch (error) {
      if (typeof notify === "function") notify(error.message || "采购记录没有保存");
    }
  }

  async function addPurchaseItem(taskId, materialOverride = "") {
    const material = materialOverride || purchaseInput(`purchase-new-material-${taskId}`);
    const supplier = materialOverride ? "" : purchaseInput(`purchase-new-supplier-${taskId}`);
    if (!material) return typeof notify === "function" && notify("请先填写材料名称。");
    const task = taskByPurchaseId(taskId);
    if (!task) return;
    if (purchaseOrdersForTask(task).some(item => purchaseMaterialKey(item.material) === purchaseMaterialKey(material))) {
      return typeof notify === "function" && notify("本单已经有这项材料，请直接编辑或删除原来的记录。");
    }
    const busyKey = `${taskId}:${purchaseMaterialKey(material)}`;
    if (purchaseAddBusy.has(busyKey)) return;
    purchaseAddBusy.add(busyKey);
    try {
      await runPurchaseAction(taskId, "add", { material, supplier });
    } finally {
      purchaseAddBusy.delete(busyKey);
    }
  }

  function addPurchaseSuggestion(taskId) {
    const task = taskByPurchaseId(taskId);
    return task ? addPurchaseItem(taskId, quoteMaterialSuggestion(task)) : null;
  }

  async function markPurchaseOrdered(taskId, purchaseId) {
    const supplier = purchaseInput(`purchase-supplier-${purchaseId}`);
    if (!supplier) return typeof notify === "function" && notify("请先填写材料店，再确认下单。");
    if (!window.confirm(`确认已经向“${supplier}”下单？`)) return;
    await runPurchaseAction(taskId, "order", { purchase_id: purchaseId, supplier, confirm: true });
  }

  async function markPurchaseArrived(taskId, purchaseId) {
    if (!window.confirm("确认这项材料已经到货？")) return;
    await runPurchaseAction(taskId, "arrive", { purchase_id: purchaseId, confirm: true });
  }

  async function undoPurchaseStatus(taskId, purchaseId) {
    if (!window.confirm("确认撤回刚才的采购状态？")) return;
    await runPurchaseAction(taskId, "undo", { purchase_id: purchaseId, confirm: true });
  }

  async function deletePurchaseItem(taskId, purchaseId) {
    if (!window.confirm("确定删除这项采购材料？")) return;
    await runPurchaseAction(taskId, "delete", { purchase_id: purchaseId, confirm: true });
  }

  async function savePurchaseDetails(taskId, purchaseId) {
    const payload = {
      purchase_id: purchaseId,
      material: purchaseInput(`purchase-material-${purchaseId}`),
      supplier: purchaseInput(`purchase-edit-supplier-${purchaseId}`),
      required_quantity: purchaseInput(`purchase-required-${purchaseId}`),
      on_hand_quantity: purchaseInput(`purchase-on-hand-${purchaseId}`),
      reserved_quantity: purchaseInput(`purchase-reserved-${purchaseId}`),
      quantity: purchaseInput(`purchase-quantity-${purchaseId}`),
      actual_quantity: purchaseInput(`purchase-actual-${purchaseId}`),
      issued_quantity: purchaseInput(`purchase-issued-${purchaseId}`),
      returned_quantity: purchaseInput(`purchase-returned-${purchaseId}`),
      leftover_quantity: purchaseInput(`purchase-leftover-${purchaseId}`),
      unit: purchaseInput(`purchase-unit-${purchaseId}`),
      unit_price: purchaseInput(`purchase-price-${purchaseId}`),
      delivery_mode: purchaseInput(`purchase-delivery-${purchaseId}`)
    };
    if (!payload.material) return typeof notify === "function" && notify("材料名称不能为空。");
    await runPurchaseAction(taskId, "update", payload);
    if (typeof notify === "function") notify("库存、采购和领料数据已保存。");
  }

  window.purchaseCardHtml = purchaseCardHtml;
  window.purchaseOrdersForTask = purchaseOrdersForTask;
  window.addPurchaseItem = addPurchaseItem;
  window.addPurchaseSuggestion = addPurchaseSuggestion;
  window.markPurchaseOrdered = markPurchaseOrdered;
  window.markPurchaseArrived = markPurchaseArrived;
  window.undoPurchaseStatus = undoPurchaseStatus;
  window.deletePurchaseItem = deletePurchaseItem;
  window.savePurchaseDetails = savePurchaseDetails;
})();
