(function (root) {
  "use strict";

  function factoryQuoteCalibrationSamples() {
    return (state.quoteHistory || []).filter(record =>
      record?.outcomeStatus === "已成交"
      && Number(record.estimatedCost || 0) > 0
      && Number(record.actualTotalCost || 0) > 0
    ).map((record, index) => {
      const lineItems = [];
      if (Number(record.estimatedMaterialCost || 0) > 0 && Number(record.actualMaterialCost || 0) > 0) {
        lineItems.push({
          id:"material", kind:"material", name:record.material || "材料",
          materialName:record.material || "材料",
          estimatedCost:Number(record.estimatedMaterialCost),
          actualCost:Number(record.actualMaterialCost)
        });
      }
      if (Number(record.estimatedProcessCost || 0) > 0 && Number(record.actualProcessCost || 0) > 0) {
        lineItems.push({
          id:"process", kind:"process", name:record.process || "生产工艺",
          processName:record.process || "生产工艺",
          estimatedCost:Number(record.estimatedProcessCost),
          actualCost:Number(record.actualProcessCost)
        });
      }
      return {
        id:record.quoteNo || `factory-order-${index + 1}`,
        status:"已成交", settled:true, source:"factory_actual_cost",
        productName:record.product || "定制产品",
        materialName:record.material || "", processName:record.process || "",
        estimatedCost:Number(record.estimatedCost),
        actualCost:Number(record.actualTotalCost),
        lineItems
      };
    });
  }

  function buildFactoryQuoteCalibration() {
    const engine = root.JIANGLAI_QUOTE_ACCURACY;
    if (!engine?.buildCalibration) return null;
    try {
      return engine.buildCalibration(factoryQuoteCalibrationSamples(), { generatedAt:new Date().toISOString() });
    } catch (error) {
      console.warn("factory quote calibration unavailable", error);
      return null;
    }
  }

  function calibrateFactoryQuoteCost(quote) {
    const engine = root.JIANGLAI_QUOTE_ACCURACY;
    const calibration = buildFactoryQuoteCalibration();
    if (!engine?.calibrateQuote || !calibration) {
      return { calibration, suggestion:null, autoApplied:false, factor:1, reason:"校准引擎尚未加载" };
    }
    try {
      const suggestion = engine.calibrateQuote(quote, calibration, { minimumConfidence:"medium" });
      const applied = suggestion.trace.filter(item => item.applied);
      const percent = Number(suggestion.comparison?.percent || 0);
      const allHighConfidence = applied.length > 0 && applied.every(item => item.confidence?.level === "high");
      const safeRange = Number.isFinite(percent) && Math.abs(percent) <= .25;
      const autoApplied = allHighConfidence && safeRange && Number(suggestion.calibrated?.totalCost || 0) > 0;
      return {
        calibration, suggestion, autoApplied,
        factor:autoApplied && Number(suggestion.original?.totalCost || 0) > 0
          ? Number(suggestion.calibrated.totalCost) / Number(suggestion.original.totalCost) : 1,
        reason:autoApplied ? "高置信实际成本样本已自动校准"
          : applied.length ? "已有参考样本，但置信度或调整幅度未达到自动应用标准"
            : "当前产品、材料或工艺的有效样本不足"
      };
    } catch (error) {
      console.warn("factory quote calibration failed", error);
      return { calibration, suggestion:null, autoApplied:false, factor:1, reason:error.message || "校准暂不可用" };
    }
  }

  function renderQuoteAccuracySummary(result) {
    const box = document.getElementById("quoteAccuracySummary");
    if (!box) return;
    const diagnostics = result?.calibration?.diagnostics || {};
    const suggestion = result?.suggestion;
    const usedSamples = Number(diagnostics.usedSamples || 0);
    const applied = suggestion?.trace?.filter(item => item.applied) || [];
    const topConfidence = applied[0]?.confidence?.label || "样本不足";
    if (!suggestion || !applied.length) {
      box.className = "quote-accuracy-summary is-learning";
      box.innerHTML = `<strong>本厂真实订单校准 · 正在学习</strong><span>已读取 ${usedSamples} 笔有实际成本的成交单。至少 5 笔相近订单可形成参考，达到 12 笔且波动稳定后才会自动校准；当前仍完全按本厂价格表计算。</span>`;
      return;
    }
    const before = Number(suggestion.comparison?.beforeTotal || 0);
    const after = Number(suggestion.comparison?.afterTotal || before);
    const percent = Number(suggestion.comparison?.percent || 0) * 100;
    box.className = `quote-accuracy-summary ${result.autoApplied ? "is-applied" : "is-reference"}`;
    box.innerHTML = `<strong>本厂真实订单校准 · ${result.autoApplied ? "已安全应用" : "仅作参考"}</strong><span>依据 ${usedSamples} 笔本厂已成交且补录实际成本的订单，匹配 ${applied.length} 个成本项，置信度：${escapeHtml(topConfidence)}。预算成本由 ¥${before.toFixed(2)} 建议为 ¥${after.toFixed(2)}（${percent >= 0 ? "+" : ""}${percent.toFixed(1)}%）。${escapeHtml(result.reason)}；原材料价和工艺价没有被修改。</span>`;
  }

  function renderQuoteMarketComparison(result) {
    const box = document.getElementById("quoteMarketComparison");
    if (!box) return;
    if (!result) {
      box.className = "quote-accuracy-summary is-learning";
      box.innerHTML = "<strong>同行同规格对比 · 等待报价</strong><span>生成报价后仅比较尺寸、材料、工艺、数量和税运口径一致的样本；市场售价不会自动写入本厂成本。</span>";
      return;
    }
    const channels = (result.channels || []).map(item => item.name).join("、");
    if (!result.exact) {
      const standard = result.standard || null;
      const market = result.market || null;
      if (result.directional && standard) {
        const reference = market?.totalPrice
          ? `${escapeHtml(market.source?.name || "公开市场")} ${escapeHtml(market.publicText || "")}，按1万件折合 ¥${Number(market.totalPrice).toFixed(2)}`
          : `${escapeHtml(market?.source?.name || "公开市场")}：${escapeHtml(market?.publicText || "尚无公开同规格价格")}`;
        box.className = "quote-accuracy-summary is-learning";
        box.innerHTML = `<strong>1 万件产品基准 · 已建档，非同规格不硬比</strong><span>标准测试：${escapeHtml(standard.specification || "")}；标准直接成本 ¥${Number(standard.totalDirectCost || 0).toFixed(2)}。${reference}。${escapeHtml(market?.comparability || "")}；不含利润、税和运费，不覆盖客户自定义价格。</span>`;
        return;
      }
      box.className = "quote-accuracy-summary is-learning";
      box.innerHTML = `<strong>同行同规格对比 · 暂无完全一致样本</strong><span>可复核渠道：${escapeHtml(channels || "等待补充")}。系统不会拿相似规格、促销价或含运价强行校准成本。</span>`;
      return;
    }
    const benchmark = result.benchmark || {};
    const channel = result.channel || {};
    const difference = Number(result.difference || 0);
    const percent = Number(result.percent || 0) * 100;
    box.className = "quote-accuracy-summary is-reference";
    box.innerHTML = `<strong>同行同规格对比 · 仅作参考，不自动改价</strong><span>本厂内部成本 ¥${Number(result.internalCost || 0).toFixed(2)}；${escapeHtml(channel.name || "同行")}“${escapeHtml(benchmark.productLabel || "同规格产品")}”${escapeHtml(benchmark.priceType || "客户报价")} ¥${Number(result.marketTotal || 0).toFixed(2)}。本厂成本${difference >= 0 ? "高" : "低"} ¥${Math.abs(difference).toFixed(2)}（${percent >= 0 ? "+" : ""}${percent.toFixed(1)}%）。${benchmark.promotional ? "该样本为促销价；" : ""}${benchmark.freightIncluded ? "" : "运费未计；"}核对日期 ${escapeHtml(result.checkedAt || "")}。</span>`;
  }

  root.factoryQuoteCalibrationSamples = factoryQuoteCalibrationSamples;
  root.buildFactoryQuoteCalibration = buildFactoryQuoteCalibration;
  root.calibrateFactoryQuoteCost = calibrateFactoryQuoteCost;
  root.renderQuoteAccuracySummary = renderQuoteAccuracySummary;
  root.renderQuoteMarketComparison = renderQuoteMarketComparison;
})(typeof globalThis !== "undefined" ? globalThis : this);
