(function (root) {
  "use strict";

  async function saveQuoteReliabilityCloud(record, payload) {
    if (!record?.serverId || typeof root.__jianglaiAppApi !== "function") throw new Error("报价尚未保存到服务端");
    const data = await root.__jianglaiAppApi(`/api/quotes/${record.serverId}/reliability`, {
      method: "POST", body: JSON.stringify(payload)
    });
    const result = data.result || {};
    record.goldenSample = result.golden_sample || null;
    record.goldenValidation = result.golden_validation || null;
    record.routeCandidates = Array.isArray(result.route_candidates) ? result.route_candidates : [];
    record.routeComparison = result.route_comparison || null;
    saveState();
    return data;
  }

  function renderQuoteReliabilityPanel(record = activeQuoteRecord()) {
    const box = document.getElementById("quoteReliabilityPanel");
    const engine = root.JIANGLAI_QUOTE_RELIABILITY;
    if (!box || !engine) return;
    const summary = engine.summarize(businessQuotes());
    const routeComparison = engine.routeComparison(record);
    const evidence = engine.costEvidence(record, record?.createdAt || new Date().toISOString());
    const hasActual = engine.hasActualCost(record);
    const canMaintainGolden = Boolean(record?.serverId && root.__hasPermission?.("quote.approve"));
    const canMaintainRoutes = Boolean(record?.serverId && root.__hasPermission?.("task.manage"));
    const golden = Boolean(record?.goldenSample?.approved);
    const validation = record?.goldenValidation || {};
    const errorText = summary.medianAbsoluteCostErrorPct === null
      ? "待积累" : `${summary.medianAbsoluteCostErrorPct.toFixed(1)}%`;
    const routeRows = (routeComparison.candidates || []).map(item => {
      const recommended = routeComparison.recommended_route && item.route === routeComparison.recommended_route;
      return `<div class="quote-route-row${recommended ? " recommended" : ""}">
        <span>${escapeHtml(item.label || item.route)}${recommended ? " · 推荐" : item.current ? " · 当前" : ""}</span>
        <strong>¥${Number(item.total_cost || 0).toFixed(2)}${Number(item.delivery_days || 0) > 0 ? ` · ${Number(item.delivery_days)}天` : " · 交期待核"}</strong>
        <span>${escapeHtml(item.source || "已核对成本")}</span>
        ${canMaintainRoutes && !item.current ? `<button type="button" onclick="removeCurrentQuoteRouteCandidate('${escapeHtml(item.route)}')">移除</button>` : ""}
      </div>`;
    }).join("");
    box.innerHTML = `
      <div class="quote-reliability-head"><div><strong>报价可靠性闭环</strong><div class="quote-reliability-note">成交后补实际成本，老板批准标准样本；新报价偏离同规格样本时自动拦截审批。</div></div><span class="quote-reliability-badge ${summary.level === "verified" ? "verified" : ""}">${escapeHtml(summary.label)}</span></div>
      <div class="quote-reliability-metrics">
        <div><span>成交成本补录</span><strong>${summary.actualCostQuotes}/${summary.wonQuotes || 0} · ${summary.completionRate.toFixed(0)}%</strong></div>
        <div><span>待补实际成本</span><strong>${summary.pendingActualCostQuotes} 笔</strong></div>
        <div><span>标准回归样本</span><strong>${summary.goldenSamples} 笔</strong></div>
        <div><span>成本误差中位数</span><strong>${errorText}</strong></div>
      </div>
      ${record ? `<div class="quote-cost-evidence ${evidence.requiresApproval ? "needs-review" : "verified"}">
        <strong>${escapeHtml(evidence.label)}</strong>
        <span>${escapeHtml(evidence.reason)}</span>
      </div>` : ""}
      ${record ? `<div class="quote-reliability-actions">
        ${hasActual ? (canMaintainGolden ? `<button type="button" onclick="setCurrentQuoteGoldenSample(${golden ? "false" : "true"})">${golden ? "取消标准样本" : "设为标准样本"}</button>` : `<span class="quote-reliability-note">${golden ? "✓ 已批准为标准样本" : "只有老板或报价审批人可批准标准样本"}</span>`) : `<span class="quote-reliability-note">${record.outcomeStatus === "已成交" ? "本单尚未补齐实际成本，不能成为标准样本。" : "本单成交并补齐实际成本后，才可批准为标准样本。"}</span>`}
        ${validation.status === "warning" ? `<span class="quote-reliability-note">⚠ ${escapeHtml(validation.reason || "偏离标准样本")}</span>` : validation.status === "passed" ? `<span class="quote-reliability-note">✓ 已通过 ${Number(validation.sample_count || 0)} 笔同规格标准样本回归</span>` : ""}
      </div>
      <div class="quote-route-comparison">
        <h4>生产路线成本择优</h4>
        <div class="quote-route-grid">${routeRows || `<div class="quote-reliability-note">当前报价尚无可比较的成本快照。</div>`}</div>
        <div class="quote-reliability-note">${escapeHtml(routeComparison.note || "只比较已核对的真实成本。")}</div>
        ${canMaintainRoutes ? `<div class="quote-route-entry">
          <select id="quoteRouteCandidateType"><option value="digital">数码生产</option><option value="offset">胶印生产</option><option value="gang">本厂拼版</option><option value="fixed">本厂固定版</option><option value="outsourced">外发采购</option></select>
          <input id="quoteRouteCandidateCost" type="number" min="0.01" step="0.01" placeholder="核对后总成本">
          <input id="quoteRouteCandidateDays" type="number" min="0" max="365" step="1" placeholder="交期天数">
          <input id="quoteRouteCandidateSource" maxlength="120" placeholder="依据：供应商/机台">
          <input id="quoteRouteDeadlineDays" type="number" min="0" max="365" step="1" value="${Number(routeComparison.deadline_days || 0) || ""}" placeholder="客户最晚天数">
          <button type="button" onclick="saveCurrentQuoteRouteCandidate()">核对并加入比选</button>
        </div>` : ""}
      </div>` : ""}
    `;
  }

  async function setCurrentQuoteGoldenSample(approved) {
    const record = activeQuoteRecord();
    if (!record?.serverId) return notify("报价正在保存，请稍后再操作。");
    try {
      await saveQuoteReliabilityCloud(record, { action: "golden", approved: Boolean(approved), tolerance_pct: 12 });
      renderQuoteReliabilityPanel(record); renderQuoteHistory();
      notify(approved ? "已批准为标准样本；同规格新报价偏差过大会转老板审批。" : "已取消标准样本资格。");
    } catch (error) { notify(error.message || "标准样本保存失败"); }
  }

  async function persistCurrentQuoteRoutes(record, candidates, deadlineDays) {
    try {
      await saveQuoteReliabilityCloud(record, {
        action: "routes", candidates, deadline_days: Number(deadlineDays || 0)
      });
      renderQuoteReliabilityPanel(record);
      notify(record.routeComparison?.status === "ready" ? `路线比选完成，当前建议：${record.routeComparison.recommended_label}` : "路线成本已保存。");
    } catch (error) { notify(error.message || "生产路线保存失败"); }
  }

  function saveCurrentQuoteRouteCandidate() {
    const record = activeQuoteRecord();
    if (!record?.serverId) return notify("报价正在保存，请稍后再录入路线。");
    const route = val("quoteRouteCandidateType");
    const totalCost = Number(val("quoteRouteCandidateCost") || 0);
    const deliveryDays = Number(val("quoteRouteCandidateDays") || 0);
    const source = val("quoteRouteCandidateSource").trim();
    const deadlineDays = Number(val("quoteRouteDeadlineDays") || 0);
    if (!(totalCost > 0)) {
      document.getElementById("quoteRouteCandidateCost")?.focus();
      return notify("请填写已经核对过的路线总成本。");
    }
    if (!(deliveryDays >= 0 && deliveryDays <= 365)) {
      document.getElementById("quoteRouteCandidateDays")?.focus();
      return notify("交期天数须在 0 到 365 天之间。");
    }
    const candidates = (record.routeCandidates || []).filter(item => item.route !== route);
    candidates.push({ route, total_cost: totalCost, delivery_days: deliveryDays, source });
    persistCurrentQuoteRoutes(record, candidates, deadlineDays);
  }

  function removeCurrentQuoteRouteCandidate(route) {
    const record = activeQuoteRecord();
    if (!record?.serverId) return;
    persistCurrentQuoteRoutes(
      record,
      (record.routeCandidates || []).filter(item => item.route !== route),
      Number(record.routeComparison?.deadline_days || 0)
    );
  }

  function quoteActualProfitMetrics(revenue, materialCost, processCost, otherCost) {
    const total = Math.max(0, Number(revenue || 0));
    const costs = [materialCost, processCost, otherCost].map(value => Math.max(0, Number(value || 0)));
    const actualCost = costs.reduce((sum, value) => sum + value, 0);
    const actualProfit = total - actualCost;
    return { actualCost, actualProfit, actualMarginRate: total ? actualProfit / total * 100 : 0, hasCost: costs.some(value => value > 0) };
  }

  function renderQuoteOutcomeProfitPreview() {
    const box = document.getElementById("quoteOutcomeProfitPreview");
    if (!box) return;
    box.classList.toggle("is-hidden", root.__quoteOutcomeMode !== "已成交");
    if (root.__quoteOutcomeMode !== "已成交") return;
    const metrics = quoteActualProfitMetrics(val("quoteOutcomeTotal"), val("quoteOutcomeMaterialCost"), val("quoteOutcomeProcessCost"), val("quoteOutcomeOtherCost"));
    const record = activeQuoteRecord();
    const budgetCost = Number(record?.estimatedMaterialCost || 0) + Number(record?.estimatedProcessCost || 0) + Number(record?.estimatedOtherCost || 0);
    const costVariance = metrics.actualCost - budgetCost;
    box.innerHTML = metrics.hasCost ? `
      <div><span>实际总成本</span><strong>¥${metrics.actualCost.toFixed(2)}</strong></div>
      <div class="${metrics.actualProfit < 0 ? "warning" : ""}"><span>实际利润</span><strong>¥${metrics.actualProfit.toFixed(2)}</strong></div>
      <div class="${metrics.actualMarginRate < 12 ? "warning" : ""}"><span>实际利润率</span><strong>${metrics.actualMarginRate.toFixed(1)}%</strong></div>
      ${budgetCost > 0 ? `<div class="${costVariance > 0 ? "warning" : ""}"><span>较报价预算</span><strong>${costVariance > 0 ? "+" : ""}¥${costVariance.toFixed(2)}</strong></div>` : ""}` : `
      <div style="grid-column:1/-1"><span>实际成本可稍后补录</span><strong>成交时先保存也可以；订单结束后补材料、加工和其他成本，老板首页会得到真实利润。</strong></div>`;
  }

  Object.assign(root, {
    __saveQuoteReliabilityCloud: saveQuoteReliabilityCloud,
    renderQuoteReliabilityPanel,
    setCurrentQuoteGoldenSample,
    saveCurrentQuoteRouteCandidate,
    removeCurrentQuoteRouteCandidate,
    quoteActualProfitMetrics,
    renderQuoteOutcomeProfitPreview
  });
})(typeof globalThis !== "undefined" ? globalThis : this);
