(() => {
  "use strict";
  const state = { tab:"warehouse", warehouse:null, finance:null, mes:null, portal:null, readiness:null };
  const labels = {
    receipt:"入库", issue:"领料", return:"退料", reserve:"预留", release:"释放", adjust:"调整",
    receivable:"应收", payable:"应付", waiting:"待排产", running:"生产中",
    paused:"已暂停", complete:"已完工", settled:"已结清", open:"未结清"
  };
  const esc = value => String(value ?? "").replace(/[&<>"']/g, char => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[char]));
  const money = value => `¥${Number(value || 0).toLocaleString("zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2})}`;
  const api = (path, options={}) => {
    if (typeof window.__jianglaiAppApi !== "function") throw new Error("服务正在初始化，请稍后再试");
    return window.__jianglaiAppApi(path, options);
  };
  const message = (text, ok=false) => {
    const node = document.getElementById("proMessage");
    if (!node) return;
    node.textContent = text || "";
    node.className = `pro-message ${text ? (ok ? "success" : "error") : ""}`;
  };
  const formData = form => Object.fromEntries(new FormData(form).entries());
  const post = async (path, body, success) => {
    message("正在保存…", true);
    try {
      const result=await api(path,{method:"POST",body:JSON.stringify(body)});
      message(success, true);
      await load(true);
      return result;
    } catch (error) { message(error.message); }
  };
  function metric(label, value) { return `<div class="pro-metric"><span>${esc(label)}</span><strong>${esc(value)}</strong></div>`; }
  function empty(text) { return `<div class="pro-empty">${esc(text)}</div>`; }
  function options(rows, label, selected="") {
    return rows.map(row => `<option value="${esc(row.id)}" ${String(row.id)===String(selected)?"selected":""}>${esc(label(row))}</option>`).join("");
  }
  function warehousePanel() {
    const data=state.warehouse||{summary:{},items:[],recent_movements:[]}, s=data.summary;
    return `<div class="pro-summary">${metric("物料种类",s.sku_count||0)}${metric("库存预警",s.low_stock_count||0)}${metric("库存总数",s.total_quantity||0)}${metric("已预留",s.reserved_quantity||0)}</div>
      <div class="pro-grid"><section class="pro-card"><h3>新建或更新物料</h3><p>设置安全库存后，系统会自动标记短缺。</p>
        <form class="pro-form" data-pro-form="item"><label>物料编码<input name="sku" required placeholder="PAPER-350"></label><label>物料名称<input name="name" required placeholder="白卡纸350g"></label><label>分类<input name="category" placeholder="纸张"></label><label>单位<input name="unit" value="kg"></label><label>安全库存<input name="safety_stock" type="number" min="0" step="0.001" value="0"></label><label>默认库位<input name="location" value="原料仓"></label><button class="pro-button wide">保存物料</button></form>
        <hr><h3>批次库存动作</h3><p>出库和预留按先进先出自动选择批次。</p>
        <form class="pro-form" data-pro-form="movement"><label class="wide">物料<select name="item_id" required><option value="">请选择</option>${options(data.items,r=>`${r.sku} · ${r.name}（可用${r.available}${r.unit}）`)}</select></label><label>动作<select name="type"><option value="receipt">采购入库</option><option value="reserve">订单预留</option><option value="issue">生产领料</option><option value="return">余料退库</option><option value="release">释放预留</option><option value="adjust">库存盘点（数量填实盘数）</option></select></label><label>数量/实盘数<input name="quantity" type="number" min="0" step=".001" required></label><label>批次号<input name="batch_no" placeholder="入库时可自动生成"></label><label>库位<input name="location" value="原料仓"></label><label>关联订单ID<input name="task_id" inputmode="numeric"></label><label>单据号<input name="reference"></label><button class="pro-button wide">执行库存动作</button></form>
      </section><section class="pro-card"><h3>实时库存</h3><p>现存量、预留量、可用量来自不可跳过的流水台账。</p><div class="pro-table-wrap"><table class="pro-table"><thead><tr><th>编码/物料</th><th>库位</th><th>现存</th><th>预留</th><th>可用</th><th>状态</th></tr></thead><tbody>${data.items.map(row=>`<tr><td><b>${esc(row.sku)}</b><br>${esc(row.name)}</td><td>${esc(row.default_location)}</td><td>${esc(row.quantity)} ${esc(row.unit)}</td><td>${esc(row.reserved)}</td><td>${esc(row.available)}</td><td><span class="pro-tag ${row.low_stock?"warn":"good"}">${row.low_stock?"需补货":"正常"}</span></td></tr>`).join("")||`<tr><td colspan="6">${empty("先建立第一种常用物料")}</td></tr>`}</tbody></table></div>
        <h3>最近流水</h3><div class="pro-table-wrap"><table class="pro-table"><tbody>${data.recent_movements.map(row=>`<tr><td>${esc(row.created_at)}</td><td>${esc(row.item_name)}</td><td>${esc(labels[row.movement_type]||row.movement_type)}</td><td>${row.quantity_delta>0?"+":""}${esc(row.quantity_delta)} ${esc(row.unit)}</td><td>${esc(row.operator)}</td></tr>`).join("")||`<tr><td>${empty("暂无库存流水")}</td></tr>`}</tbody></table></div></section></div>`;
  }
  function financePanel() {
    const data=state.finance||{summary:{receivable:{},payable:{}},documents:[],transactions:[]}, ar=data.summary.receivable||{}, ap=data.summary.payable||{};
    return `<div class="pro-summary">${metric("应收总额",money(ar.amount))}${metric("待收款",money(ar.outstanding))}${metric("应付总额",money(ap.amount))}${metric("待付款",money(ap.outstanding))}</div>
      <div class="pro-grid"><section class="pro-card"><h3>登记收付款</h3><p>系统已从订单和采购自动形成应收应付，收付款按流水追加，历史不可覆盖。</p><form class="pro-form" data-pro-form="transaction"><label class="wide">账款<select name="document_id" required><option value="">请选择</option>${options(data.documents.filter(r=>r.status!=="settled"),r=>`${labels[r.direction]} · ${r.counterparty} · 待结${money(r.amount-r.paid_amount)}`)}</select></label><label>金额<input name="amount" type="number" min=".01" step=".01" required></label><label>方式<select name="method"><option>银行转账</option><option>微信</option><option>支付宝</option><option>现金</option></select></label><label class="wide">备注<input name="note" placeholder="回单号或付款说明"></label><button class="pro-button wide">登记并更新余额</button></form>
        <hr><h3>新增独立账款</h3><form class="pro-form" data-pro-form="document"><label>方向<select name="direction"><option value="receivable">应收</option><option value="payable">应付</option></select></label><label>往来单位<input name="counterparty" required></label><label class="wide">账款名称<input name="title" required></label><label>金额<input name="amount" type="number" min=".01" step=".01" required></label><label>到期日<input name="due_date" type="date"></label><button class="pro-button wide">建立账款</button></form><hr><h3>开票登记</h3><form class="pro-form" data-pro-form="invoice"><label class="wide">应收账款<select name="document_id" required><option value="">请选择</option>${options(data.documents.filter(r=>r.direction==="receivable"),r=>`${r.counterparty} · ${r.title}`)}</select></label><label>发票号码<input name="invoice_no" required></label><label>开票金额<input name="amount" type="number" min=".01" step=".01" required></label><label>开票日期<input name="issued_at" type="date"></label><button class="pro-button">登记发票</button></form><hr><h3>往来对账</h3><form class="pro-form" data-pro-form="reconcile"><label>往来单位<input name="counterparty" required></label><label>方向<select name="direction"><option value="receivable">应收</option><option value="payable">应付</option></select></label><label>期间<input name="period" type="month"></label><label>对方确认金额<input name="statement_amount" type="number" min="0" step=".01" required></label><button class="pro-button wide">核对差额并留档</button></form></section>
      <section class="pro-card"><h3>应收应付台账</h3><p>订单、采购和手工账款集中核对。</p><div class="pro-table-wrap"><table class="pro-table"><thead><tr><th>方向</th><th>往来单位/事项</th><th>总额</th><th>已结</th><th>待结</th><th>状态</th></tr></thead><tbody>${data.documents.map(row=>`<tr><td><span class="pro-tag">${esc(labels[row.direction])}</span></td><td><b>${esc(row.counterparty)}</b><br>${esc(row.title)}</td><td>${money(row.amount)}</td><td>${money(row.paid_amount)}</td><td>${money(row.amount-row.paid_amount)}</td><td><span class="pro-tag ${row.status==="settled"?"good":"warn"}">${esc(labels[row.status])}</span></td></tr>`).join("")||`<tr><td colspan="6">${empty("成交订单后会自动形成账款")}</td></tr>`}</tbody></table></div></section></div>`;
  }
  function mesPanel() {
    const data=state.mes||{summary:{},work_centers:[],jobs:[]}, s=data.summary;
    return `<div class="pro-summary">${metric("待排产",s.waiting||0)}${metric("生产中",s.running||0)}${metric("已完工",s.completed||0)}${metric("综合良率",`${s.yield_rate??100}%`)}</div>
      <div class="pro-grid"><section class="pro-card"><h3>机台与产能</h3><form class="pro-form" data-pro-form="center"><label>机台编号<input name="code" required placeholder="YS-01"></label><label>机台名称<input name="name" required placeholder="海德堡印刷机"></label><label>每日工时<input name="daily_hours" type="number" min="1" max="24" value="8"></label><button class="pro-button">保存机台</button></form>
        <hr><h3>创建生产工单</h3><p>系统会避开已有任务，自动排到最早可用时段。</p><form class="pro-form" data-pro-form="job"><label class="wide">工作中心<select name="work_center_id" required><option value="">请选择</option>${options(data.work_centers,r=>`${r.code} · ${r.name}`)}</select></label><label>关联订单ID<input name="task_id" inputmode="numeric"></label><label>工序<input name="process_name" required placeholder="四色印刷"></label><label>计划数量<input name="target_quantity" type="number" min="0"></label><label>预计工时<input name="planned_hours" type="number" min=".1" step=".1" value="1"></label><label>最早开工<input name="requested_start" type="datetime-local"></label><button class="pro-button wide">自动排产并生成扫码工单</button></form></section>
      <section class="pro-card"><h3>扫码报工</h3><p>粘贴或扫描工单码，选择动作；良品、废品、质检结果自动回写订单。</p><form class="pro-form" data-pro-form="scan"><label class="wide">工单码<input name="scan_code" required autofocus placeholder="JL-MES-…"></label><label>动作<select name="action"><option value="start">开工</option><option value="good">良品报工</option><option value="scrap">废品报工</option><option value="pause">暂停</option><option value="quality_pass">质检合格</option><option value="quality_fail">质检不合格</option><option value="complete">完工</option></select></label><label>数量<input name="quantity" type="number" min="0" step="1" value="0"></label><label class="wide">备注<input name="note"></label><button class="pro-button wide">提交报工</button></form>
        <h3>生产队列</h3><div class="pro-table-wrap"><table class="pro-table"><thead><tr><th>工单/扫码码</th><th>机台工序</th><th>计划</th><th>良品/废品</th><th>状态</th></tr></thead><tbody>${data.jobs.map(row=>`<tr><td><b>${esc(row.job_no)}</b><br><button class="pro-button light" data-copy="${esc(row.scan_code)}">复制工单码</button></td><td>${esc(row.work_center_name)}<br>${esc(row.process_name)}</td><td>${esc(row.scheduled_start)}<br>至 ${esc(row.scheduled_end)}</td><td>${esc(row.good_quantity)} / ${esc(row.scrap_quantity)}</td><td><span class="pro-tag">${esc(labels[row.status]||row.status)}</span></td></tr>`).join("")||`<tr><td colspan="5">${empty("先建立机台，再创建第一张生产工单")}</td></tr>`}</tbody></table></div></section></div>`;
  }
  function portalPanel() {
    const data=state.portal||{links:[]};
    return `<div class="pro-grid"><section class="pro-card"><h3>生成客户自助链接</h3><p>客户只看到本订单的进度、交付、收款和发票状态，不会看到成本、利润、供应商或其他客户数据。</p><form class="pro-form" data-pro-form="portal"><label>订单ID<input name="task_id" required inputmode="numeric"></label><label>有效天数<input name="valid_days" type="number" min="1" max="90" value="14"></label><button class="pro-button wide">生成安全链接</button></form><div class="pro-help">客户可在线确认订单、提出修改、确认收货。所有操作会写入订单日志；链接到期即失效。</div></section>
      <section class="pro-card"><h3>已创建链接</h3><div class="pro-table-wrap"><table class="pro-table"><thead><tr><th>客户/订单</th><th>创建时间</th><th>到期</th><th>状态</th></tr></thead><tbody>${data.links.map(row=>`<tr><td><b>${esc(row.customer)}</b><br>${esc(row.title)}</td><td>${esc(row.created_at)}</td><td>${new Date(Number(row.expires_at)*1000).toLocaleDateString("zh-CN")}</td><td><span class="pro-tag ${Number(row.expires_at)*1000>Date.now()&&!row.revoked_at?"good":"warn"}">${Number(row.expires_at)*1000>Date.now()&&!row.revoked_at?"有效":"已失效"}</span></td></tr>`).join("")||`<tr><td colspan="4">${empty("尚未给客户创建自助链接")}</td></tr>`}</tbody></table></div></section></div>`;
  }
  function readinessPanel() {
    const data=state.readiness||{checks:{},ready_count:0,total_count:0,alerts:[]};
    const names={database_integrity:"数据库完整性",professional_tables:"专业模块结构",recent_local_backup:"最近本机备份",offsite_backup:"异地备份",external_monitoring:"外部监控告警",mac_code_signing:"Mac开发者签名",windows_code_signing:"Windows商业签名"};
    return `<div class="pro-summary">${metric("已通过检查",`${data.ready_count}/${data.total_count}`)}${metric("数据库",data.database==="ok"?"正常":"需处理")}${metric("最近备份",data.latest_backup?.name||"尚无")}${metric("未处理告警",data.alerts?.length||0)}</div><div class="pro-grid"><section class="pro-card"><h3>商用上线检查</h3><p>数据能力与外部服务分开显示，避免“功能能用”被误判为“已经完成商业签名和容灾”。</p><div class="pro-readiness">${Object.entries(names).map(([key,name])=>`<div class="pro-check"><span>${esc(name)}</span><b class="${data.checks?.[key]?"":"no"}">${data.checks?.[key]?"已就绪":"待配置"}</b></div>`).join("")}</div></section><section class="pro-card"><h3>恢复演练</h3><p>复制当前数据库并在副本上执行完整性检查，不修改正在使用的数据。</p><button class="pro-button" data-pro-action="drill">立即做一次安全恢复演练</button><div class="pro-help">异地备份、监控 Webhook 和代码签名需要正式云端地址及开发者证书，软件不会伪造“已完成”。配置后这里会自动转为已就绪。</div></section></div>`;
  }
  function render() {
    const root=document.getElementById("professionalSuiteRoot"); if(!root)return;
    root.innerHTML=`<div class="pro-shell"><header class="pro-hero"><div><h2>专业经营套件</h2><p>库存、财务、车间、客户协同和商用运维，共用同一套订单数据。</p></div><div class="pro-badge">模块化台账 · 全程可追溯</div></header><nav class="pro-tabs">${[["warehouse","仓库/WMS"],["finance","财务对账"],["mes","车间/MES"],["portal","客户自助"],["readiness","商用运维"]].map(([id,name])=>`<button data-pro-tab="${id}" class="${state.tab===id?"active":""}">${name}</button>`).join("")}</nav><div class="pro-panel active">${({warehouse:warehousePanel,finance:financePanel,mes:mesPanel,portal:portalPanel,readiness:readinessPanel}[state.tab])()}</div><div class="pro-message" id="proMessage"></div></div>`;
  }
  async function load(force=false) {
    if(!force&&state[state.tab]){render();return}
    try { state[state.tab]=await api(`/api/professional/${state.tab}`,{method:"GET"}); render(); }
    catch(error){render();message(error.message)}
  }
  document.addEventListener("click", async event => {
    const tab=event.target.closest("[data-pro-tab]"); if(tab){state.tab=tab.dataset.proTab;await load();return}
    const copy=event.target.closest("[data-copy]"); if(copy){await navigator.clipboard.writeText(copy.dataset.copy);message("工单码已复制",true);return}
    const action=event.target.closest("[data-pro-action]"); if(action?.dataset.proAction==="drill") await post("/api/professional/readiness/recovery-drill",{},"恢复演练通过");
  });
  document.addEventListener("submit", event => {
    const form=event.target.closest("[data-pro-form]"); if(!form)return; event.preventDefault();
    const body=formData(form), type=form.dataset.proForm;
    const routes={item:["/api/professional/warehouse/items","物料已保存"],movement:["/api/professional/warehouse/movements","库存流水已登记"],transaction:["/api/professional/finance/transactions","收付款已登记"],document:["/api/professional/finance/documents","账款已建立"],invoice:["/api/professional/finance/invoices","发票已登记并回写订单"],reconcile:["/api/professional/finance/reconcile","对账结果已留档"],center:["/api/professional/mes/work-centers","机台已保存"],job:["/api/professional/mes/jobs","生产工单已自动排产"],scan:["/api/professional/mes/scan","报工已同步到订单"],portal:["/api/professional/portal/links","客户链接已生成"]};
    const [path,success]=routes[type]||[]; if(!path)return;
    post(path,body,success).then(result=>{if(type==="portal"&&result?.link){const url=new URL(result.link.path,location.href).href;navigator.clipboard?.writeText(url);message(`客户链接已复制：${url}`,true)}});
  });
  window.__loadProfessionalSuite=load;
})();
