(() => {
  const root=document.getElementById("portalRoot"), token=new URLSearchParams(location.search).get("token")||"";
  const esc=value=>String(value??"").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
  const money=value=>`¥${Number(value||0).toLocaleString("zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2})}`;
  async function request(path,options={}){const response=await fetch(path,{...options,headers:{"Content-Type":"application/json"}});const data=await response.json().catch(()=>({}));if(!response.ok||data.ok===false)throw new Error(data.error||"链接无效或已过期");return data}
  async function load(){try{const data=await request(`/api/public/order-portal/${encodeURIComponent(token)}`);render(data)}catch(error){root.innerHTML=`<div class="portal-error"><h2>暂时无法查看</h2><p>${esc(error.message)}</p><p>请联系业务人员重新发送有效链接。</p></div>`}}
  function render(data){root.innerHTML=`<header class="portal-head"><small>将莱数字员工 · 客户订单中心</small><h1>${esc(data.title)}</h1><div>${esc(data.customer)} · 当前状态：${esc(data.status)}</div></header><div class="portal-grid"><div class="portal-stat"><span>计划交期</span><strong>${esc(data.due||"待确认")}</strong></div><div class="portal-stat"><span>已生产 / 已发货</span><strong>${esc(data.delivery.finished_quantity)} / ${esc(data.delivery.shipped_quantity)}</strong></div><div class="portal-stat"><span>待结金额</span><strong>${money(data.payment.outstanding_amount)}</strong></div></div><section class="portal-card"><h2>生产进度</h2><div class="portal-steps">${data.production_steps.map(step=>`<div class="portal-step ${step.completed?"done":""}">${step.completed?"✓":"○"} ${esc(step.label)}</div>`).join("")||"生产工序正在整理"}</div></section><section class="portal-card"><h2>交付与财务</h2><p>物流单号：${esc(data.delivery.tracking_no||"尚未发货")}</p><p>订单金额：${money(data.payment.order_amount)}　已收：${money(data.payment.received_amount)}　发票：${esc(data.payment.invoice_status)}</p></section><section class="portal-card"><h2>在线确认</h2><input id="portalContact" placeholder="联系人（选填）"><textarea id="portalNote" rows="3" placeholder="申请修改时，请写清楚需要调整的内容"></textarea><div class="portal-actions"><button data-action="confirm_order">确认订单</button><button class="light" data-action="request_change">申请修改</button><button class="light" data-action="acknowledge_delivery">确认收货</button></div><div class="portal-message" id="portalMessage"></div></section>`}
  root.addEventListener("click",async event=>{const action=event.target.dataset.action;if(!action)return;event.target.disabled=true;try{const data=await request(`/api/public/order-portal/${encodeURIComponent(token)}/actions`,{method:"POST",body:JSON.stringify({action,contact:document.getElementById("portalContact").value,note:document.getElementById("portalNote").value})});document.getElementById("portalMessage").textContent=data.message;event.target.textContent="已提交"}catch(error){document.getElementById("portalMessage").textContent=error.message;event.target.disabled=false}});
  load();
})();
