'use strict';
// Fixed field boundaries keep extraction deterministic; raw title stays on the event.
const summaryKeys={'机芯号':'coreNo','产品型号':'productModel','客户简称':'customerShort','出货方式':'shippingMethod','总数量':'totalQuantity','订单类别':'orderCategory'};
const retained=new Set(['订单号',...Object.keys(summaryKeys)]);
function extractTitle(title){
const raw=typeof title==='string'?title:'';
const text=raw.replace(/
/gi,'\n').replace(/ | | /gi,' ');
const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|出货方式|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
const orders=[],factoryHints=[],issues=[];let current=null,pendingMode=null,pendingAmbiguous=false;
for(let i=0;iindex>i&&m[1]==='订单号');
const between=nextOrder<0?[]:matches.slice(i+1,nextOrder).map(m=>m[1]);
// Summary fields after a mode still belong to the current order, irrespective
// of line wrapping. Only a header with no intervening summary binds forward.
const startsParagraph=/[\n|]\s*$/.test(text.slice(0,match.index));
const hasOwnSummary=between.some(label=>Object.hasOwn(summaryKeys,label));
const forward=nextOrder>=0&&!hasOwnSummary&&(between.includes('毛利')||startsParagraph);
if(current&&nextOrder>=0&&!hasOwnSummary&&!forward){
// An unmarked boundary cannot establish which adjacent order owns the mode.
current.businessModeAmbiguous=true;pendingMode=value;pendingAmbiguous=true;
}
else if(!current||forward){
if(pendingMode&&pendingMode!==value)pendingAmbiguous=true;
pendingMode=value;
}
else if(current){if(current.businessMode&¤t.businessMode!==value)current.businessModeAmbiguous=true;current.businessMode=value;}
}
if(current&&retained.has(label)){current.text+=`${label}:${value}`;if(summaryKeys[label])current[summaryKeys[label]]=value;}
}
if(!orders.length)issues.push('标题中没有可识别的“订单号:”段落');
return {rawTitle:raw,orders,brief:orders.map(order=>order.text).join('\n'),factoryHints,issues};
}
module.exports={extractTitle};