@agile-team/mach-report 2.3.2 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +40 -5
  2. package/dist/ReportPreview-CL9J9MEE.js +1907 -0
  3. package/dist/ReportPreview-DJvv3h8m.cjs +6 -0
  4. package/dist/grid-geometry-BNIvw52m.cjs +1 -0
  5. package/dist/{grid-geometry-Dw7BlENr.js → grid-geometry-C8hGoe9o.js} +10 -10
  6. package/dist/index.cjs +5 -5
  7. package/dist/index.d.cts +74 -0
  8. package/dist/index.d.ts +74 -0
  9. package/dist/index.js +946 -782
  10. package/dist/number-format-BA_KwrZe.js +55 -0
  11. package/dist/number-format-CZ2T_5kF.cjs +1 -0
  12. package/dist/pdf.cjs +1 -1
  13. package/dist/pdf.d.cts +6 -0
  14. package/dist/pdf.d.ts +6 -0
  15. package/dist/pdf.js +2 -2
  16. package/dist/{plugin-2lqgTX26.cjs → plugin-BkK2mm_p.cjs} +1 -1
  17. package/dist/{plugin-5R00MJQs.js → plugin-DRnvIbdP.js} +1 -1
  18. package/dist/render-plan-CCTL4F9v.cjs +1 -0
  19. package/dist/{render-plan-I9AHvQv7.js → render-plan-CXBWRog4.js} +12 -7
  20. package/dist/style.css +1 -1
  21. package/dist/vue/async.d.cts +598 -1
  22. package/dist/vue/async.d.ts +598 -1
  23. package/dist/vue/index.d.cts +820 -10
  24. package/dist/vue/index.d.ts +820 -10
  25. package/dist/vue-async.cjs +1 -1
  26. package/dist/vue-async.js +3 -3
  27. package/dist/vue.cjs +1 -1
  28. package/dist/vue.js +96 -73
  29. package/dist/xlsx.cjs +24 -24
  30. package/dist/xlsx.d.cts +209 -0
  31. package/dist/xlsx.d.ts +209 -0
  32. package/dist/xlsx.js +9805 -9284
  33. package/package.json +1 -1
  34. package/dist/ReportPreview-B-mwUSk9.cjs +0 -6
  35. package/dist/ReportPreview-DKjr4cwO.js +0 -1688
  36. package/dist/defaults-D4o0NCLo.js +0 -9
  37. package/dist/defaults-DOO1yHwx.cjs +0 -1
  38. package/dist/grid-geometry-bkciiZ4Q.cjs +0 -1
  39. package/dist/render-plan-CfJ3wf1l.cjs +0 -1
@@ -0,0 +1,6 @@
1
+ "use strict";var Zt=Object.create;var ft=Object.defineProperty;var Jt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var en=(t,n,l,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Xt(n))!_t.call(t,r)&&r!==l&&ft(t,r,{get:()=>n[r],enumerable:!(o=Jt(n,r))||o.enumerable});return t};var Ke=(t,n,l)=>(l=t!=null?Zt(Qt(t)):{},en(n||!t||!t.__esModule?ft(l,"default",{value:t,enumerable:!0}):l,t));const e=require("vue"),j=require("@agile-team/mach-report"),vt=require("./page-window-index-DEjnM6IB.cjs"),gt=require("./render-plan-CCTL4F9v.cjs"),de=require("./plugin-BkK2mm_p.cjs");function Je(t){return t==null?[]:Array.isArray(t)?t.map(String).filter(n=>n!==""):String(t).split(",").map(n=>n.trim()).filter(n=>n!=="")}function tn(t){return Je(t).join(",")}class $e extends Error{constructor(n){super(n),this.name="PlanLoadError"}}function nn(t={}){const{baseUrl:n="",headers:l,credentials:o,timeoutMs:r=3e4}=t,a=n.replace(/\/+$/,"");return async({url:s,method:d,params:v,signal:y})=>{let p=`${a}${s}`;if(v&&Object.keys(v).length>0){const w=p.indexOf("#"),B=w>=0?p.slice(w):"",P=w>=0?p.slice(0,w):p,R=P.indexOf("?"),C=R>=0?P.slice(0,R):P,S=new URLSearchParams(R>=0?P.slice(R+1):"");for(const[N,L]of Object.entries(v))S.set(N,L);p=`${C}?${S}${B}`}const m=(w,B)=>{const P=new $e(w);return Object.defineProperty(P,"cause",{value:B,configurable:!0,writable:!0}),P};if(y?.aborted)throw m(`请求已取消: ${s}`,y.reason);const b=new AbortController;let u;const E=()=>{b.signal.aborted||(u="external",b.abort(y?.reason))};y?.addEventListener("abort",E,{once:!0});const k=setTimeout(()=>{b.signal.aborted||(u="timeout",b.abort())},r);try{const w=await fetch(p,{method:d.toUpperCase(),headers:{Accept:"application/json",...l},credentials:o,signal:b.signal});if(!w.ok)throw new $e(`HTTP ${w.status} ${s}`);return await w.json()}catch(w){throw u==="timeout"?m(`请求超时(${r}ms): ${s}`,w):u==="external"?m(`请求已取消: ${s}`,w):w instanceof $e?w:m(`请求失败(${s}): ${w instanceof Error?w.message:String(w)}`,w)}finally{clearTimeout(k),y?.removeEventListener("abort",E)}}}function ht(t,n,l={}){const o=l.pxPerMm??3.7795275590551185,r=e.computed(()=>Math.max(0,e.unref(l.gapPx)??18)),a=e.ref(0),s=e.ref(800),d=e.computed(()=>{const w=t.value?.pages??[];return vt.createPageWindowIndex(w.map(B=>B.pageHeightMm*o),r.value)}),v=e.computed(()=>{let w=0;for(const B of t.value?.pages??[])w=Math.max(w,B.pageWidthMm*o);return{w,h:d.value.totalHeightPx}}),y=e.computed(()=>d.value.window(s.value/n.value,a.value/n.value,e.unref(l.overscan)??1)),p=e.computed(()=>{const w=t.value;if(!w)return[];const{start:B,end:P}=y.value;return w.pages.slice(B,P+1).map((R,C)=>({page:R,index:B+C}))});let m=0,b=!1;function u(w){w&&(a.value=w.scrollTop,s.value=w.clientHeight||800)}function E(w,B){return P=>{m||b||(m=requestAnimationFrame(()=>{if(m=0,b||(u(P),B.value<=0))return;const R=Math.max(0,P.scrollTop+32)/n.value;w.value=Math.min(B.value,d.value.pageAt(R)+1)}))}}function k(){b=!0,m&&cancelAnimationFrame(m),m=0}return e.onScopeDispose(k),{contentSize:v,windowRange:y,visiblePages:p,makeScrollHandler:E,refreshViewport:u,pageOffsetPx:w=>d.value.offsetAt(w),destroy:k}}function bt(t){const n=e.ref(1),l=e.ref("fit");let o=0;function r(){o&&cancelAnimationFrame(o),o=0}function a(){r(),o=requestAnimationFrame(()=>{if(o=0,l.value!=="fit")return;const d=t();!d?.viewport||d.viewport.clientWidth<=48||!Number.isFinite(d.pageWidthPx)||(n.value=Math.min(1,(d.viewport.clientWidth-48)/Math.max(1,d.pageWidthPx)))})}function s(d){if(d==="fit")l.value="fit",a();else{if(!Number.isFinite(d))return;r(),l.value="raw",n.value=Math.min(3,Math.max(.3,d/100))}}return e.getCurrentScope()&&e.onScopeDispose(r),{zoom:n,zoomMode:l,applyFitZoom:a,setZoom:s}}const Re=8;function Me(){return new Promise(t=>setTimeout(t,0))}function Be(t){return`p${t.pageWidthMm}x${t.pageHeightMm}`.replace(/[.+]/g,"_")}function Xe(t){const n=new Map;return t.pages.forEach(r=>{n.has(Be(r))||n.set(Be(r),r)}),`<!doctype html><html><head><meta charset="utf-8"><style>${`.mr-page{margin:0 auto;page-break-after:always;}
2
+ .mr-page tr{break-inside:avoid;page-break-inside:avoid;}
3
+ .mr-comp{break-inside:avoid;page-break-inside:avoid;}
4
+ ${[...n.values()].map(r=>`@page ${Be(r)}{size:${r.pageWidthMm}mm ${r.pageHeightMm}mm;margin:0;}`).join(`
5
+ `)}
6
+ body{margin:0;background:#fff;}`}</style></head><body>`}function Qe(t){const n=j.renderPage(t,96,{},document);return n.style.page=Be(t),n.outerHTML}function _e(t){return{head:Xe(t),pageChunks:t.pages.map(Qe)}}async function rn(t,n={}){const l={schemaVersion:"mach-report-batch-print",pages:t.flatMap(s=>s.pages)};if(l.pages.length===0)return;const o=Xe(l),r=document.createElement("iframe");r.style.cssText="position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;",document.body.appendChild(r);let a=!1;try{const s=r.contentDocument;s.open(),s.write(o);for(let d=0;d<l.pages.length;d++)s.write(Qe(l.pages[d])),d%Re===Re-1&&(n.onProgress?.(d+1,l.pages.length),await Me());s.write("</body></html>"),s.close(),await Me(),n.onProgress?.(l.pages.length,l.pages.length),a=!0,r.contentWindow?.focus(),r.contentWindow?.print()}catch(s){n.onError?.(s instanceof Error?`批量打印失败: ${s.message}`:"批量打印失败")}finally{a?setTimeout(()=>r.remove(),6e4):r.remove()}}function yt(t){const{head:n,pageChunks:l}=_e(t);return{html:`${`<!doctype html><html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"><!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom></w:WordDocument></xml><![endif]-->${n.replace(/^<!doctype html><html><head>/,"")}`}${l.join("")}</body></html>`,filename:"mach-report.doc"}}function wt(t,n){let l=null,o=!1,r=!1,a=0;const s=new Map,d=new Map;let v=null,y=null,p=null,m=null,b=null;function u(c,f){return!r&&t.value===c&&a===f}function E(){if(r)return;const c=[...s.values()].reverse().find(f=>u(f.plan,f.epoch))?.format??null;c!==v&&(v=c,n.onBusy?.(c))}function k(c,f,x){const $={};return s.set($,{plan:c,epoch:f,format:x}),E(),$}function w(c){s.delete(c),E()}function B(){for(const[c,f]of d)u(f.plan,f.epoch)||(c.close(),d.delete(c))}function P(){a++,C(),E(),B()}const R=e.watch(t,P,{flush:"sync"});function C(){l?.remove(),l=null}function S(){r=!0,a++,R(),C(),B(),s.clear(),n.onPrinting?.(!1)}function N(c,f){const x=URL.createObjectURL(c);setTimeout(()=>URL.revokeObjectURL(x),1e4);const $=document.createElement("a");$.href=x,$.download=f,$.click()}async function L(){if(o)return;const c=t.value;if(r||!c||c.pages.length===0)return;const f=a;o=!0,n.onPrinting?.(!0),C();const x=Xe(c);l=document.createElement("iframe"),l.style.cssText="position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden;",document.body.appendChild(l);const $=l;try{const M=$.contentDocument;M.open(),M.write(x);for(let z=0;z<c.pages.length;z++)if(M.write(Qe(c.pages[z])),z%Re===Re-1&&await Me(),$!==l)return;if(M.write("</body></html>"),M.close(),await Me(),!u(c,f)||$!==l)return;$.contentWindow?.focus(),$.contentWindow?.print()}catch{$===l&&C(),u(c,f)&&n.onError("调用打印失败,请改用导出 PDF","print")}finally{o=!1,r||n.onPrinting?.(!1)}}function U(c,f){if(y?.plan===c&&y.epoch===f)return y.promise;const x=Promise.resolve().then(()=>{if(!u(c,f))throw new Error("报表已切换或卸载");return n.getPdfExporter()(c,$=>{u(c,f)&&n.onWarning?.($)})}).finally(()=>{y?.promise===x&&(y=null)});return y={plan:c,epoch:f,promise:x},x}async function K(){const c=t.value;if(r||!c||c.pages.length===0)return;const f=a;if(p?.plan===c&&p.epoch===f)return p.promise;const x=k(c,f,"PDF"),$=(async()=>{try{const M=await U(c,f);if(!u(c,f))return;N(new Blob([M],{type:"application/pdf"}),"mach-report.pdf")}catch(M){u(c,f)&&n.onError(M instanceof Error?`PDF 导出失败: ${M.message}`:"PDF 导出失败","pdf")}finally{w(x),p?.token===x&&(p=null)}})();return p={plan:c,epoch:f,promise:$,token:x},$}async function W(){const c=t.value;if(r||!c||c.pages.length===0)return;const f=a;if(m?.plan===c&&m.epoch===f)return m.promise;const x={...n.getXlsxOptions?.()},$=k(c,f,"Excel"),M=(async()=>{try{const{renderPlanToXlsx:z}=await import("@agile-team/mach-report/xlsx");if(!u(c,f))return;const{buffer:G,warnings:Q}=await z(c,x);if(!u(c,f)||(Q.length>0&&n.onWarning?.(`Excel 导出有 ${Q.length} 条提示:${Q.slice(0,2).join(";")}`),!u(c,f)))return;N(new Blob([G],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),"mach-report.xlsx")}catch(z){u(c,f)&&n.onError(z instanceof Error?`Excel 导出失败: ${z.message}`:"Excel 导出失败","export")}finally{w($),m?.token===$&&(m=null)}})();return m={plan:c,epoch:f,promise:M,token:$},M}async function ee(){const c=t.value;if(r||!c||c.pages.length===0)return;const f=a;if(b?.plan===c&&b.epoch===f)return b.promise;const x=k(c,f,"图片"),$=(async()=>{try{const{blobs:M}=await j.renderPlanToImages(c,{dpr:Math.min(2,typeof devicePixelRatio=="number"?devicePixelRatio:1)});if(!u(c,f))return;M.forEach((z,G)=>{N(z,M.length>1?`mach-report-page-${G+1}.png`:"mach-report.png")})}catch(M){u(c,f)&&n.onError(M instanceof Error?`图片导出失败: ${M.message}`:"图片导出失败","export")}finally{w(x),b?.token===x&&(b=null)}})();return b={plan:c,epoch:f,promise:$,token:x},$}function O(){const c=t.value;if(!(r||!c||c.pages.length===0))try{const{html:f,filename:x}=yt(c);N(new Blob([f],{type:"application/msword;charset=utf-8"}),x)}catch(f){n.onError(f instanceof Error?`Word 导出失败: ${f.message}`:"Word 导出失败","export")}}async function ae(c){const f=t.value;if(!(r||!f||f.pages.length===0)){if(c==="pdf"){await K();return}if(c==="xlsx"||c==="excel"){await W();return}if(c==="png"||c==="image"){await ee();return}if(c==="word"||c==="doc"){O();return}if(c!=="html"){n.onError(`不支持的导出格式:${c}`,"export");return}try{const{head:x,pageChunks:$}=_e(f),M=`${x}${$.join("")}</body></html>`;N(new Blob([M],{type:"text/html;charset=utf-8"}),"mach-report.html")}catch(x){n.onError(x instanceof Error?`HTML 导出失败: ${x.message}`:"HTML 导出失败","export")}}}function H(){const c=t.value;if(r||!c||c.pages.length===0)return;const f=a,x=window.open("","_blank");if(!x){n.onError("浏览器拦截了弹窗,请允许弹窗后重试","pdf");return}d.set(x,{plan:c,epoch:f});const $=k(c,f,"PDF");U(c,f).then(M=>{if(!u(c,f)||x.closed){d.delete(x)&&x.close();return}const z=URL.createObjectURL(new Blob([M],{type:"application/pdf"}));setTimeout(()=>URL.revokeObjectURL(z),6e4);const G=x.document;G.title="PDF 预览",G.documentElement.style.height="100%",G.body.style.cssText="margin:0;height:100%;";const Q=G.createElement("iframe");Q.title="PDF 预览",Q.style.cssText="display:block;width:100%;height:100%;border:0;",Q.src=z,G.body.replaceChildren(Q),d.delete(x)}).catch(M=>{x.close(),d.delete(x),u(c,f)&&n.onError(M instanceof Error?`PDF 预览失败: ${M.message}`:"PDF 预览失败","pdf")}).finally(()=>w($))}return{print:L,exportAs:ae,exportImages:ee,exportWord:O,openPdfWindow:H,invalidatePending:P,releasePrintFrame:C,dispose:S}}const xt="mrp-hit";function on(t){t.querySelectorAll(`mark.${xt}`).forEach(l=>{const o=l.parentNode;if(o){for(;l.firstChild;)o.insertBefore(l.firstChild,l);l.remove(),o.normalize()}})}function an(t,n){const l=n.trim();if(!l)return 0;const o=l.toLowerCase(),r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(d){const v=d.parentElement;return!v||v.closest("mark")||/^(SCRIPT|STYLE)$/.test(v.tagName)?NodeFilter.FILTER_REJECT:(d.nodeValue??"").toLowerCase().includes(o)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}}),a=[];for(let d=r.nextNode();d;d=r.nextNode())a.push(d);let s=0;for(const d of a){const v=d.nodeValue??"",y=v.toLowerCase(),p=d.parentElement;if(!p)continue;const m=document.createDocumentFragment();let b=0,u=y.indexOf(o);for(;u>=0;){u>b&&m.appendChild(document.createTextNode(v.slice(b,u)));const E=document.createElement("mark");E.className=xt,E.textContent=v.slice(u,u+l.length),m.appendChild(E),s++,b=u+l.length,u=y.indexOf(o,b)}b<v.length&&m.appendChild(document.createTextNode(v.slice(b))),p.replaceChild(m,d)}return s}const ln=new Set(["line","rect","ellipse","chart"]);function*sn(t){for(const n of t.cells??[])for(const l of n??[])yield l?.text??"",yield*l?.children??[]}function*un(t){if(gt.isRichText(t))for(const n of t.richParagraphs)for(const l of n.segments??[])yield(l.kind==="field"?l.field:l.text)??"";else t.lines?.length?yield*t.lines:yield t.text??""}function*cn(t){const n=[t.values()];for(;n.length>0;){const l=n[n.length-1].next();if(l.done){n.pop();continue}const o=l.value;if(typeof o=="string"){yield o;continue}yield"",!gt.isImageBackedComponent(o)&&(o.kind==="text"?n.push(un(o)):o.grid?n.push(sn(o.grid)):ln.has(o.kind)||(yield o.fallbackText??""))}}function*dn(t){for(let n=0;n<t.pages.length;n++){for(const l of cn(t.pages[n].components))yield{text:l,pageIndex:n};yield{text:"",pageIndex:n}}}function fn(t,n){const l=t.toLowerCase();let o=0;for(let r=l.indexOf(n);r>=0;r=l.indexOf(n,r+n.length))o++;return o}function pn(t){const{plan:n,gotoPage:l,highlight:o,clearHighlights:r}=t,a=e.ref(!1),s=e.ref(""),d=e.ref(0),v=e.ref(0),y=e.ref(!1);let p=[];const m=e.computed(()=>{if(v.value===0)return null;const C=d.value;let S=0,N=p.length-1;for(;S<N;){const U=S+N>>>1;p[U].cumulative<=C?S=U+1:N=U}const L=p[S];return L?{pageIndex:L.pageIndex,occurrence:C-(p[S-1]?.cumulative??0)}:null});let b=null,u=null,E=0;function k(){E++,b&&clearTimeout(b),u&&clearTimeout(u),b=u=null,y.value=!1}function w(C){s.value=C,d.value=0,v.value=0,p=[],y.value=!1;const S=C.trim().toLowerCase(),N=n.value;if(!S||!N)return;y.value=!0;const L=E,U=dn(N),K=[];let W=0;function ee(){if(u=null,L!==E||N!==n.value)return;const O=performance.now();let ae=0;for(;ae<5e3&&performance.now()-O<4;){const H=U.next();if(H.done){p=K,v.value=W,y.value=!1,p[0]&&l(p[0].pageIndex+1);return}const c=fn(H.value.text,S);if(c>0){W+=c;const f=K[K.length-1];f?.pageIndex===H.value.pageIndex?f.cumulative=W:K.push({pageIndex:H.value.pageIndex,cumulative:W})}ae++}u=setTimeout(ee,0)}ee()}function B(C){if(k(),s.value=C,d.value=v.value=0,p=[],!C.trim()){w("");return}y.value=!0,b=setTimeout(()=>{b=null,w(C)},Math.max(0,e.unref(t.debounceMs)??200))}function P(C){const S=v.value;if(S===0||y.value)return;d.value=(d.value+C+S)%S;const N=m.value;N&&l(N.pageIndex+1)}function R(){k(),s.value="",d.value=v.value=0,p=[]}return e.watch(n,R,{flush:"sync"}),e.onScopeDispose(R),{visible:a,query:s,matchIndex:d,matchCount:v,activeMatch:m,searching:y,toggle:()=>{a.value=!a.value},onInput:B,onNav:P,apply:C=>{s.value.trim()&&o(C,s.value.trim())},clear:C=>{r(C)},reset:R}}function mn(t,n){const l=e.computed(()=>{if(t.value)return!0;if(typeof location>"u")return!1;try{return new URLSearchParams(location.search).get("mrp-debug")==="1"}catch{return!1}}),o=e.computed(()=>!l.value||!n.plan.value?0:Math.round(JSON.stringify(n.plan.value).length/1024)),r=e.computed(()=>!l.value||!n.plan.value?null:{pages:n.pageCount.value,window:`${n.windowRange.value.start}-${n.windowRange.value.end}`,zoom:`${Math.round(n.zoom.value*100)}%`,loadMs:`${n.loadMs.value}ms`,planKB:o.value});return{enabled:l,debugStats:r}}function vn(t,n){const{thumbsRoot:l,visible:o,renderThumbCanvas:r}=n,a=e.ref(0),s=e.ref(800),d=e.computed(()=>(t.value?.pages??[]).map(P=>Math.round(P.pageHeightMm/P.pageWidthMm*116))),v=e.computed(()=>vt.createPageWindowIndex(d.value.map(P=>P+20),8)),y=e.computed(()=>v.value.window(s.value,a.value,1)),p=e.computed(()=>{if(!o.value)return[];const{start:P,end:R}=y.value;return d.value.slice(P,R+1).map((C,S)=>({index:P+S,height:C}))});let m=0,b=0,u=!1;function E(){const P=l.value;P&&(a.value=P.scrollTop,s.value=P.clientHeight||800)}function k(){u||b||(b=requestAnimationFrame(()=>{b=0,E()}))}function w(){if(p.value,m&&cancelAnimationFrame(m),m=0,u||!o.value||!t.value||!l.value)return;E();const P=p.value,R=t.value,C=l.value;let S=0;function N(){if(m=0,!(u||!o.value||t.value!==R||l.value!==C)){for(let L=0;S<P.length&&L<2;L++,S++){const U=P[S].index,K=C.querySelector(`[data-thumb="${U+1}"]`);if(!K||K.childElementCount>0)continue;const W=r(U);W&&(W.style.width="100%",W.style.height="100%",W.style.display="block",K.appendChild(W))}S<P.length&&(m=requestAnimationFrame(N))}}m=requestAnimationFrame(N)}function B(){u=!0,m&&cancelAnimationFrame(m),b&&cancelAnimationFrame(b),m=b=0}return e.onScopeDispose(B),{schedule:w,destroy:B,onScroll:k,windowRange:y,visibleThumbs:p}}function gn(){const t=e.shallowRef(0);return{loadMs:t,start(){return typeof performance<"u"?performance.now():0},end(n){t.value=n?Math.round(performance.now()-n):0}}}const hn={class:"mrp-toolbar"},bn={class:"mrp-title"},yn=["disabled"],wn={class:"mrp-pageinfo"},xn=["disabled"],En=["disabled"],Pn={key:2,class:"mrp-search"},kn=["placeholder","value"],Cn={key:0,class:"mrp-search-count",role:"status"},$n=["disabled"],Bn=["disabled"],Sn=["disabled"],Rn=["disabled"],Mn=["disabled"],Fn=["disabled"],Dn=["disabled"],Tn=["disabled"],Nn=["disabled"],In=e.defineComponent({__name:"ReportToolbar",props:{pageCount:{},currentPage:{},zoomMode:{},zoom:{},showExport:{type:Boolean},showPrint:{type:Boolean},showPdfWindow:{type:Boolean},messages:{},search:{},thumbsVisible:{type:Boolean},showImport:{type:Boolean},busy:{type:Boolean}},emits:["goto","zoom","export","print","pdf-window","search-input","search-nav","search-toggle","thumbs-toggle","import-excel"],setup(t){const n=t,l=e.ref(null);e.watch(()=>n.search.visible,r=>{r&&e.nextTick(()=>l.value?.focus())});function o(r,a,s){return r.replace("{cur}",String(a)).replace("{total}",String(s))}return(r,a)=>(e.openBlock(),e.createElementBlock("div",hn,[e.createElementVNode("span",bn,e.toDisplayString(t.messages.title),1),t.pageCount>0?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{class:"mrp-nav",type:"button",disabled:t.currentPage<=1,onClick:a[0]||(a[0]=s=>r.$emit("goto",t.currentPage-1))},e.toDisplayString(t.messages.prevPage),9,yn),e.createElementVNode("span",wn,e.toDisplayString(o(t.messages.pageInfo,t.currentPage,t.pageCount)),1),e.createElementVNode("button",{class:"mrp-nav",type:"button",disabled:t.currentPage>=t.pageCount,onClick:a[1]||(a[1]=s=>r.$emit("goto",t.currentPage+1))},e.toDisplayString(t.messages.nextPage),9,xn)],64)):e.createCommentVNode("",!0),a[18]||(a[18]=e.createElementVNode("span",{class:"mrp-spacer"},null,-1)),t.showImport?(e.openBlock(),e.createElementBlock("button",{key:1,class:"mrp-nav mrp-import-excel",type:"button",disabled:t.busy,onClick:a[2]||(a[2]=s=>r.$emit("import-excel"))},e.toDisplayString(t.messages.importExcel??"导入 Excel 模板"),9,En)):e.createCommentVNode("",!0),t.search.visible?(e.openBlock(),e.createElementBlock("div",Pn,[e.createElementVNode("input",{ref_key:"searchInputRef",ref:l,class:"mrp-search-input",type:"text",placeholder:t.messages.searchPlaceholder,value:t.search.query,onInput:a[3]||(a[3]=s=>r.$emit("search-input",s.target.value))},null,40,kn),t.search.query?(e.openBlock(),e.createElementBlock("span",Cn,e.toDisplayString(t.search.searching?t.messages.searching??"搜索中…":o(t.messages.matchInfo,t.search.matchCount>0?t.search.matchIndex+1:0,t.search.matchCount)),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"mrp-nav",type:"button",disabled:t.search.matchCount===0,onClick:a[4]||(a[4]=s=>r.$emit("search-nav",-1))},e.toDisplayString(t.messages.prevMatch),9,$n),e.createElementVNode("button",{class:"mrp-nav",type:"button",disabled:t.search.matchCount===0,onClick:a[5]||(a[5]=s=>r.$emit("search-nav",1))},e.toDisplayString(t.messages.nextMatch),9,Bn)])):e.createCommentVNode("",!0),e.createElementVNode("button",{class:e.normalizeClass(["mrp-nav",{"mrp-active":t.search.visible}]),type:"button",title:"Ctrl+F",onClick:a[6]||(a[6]=s=>r.$emit("search-toggle"))}," 🔍 ",2),e.createElementVNode("button",{class:e.normalizeClass(["mrp-nav",{"mrp-active":t.thumbsVisible}]),type:"button",onClick:a[7]||(a[7]=s=>r.$emit("thumbs-toggle"))}," ▦ "+e.toDisplayString(t.messages.thumbnails),3),e.createElementVNode("button",{class:e.normalizeClass(["mrp-nav",{"mrp-active":t.zoomMode==="fit"}]),type:"button",onClick:a[8]||(a[8]=s=>r.$emit("zoom","fit"))},e.toDisplayString(t.messages.fitWidth),3),e.createElementVNode("button",{class:e.normalizeClass(["mrp-nav",{"mrp-active":t.zoomMode==="raw"&&Math.round(t.zoom*100)===100}]),type:"button",onClick:a[9]||(a[9]=s=>r.$emit("zoom",100))}," 100% ",2),e.createElementVNode("button",{class:e.normalizeClass(["mrp-nav",{"mrp-active":t.zoomMode==="raw"&&Math.round(t.zoom*100)===150}]),type:"button",onClick:a[10]||(a[10]=s=>r.$emit("zoom",150))}," 150% ",2),t.showExport?(e.openBlock(),e.createElementBlock("button",{key:3,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[11]||(a[11]=s=>r.$emit("export","html"))},e.toDisplayString(t.messages.exportHtml),9,Sn)):e.createCommentVNode("",!0),t.showExport?(e.openBlock(),e.createElementBlock("button",{key:4,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[12]||(a[12]=s=>r.$emit("export","pdf"))},e.toDisplayString(t.messages.exportPdf),9,Rn)):e.createCommentVNode("",!0),t.showExport?(e.openBlock(),e.createElementBlock("button",{key:5,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[13]||(a[13]=s=>r.$emit("export","xlsx"))},e.toDisplayString(t.messages.exportExcel),9,Mn)):e.createCommentVNode("",!0),t.showExport?(e.openBlock(),e.createElementBlock("button",{key:6,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[14]||(a[14]=s=>r.$emit("export","png"))},e.toDisplayString(t.messages.exportImage),9,Fn)):e.createCommentVNode("",!0),t.showExport?(e.openBlock(),e.createElementBlock("button",{key:7,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[15]||(a[15]=s=>r.$emit("export","word"))},e.toDisplayString(t.messages.exportWord),9,Dn)):e.createCommentVNode("",!0),t.showPrint?(e.openBlock(),e.createElementBlock("button",{key:8,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[16]||(a[16]=s=>r.$emit("print"))},e.toDisplayString(t.messages.print),9,Tn)):e.createCommentVNode("",!0),t.showPdfWindow?(e.openBlock(),e.createElementBlock("button",{key:9,class:"mrp-nav",type:"button",disabled:t.busy,onClick:a[17]||(a[17]=s=>r.$emit("pdf-window"))},e.toDisplayString(t.messages.pdfWindow),9,Nn)):e.createCommentVNode("",!0)]))}}),et=(t,n)=>{const l=t.__vccOpts||t;for(const[o,r]of n)l[o]=r;return l},Et=et(In,[["__scopeId","data-v-1c2568a7"]]),Vn={class:"mrp-params"},On={class:"mrp-params-title"},zn={class:"mrp-params-grid"},Ln={class:"mrp-param-label"},Wn={key:0,class:"mrp-param-star"},An=["value","onChange"],Hn={value:"",disabled:"",hidden:""},qn=["value"],jn=["type","placeholder","value","onInput"],Un={class:"mrp-params-actions"},Kn=e.defineComponent({__name:"ReportParamPanel",props:{defs:{},modelValue:{},messages:{},attempted:{type:Boolean}},emits:["update:modelValue","query","reset"],setup(t,{emit:n}){const l=t,o=n,r=e.ref({...l.modelValue});e.watch(()=>l.modelValue,v=>{r.value={...v}});const a=e.computed(()=>l.defs.map(v=>({def:v,label:v.label??v.field,value:r.value[v.field]??""})));function s(v,y){r.value={...r.value,[v]:y},o("update:modelValue",{...r.value})}function d(v){const y=l.defs.find(p=>p.field===v);return l.attempted&&y?.required===!0&&!(r.value[v]??"").trim()}return(v,y)=>(e.openBlock(),e.createElementBlock("div",Vn,[e.createElementVNode("span",On,e.toDisplayString(t.messages.paramsTitle),1),e.createElementVNode("div",zn,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,p=>(e.openBlock(),e.createElementBlock("label",{key:p.def.field,class:e.normalizeClass(["mrp-param",{"mrp-param-missing":d(p.def.field)}])},[e.createElementVNode("span",Ln,[e.createTextVNode(e.toDisplayString(p.label),1),p.def.required?(e.openBlock(),e.createElementBlock("i",Wn,"*")):e.createCommentVNode("",!0)]),(p.def.type??"text")==="select"?(e.openBlock(),e.createElementBlock("select",{key:0,class:"mrp-param-input",value:p.value,onChange:m=>s(p.def.field,m.target.value),onKeydown:y[0]||(y[0]=e.withKeys(m=>v.$emit("query"),["enter"]))},[e.createElementVNode("option",Hn,e.toDisplayString(p.def.placeholder??`请选择${p.label}`),1),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.def.options??[],m=>(e.openBlock(),e.createElementBlock("option",{key:m.value,value:m.value},e.toDisplayString(m.label),9,qn))),128))],40,An)):(e.openBlock(),e.createElementBlock("input",{key:1,class:"mrp-param-input",type:p.def.type==="number"?"number":p.def.type==="date"?"date":"text",placeholder:p.def.placeholder??`请输入${p.label}`,value:p.value,onInput:m=>s(p.def.field,m.target.value),onKeydown:y[1]||(y[1]=e.withKeys(m=>v.$emit("query"),["enter"]))},null,40,jn))],2))),128))]),e.createElementVNode("div",Un,[e.createElementVNode("button",{class:"mrp-nav mrp-param-query",type:"button",onClick:y[2]||(y[2]=p=>v.$emit("query"))},e.toDisplayString(t.messages.query),1),e.createElementVNode("button",{class:"mrp-nav",type:"button",onClick:y[3]||(y[3]=p=>v.$emit("reset"))},e.toDisplayString(t.messages.reset),1)])]))}}),Pt=et(Kn,[["__scopeId","data-v-aafce92d"]]),kt={title:"报表预览",prevPage:"‹ 上一页",nextPage:"下一页 ›",pageInfo:"{cur} / {total}",fitWidth:"适宽",exportHtml:"导出 HTML",exportPdf:"导出 PDF",exportExcel:"导出 Excel",exportImage:"导出图片",exportWord:"导出 Word",exporting:"正在生成 {format}…",print:"打印",pdfWindow:"PDF 窗口",loading:"报表渲染中…",empty:"暂无预览数据",errorPrefix:"",retry:"重试",pdfFontUnavailable:"PDF 字体尚未就绪,请联系管理员检查字体配置;预览及其它导出仍可使用。",searchPlaceholder:"搜索报表内容",matchInfo:"{cur}/{total}",prevMatch:"‹",nextMatch:"›",thumbnails:"缩略图",paramsTitle:"查询条件",query:"查 询",reset:"重 置",paramRequired:"请填写{label}",searching:"搜索中…",importExcel:"导入 Excel 模板",importing:"正在导入 Excel…",editCell:"编辑单元格",editingHint:"双击单元格编辑 · Enter 确认 · Esc 取消",saving:"正在保存修改…",editInvalidNumber:"请输入有效数字;清空表示无值",editInvalidBoolean:"请输入 true / false、是 / 否或 1 / 0",editConflict:"该单元格已变化,请重新打开编辑"},Ct={shellBg:"#525659",shellFg:"#e8e8e8",toolbarBg:"#323639",toolbarBorder:"#22252a",toolbarFg:"#e8e8e8",btnFg:"#cfcfcf",btnBorder:"#4a4d52",btnHoverBg:"#414549",btnHoverFg:"#ffffff",btnActiveBg:"#2d5fb8"};function $t(t={}){return{...t,defaults:t.defaults??{},presets:t.presets??{}}}function Gn(t){return t}const ie={showExport:!0,showPrint:!0,showPdfWindow:!0,showParams:!0,gapPx:18,pdfFontUrl:"/simhei.ttf",logger:console},Yn={warn:()=>{},info:()=>{}};function Se(t,n){return{...t,...n,theme:{...t?.theme,...n?.theme},messages:{...t?.messages,...n?.messages},preview:{...t?.preview,...n?.preview},xlsx:{...t?.xlsx,...n?.xlsx}}}function Bt(t,n){const l=n?t?.presets?.[n]:t?.defaultPreset?t?.presets?.[t.defaultPreset]:void 0,o=Se(t?.defaults,l);return{showExport:o.showExport??ie.showExport,showPrint:o.showPrint??ie.showPrint,showPdfWindow:o.showPdfWindow??ie.showPdfWindow,showParams:o.showParams??ie.showParams,gapPx:o.gapPx??ie.gapPx,pdfFontUrl:o.pdfFontUrl??ie.pdfFontUrl,theme:{...Ct,...o.theme},messages:{...kt,...o.messages},logger:o.logger??ie.logger,preview:{overscanPages:pt(o.preview?.overscanPages,1,10,!0),searchDebounceMs:pt(o.preview?.searchDebounceMs,200,2e3)},xlsx:{...o.xlsx},editable:o.editable??!1,excelImport:o.excelImport??!1}}function pt(t,n,l,o=!1){if(t==null||!Number.isFinite(t))return n;const r=Math.max(0,Math.min(l,t));return o?Math.floor(r):r}function St(t){const n={};return t.shellBg!=null&&(n["--mrp-shell-bg"]=t.shellBg),t.shellFg!=null&&(n["--mrp-shell-fg"]=t.shellFg),t.toolbarBg!=null&&(n["--mrp-toolbar-bg"]=t.toolbarBg),t.toolbarBorder!=null&&(n["--mrp-toolbar-border"]=t.toolbarBorder),t.toolbarFg!=null&&(n["--mrp-toolbar-fg"]=t.toolbarFg),t.btnFg!=null&&(n["--mrp-btn-fg"]=t.btnFg),t.btnBorder!=null&&(n["--mrp-btn-border"]=t.btnBorder),t.btnHoverBg!=null&&(n["--mrp-btn-hover-bg"]=t.btnHoverBg),t.btnHoverFg!=null&&(n["--mrp-btn-hover-fg"]=t.btnHoverFg),t.btnActiveBg!=null&&(n["--mrp-btn-active-bg"]=t.btnActiveBg),n}function Zn(t){const n=e.inject(de.MACH_REPORT_CONFIG_KEY,null),l=e.computed(()=>{const o=n?.value??null,r="defaults"in t||"presets"in t||"defaultPreset"in t?$t(t):{defaults:t,presets:{}};if(!o)return r;const a={...o.presets,...r.presets};for(const s of Object.keys(a))a[s]=Se(Se(o.presets[s],r.defaults),r.presets[s]);return{defaults:Se(o.defaults,r.defaults),presets:a,defaultPreset:r.defaultPreset??o.defaultPreset}});e.provide(de.MACH_REPORT_CONFIG_KEY,l)}function Rt(){return e.inject(de.MACH_REPORT_CONFIG_KEY,e.computed(()=>null))}const mt=new Map,ce=new Map,Jn=15e3;function Ze(t,n){return Object.assign(new Error(t),{cause:n})}function be(t,n){return`PDF 字体 ${JSON.stringify(t)}:${n}。请部署支持报表文字的字体文件,并将 pdfFontUrl 配置为可访问的字体 URL;西文报表可设为空串`}function Fe(t){if(t?.reason instanceof Error&&t.reason.name==="AbortError")return t.reason;const n=Ze("PDF 字体检查已取消",t?.reason);return n.name="AbortError",n}async function Xn(t,n){let l=!1;const o=setTimeout(()=>{l=!0,n.abort()},Jn);try{const r=await fetch(t,{method:"HEAD",signal:n.signal});if(n.signal.aborted)throw Fe(n.signal);if(r.status===405||r.status===501||r.type==="opaque")return{status:"unverified",fontUrl:t,message:`PDF 字体 ${JSON.stringify(t)} 无法通过 HEAD 检查验证;仍可尝试导出,届时会加载并校验字体`};if(!r.ok){const s=new Error(`字体请求返回 HTTP ${r.status}`);return{status:"error",fontUrl:t,message:be(t,s.message),cause:s}}const a=r.headers.get("content-type")??"";if(/text\/html|application\/xhtml\+xml/i.test(a)){const s=new Error("字体 URL 返回 HTML 页面(可能是 SPA 路由回退),不是字体文件");return{status:"error",fontUrl:t,message:be(t,s.message),cause:s}}if(/^text\//i.test(a)||/(?:\/|\+)json(?:\s*;|$)/i.test(a)){const s=new Error(`字体 URL 返回 ${a} 文本响应,不是字体文件`);return{status:"error",fontUrl:t,message:be(t,s.message),cause:s}}return{status:"available",fontUrl:t,message:"PDF 字体资源可达;文字覆盖范围将在实际导出时校验"}}catch(r){if(n.signal.aborted&&!l)throw Fe(n.signal);return{status:"error",fontUrl:t,message:be(t,l?"字体检查超时,请检查网络或字体服务":"字体检查失败,请检查网络、字体服务或跨域访问配置"),cause:r}}finally{clearTimeout(o)}}function Qn(t,n){if(n?.aborted)return Promise.reject(Fe(n));if(!t)return Promise.resolve({status:"disabled",fontUrl:t,message:"已停用自定义 PDF 字体;内置字体用于西文,其他文字会在导出时校验"});const l=mt.get(t);if(l)return Promise.resolve(l);let o=ce.get(t);if(!o){const a=new AbortController;o={controller:a,promise:Xn(t,a),subscribers:0};const s=o;ce.set(t,s),s.promise=s.promise.then(d=>(!a.signal.aborted&&d.status==="available"&&mt.set(t,d),d)).finally(()=>{ce.get(t)===s&&ce.delete(t)})}const r=o;return r.subscribers++,new Promise((a,s)=>{let d=!1;const v=()=>d?!1:(d=!0,r.subscribers--,n?.removeEventListener("abort",y),!0),y=()=>{v()&&(r.subscribers===0&&(ce.get(t)===r&&ce.delete(t),r.controller.abort()),s(Fe(n)))};n?.addEventListener("abort",y,{once:!0}),r.promise.then(p=>{v()&&a(p)},p=>{v()&&s(p)}),n?.aborted&&y()})}function Mt(t={fontUrl:"/simhei.ttf"}){let n=null;const l=async(o,r)=>{n||(n=await import("@agile-team/mach-report/pdf"));let a=null;if(t.fontUrl)try{if(a=await n.loadFontWithCache(t.fontUrl,{strict:!0}),!a?.byteLength)throw new Error("字体文件为空或加载失败")}catch(m){const b=m instanceof Error?m.message:String(m);throw Ze(be(t.fontUrl,b),m)}let s;try{s=await n.renderPlanToPdf(o,a?{customFontBytes:a}:{})}catch(m){if(!a)throw m;const b=m instanceof Error?m.message:String(m);throw Ze(`PDF 生成失败:${b}。当前字体 URL 为 ${JSON.stringify(t.fontUrl)};请确认该文件是有效字体,或重新配置 pdfFontUrl`,m)}const{bytes:d,unsupportedTextCount:v,pageErrors:y,fidelityWarnings:p}=s;if(v>0)throw new Error(`PDF 中有 ${v} 行文字无法编码;请部署支持所用文字的字体并配置 pdfFontUrl`);if(y.length>0)throw new Error(`PDF 有 ${y.length} 页渲染失败:${y[0]}`);return p.length>0&&r?.(`PDF 有 ${p.length} 处版式降级:${p.slice(0,2).join(";")}`),d};return l.checkFont=o=>Qn(t.fontUrl,o),l}class re extends Error{constructor(n,l,o){super(l),this.name="MachReportError",this.code=n,this.cause=o}}function Ft(t){return t instanceof re?{code:t.code,cause:t.cause}:{code:"render",cause:t}}function _n(t){const n=t.closest(".mrp-page-holder"),l=t.closest("[data-mr-component-index]");if(!n||!l)return null;const o={pageIndex:Number(n.dataset.page)-1,componentIndex:Number(l.dataset.mrComponentIndex),rowIndex:Number(t.dataset.mrRowIndex),columnIndex:Number(t.dataset.mrColumnIndex)};return Object.values(o).every(r=>Number.isInteger(r)&&r>=0)?o:null}function er(t,n,l){const o=t.ownerDocument.createElement("textarea");return o.className="mrp-cell-editor",o.setAttribute("aria-label",n),o.value=l==null?"":String(l),o.style.cssText="position:absolute;inset:0;width:100%;height:100%;min-height:20px;box-sizing:border-box;z-index:10;resize:none;margin:0;padding:2px 4px;border:2px solid #2563eb;outline:none;background:#fff;color:#111;font:inherit;line-height:1.25;white-space:pre-wrap;",t.appendChild(o),o}function tr(t){const n=e.shallowRef(null),l=e.ref(!1),o=e.shallowRef([]);let r=null;function a(){const u=n.value;n.value=null,l.value=!1,r=null,u?.controller.abort(),u?.input.remove()}function s(){a(),o.value=[]}function d(u){return n.value===u&&!u.controller.signal.aborted&&t.plan.value===u.plan}function v(u){const E=t.options.value,k=j.getReportCellContext(u.plan,u.address);if(!(typeof E=="object"?E===u.options:E===!0)||!k?.editable||u.options.canEdit?.(k)===!1)throw new j.ReportCellEditError("readonly")}async function y(u){try{v(u);const E=j.createReportCellEdit(u.plan,u.address,u.input.value);if(Object.is(E.value,E.previousValue))return a(),!0;const k={signal:u.controller.signal},w=await u.options.validate?.(structuredClone(E),k);if(!d(u))return!1;if(w)throw new Error(w);if(v(u),await u.options.save?.(structuredClone(E),k),!d(u))return!1;v(u);const B=j.applyReportCellEdit(u.plan,E);return a(),o.value=[...o.value,E],t.plan.value=B,t.onChange(structuredClone(E)),!0}catch(E){return d(u)&&(t.onError(t.errorMessage?.(E)??(E instanceof Error?E.message:"单元格保存失败"),E),u.input.disabled=!1,u.input.setAttribute("aria-invalid","true"),u.input.focus()),!1}finally{n.value===u&&(l.value=!1)}}async function p(){if(r)return r;const u=n.value;if(!u)return!0;if(!d(u))return a(),!1;l.value=!0,u.input.disabled=!0;const E=y(u);r=E;const k=await E;return r===E&&(r=null),k}function m(u){u.stopPropagation(),!u.isComposing&&(u.key==="Escape"&&(u.preventDefault(),a()),u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),p()))}async function b(u){if(!t.options.value||t.blocked())return;const E=u.target;if(!(E instanceof Element)||E.closest(".mrp-cell-editor"))return;const k=E.closest("td[data-mr-row-index]");if(!k||!await p()||!k.isConnected)return;const w=t.plan.value,B=_n(k);if(!w||!B||!t.options.value||t.blocked())return;const P=typeof t.options.value=="object"?t.options.value:{};try{const R=j.getReportCellContext(w,B);if(!R?.editable||P.canEdit?.(R)===!1)return;const C=er(k,t.label(),R.value);n.value={plan:w,address:B,input:C,controller:new AbortController,options:P},C.addEventListener("keydown",m),C.addEventListener("blur",()=>{l.value||p()}),C.focus(),C.select()}catch(R){t.onError(R instanceof Error?R.message:"无法编辑单元格",R)}}return e.watch(t.options,(u,E)=>{(!u||u!==E)&&a()},{flush:"sync"}),e.watch(t.plan,()=>{n.value&&t.plan.value!==n.value.plan&&a()},{flush:"sync"}),e.onScopeDispose(s),{active:n,saving:l,changes:o,cancel:a,reset:s,commit:p,onDoubleClick:b,getChanges:()=>structuredClone(o.value)}}const nr={key:2,class:"mrp-edit-hint",role:"status"},rr={key:4,class:"mrp-export-notice mrp-export-warning",role:"status"},or={class:"mrp-main"},ar={key:0,class:"mrp-state"},lr={key:1,class:"mrp-state mrp-error"},sr={key:2,class:"mrp-state"},ir=["data-page"],ur=["onClick"],cr=["data-thumb"],dr={class:"mrp-thumb-no"},fr={class:"mrp-overlay"},pr={key:5,class:"mrp-debug","aria-hidden":"true"},Ce=96/25.4,Ge="mach-report:ui",Ye="mach-report:ui:wide",mr=e.defineComponent({__name:"ReportPreview",props:{reportId:{type:[String,Array],default:null},params:{type:Object,default:()=>({})},height:{type:String,default:"100vh"},autoLoad:{type:Boolean,default:!0},showExport:{type:Boolean,default:void 0},showPrint:{type:Boolean,default:void 0},showPdfWindow:{type:Boolean,default:void 0},gapPx:{type:Number,default:void 0},messages:{type:Object,default:void 0},preset:{type:String,default:void 0},debug:{type:Boolean,default:!1},paramDefs:{type:Array,default:void 0},showParams:{type:Boolean,default:void 0},editable:{type:[Boolean,Object],default:void 0},excelImport:{type:[Boolean,Object],default:void 0},fetcher:{type:Function,default:null}},emits:["loaded","error","warning","cell-edit","template-import"],setup(t,{expose:n,emit:l}){e.useCssVars(i=>({v587d5a34:N.value+"px"}));const o=t,r=l,a=e.shallowRef(null),s=e.ref(!1),d=e.ref(""),v=e.shallowRef(null),y=e.ref(null),p=e.ref(!1),m=e.shallowRef(Object.freeze({status:"unchecked",fontUrl:""})),b=e.ref(null),u=e.ref(1),E=e.ref(null),k=e.ref(null),w=e.ref(null),B=e.ref(!1),P=e.ref(!1),R=e.ref(null),C=gn(),S=e.computed(()=>!!a.value?.pages.length&&a.value.pages.every(i=>i.layout==="wide")),N=e.computed(()=>Math.max(0,G.value));let L=Ge;const U=e.inject(de.MACH_REPORT_FETCHER_KEY,null),K=e.inject(de.MACH_REPORT_PDF_EXPORTER_KEY,null),W=e.computed(()=>Je(o.reportId)),ee=e.computed(()=>o.fetcher??U),O=e.computed(()=>a.value?.pages.length??0),ae=e.computed(()=>Object.freeze({loading:s.value,hasPlan:O.value>0,pageCount:O.value,currentPage:u.value,exporting:y.value,printing:p.value,canExport:!s.value&&!P.value&&!V.saving.value&&O.value>0&&y.value===null,canPrint:!s.value&&!P.value&&!V.saving.value&&O.value>0&&!p.value,error:v.value,pdfFont:m.value,editing:V.active.value!==null,saving:V.saving.value,importing:P.value,dirty:V.changes.value.length>0}));function H(i,g,h){v.value=Object.freeze({message:i,code:g,cause:h}),r("error",i,{code:g,cause:h})}const c=Rt(),f=e.computed(()=>Bt(c.value,o.preset)),x=e.computed(()=>({...f.value.messages,...o.messages})),$=e.computed(()=>o.showExport??f.value.showExport),M=e.computed(()=>o.showPrint??f.value.showPrint),z=e.computed(()=>o.showPdfWindow??f.value.showPdfWindow),G=e.computed(()=>o.gapPx??(S.value?0:f.value.gapPx)),Q=e.computed(()=>o.showParams??f.value.showParams),tt=e.computed(()=>o.editable??f.value.editable),ye=e.computed(()=>o.excelImport??f.value.excelImport);function Tt(i){return i instanceof j.ReportCellEditError?{number:x.value.editInvalidNumber,boolean:x.value.editInvalidBoolean,conflict:x.value.editConflict}[i.code]??i.message:i instanceof Error?i.message:"单元格保存失败"}const V=tr({plan:a,options:tt,blocked:()=>s.value||P.value||y.value!==null||p.value,label:()=>x.value.editCell??"编辑单元格",errorMessage:Tt,onChange:i=>{v.value=null,b.value=null,r("cell-edit",i)},onError:(i,g)=>{b.value={kind:"error",message:i},H(i,"edit",g)}});let nt=null,De=null;function rt(){if(K)return K;const i=f.value.pdfFontUrl;return(!De||nt!==i)&&(nt=i,De=Mt({fontUrl:i})),De}let we=0,fe=null,xe=null,te=!1;function Te(){we++,fe?.abort(),fe=null}async function Ee(){if(te)throw new re("config","报表预览已卸载");Te();const i=we,g=new AbortController;fe=g;const h=f.value.pdfFontUrl;m.value=Object.freeze({status:"checking",fontUrl:h});try{const T=rt(),D=T.checkFont?await T.checkFont(g.signal):{status:"unverified",fontUrl:"",message:"自定义 PDF 导出器未提供字体预检查;字体由宿主确认"};return!te&&i===we&&!g.signal.aborted&&(m.value=Object.freeze({...D})),D}catch(T){if(g.signal.aborted)throw T;const D={status:"error",fontUrl:h,message:T instanceof Error?T.message:"PDF 字体检查失败",cause:T};return!te&&i===we&&(m.value=Object.freeze(D)),D}finally{fe===g&&(fe=null)}}function Nt(){Ee().catch(()=>{})}e.watch([a,()=>f.value.pdfFontUrl,$,z],()=>{const i=m.value.fontUrl===f.value.pdfFontUrl;i&&m.value.status==="available"||(Te(),(!i||m.value.status==="checking")&&(m.value=Object.freeze({status:"unchecked",fontUrl:f.value.pdfFontUrl})),!te&&O.value>0&&($.value||z.value)&&Ee().catch(()=>{}))},{immediate:!0});const oe=e.computed(()=>o.paramDefs??ee.value?.getParamDefs?.(W.value)??[]),le=e.ref({}),Ne=e.ref(!1);function pe(i){const g={};for(const h of i)g[h.field]=o.params[h.field]??h.defaultValue??"";le.value=g,Ne.value=!1}pe(oe.value),e.watch(oe,i=>pe(i)),e.watch(W,()=>pe(oe.value)),e.watch(()=>JSON.stringify(o.params),()=>pe(oe.value));const It=e.computed(()=>{const i={...o.params};for(const[g,h]of Object.entries(le.value))h===""?delete i[g]:i[g]=h;return i});function Vt(){return oe.value.filter(i=>i.required===!0&&!(le.value[i.field]??"").trim())}function Ot(){Ne.value=!0;const i=Vt();if(i.length>0){const g=i[0].label??i[0].field,h=x.value.paramRequired.replace("{label}",g);d.value=h,H(h,"param");return}se()}function zt(){pe(oe.value)}const Lt=e.computed(()=>({height:o.height,...St(f.value.theme)})),{zoom:Y,zoomMode:me,applyFitZoom:ot,setZoom:ve}=bt(()=>({viewport:k.value,pageWidthPx:Ie.contentSize.value.w||210*Ce})),Ie=ht(a,Y,{pxPerMm:Ce,gapPx:G,overscan:e.computed(()=>f.value.preview.overscanPages)}),{contentSize:Ve,windowRange:ge,visiblePages:at,makeScrollHandler:Wt,refreshViewport:Oe}=Ie,At=Wt(u,O);function ze(i){ve(i*100)}function Pe(){P.value=!1,V.reset(),lt(),a.value=null,u.value=1,I.reset()}let A=0,J=null;async function se(){if(te)return;const i=++A;P.value=!1,J?.abort(),J=null;const g=ee.value;if(s.value=!1,v.value=null,W.value.length===0){d.value="缺少报表 ID",Pe(),H(d.value,"param");return}if(!g){d.value="未提供渲染数据源 fetcher",Pe(),H(d.value,"config");return}s.value=!0,d.value="",b.value=null,Pe();const h=C.start(),T=new AbortController;J=T;const D=new Set;function X(F){i!==A||T.signal.aborted||D.has(F)||(D.add(F),f.value.logger.warn("[mach-report] 报表告警:",F),r("warning",F))}try{const F=await g({reportIds:W.value,params:{...It.value},signal:T.signal,onWarning:X});if(i!==A)return;const q=j.validateRenderPlan(F);if(!q.ok){const ke=q.errors.slice(0,3).map(dt=>`${dt.path}: ${dt.message}`).join("; ");throw new re("validate",`渲染计划校验失败(${q.errors.length} 处): ${ke}`)}if(q.warnings.forEach(ke=>X(`${ke.path}: ${ke.message}`)),i!==A||T.signal.aborted)return;a.value=F,u.value=1,C.end(h),k.value&&(k.value.scrollTop=0,k.value.scrollLeft=0);const Z=S.value?Ye:Ge;Z!==L&&(L=Z,Ue()),me.value==="fit"&&ot(),r("loaded",F.pages.length)}catch(F){if(i!==A)return;const q=F instanceof re?F:F instanceof j.ReportSourceError?new re(F.code,F.message,F.cause):new re("fetch",F instanceof Error?F.message:"预览加载失败",F);d.value=q.message;const Z=Ft(q);H(q.message,Z.code,Z.cause)}finally{i===A&&(s.value=!1),J===T&&(J=null)}}function ne(i){if(te||O.value<=0)return;const g=Math.max(1,Math.min(O.value,i));u.value=g;const h=k.value;h&&(h.scrollTop=Ie.pageOffsetPx(g-1)*Y.value,Oe(h))}const he=wt(a,{getPdfExporter:rt,getXlsxOptions:()=>f.value.xlsx,onError:(i,g)=>{b.value={kind:"error",message:i},H(i,g??"print")},onWarning:i=>{b.value={kind:"warning",message:i},r("warning",i)},onBusy:i=>{y.value=i,i?b.value={kind:"progress",message:x.value.exporting.replace("{format}",i)}:b.value?.kind==="progress"&&(b.value=null)},onPrinting:i=>{p.value=i}}),{releasePrintFrame:lt,dispose:Ht}=he;async function Le(){s.value||P.value||V.active.value&&!await V.commit()||(v.value=null,await he.print())}async function We(i){s.value||P.value||V.active.value&&!await V.commit()||(v.value=null,await he.exportAs(i))}function Ae(){if(s.value||P.value||V.active.value){b.value={kind:"warning",message:x.value.editingHint??"请先确认单元格修改"};return}v.value=null,he.openPdfWindow()}async function st(i,g={}){te||(le.value={...le.value,...i},g.reload!==!1&&await se())}const qt={reload:se,print:Le,exportAs:We,openPdfWindow:Ae,gotoPage:ne,setParams:st,checkPdfFont:Ee,importExcel:He,getPlan:it,getChanges:V.getChanges,get state(){return ae.value}};e.provide(de.MACH_REPORT_CONTROLLER_KEY,qt);function it(){return a.value?structuredClone(a.value):null}async function He(i,g){if(te)throw new re("config","报表预览已卸载");const h=++A;J?.abort(),J=null,s.value=!1,V.cancel(),he.invalidatePending(),P.value=!0,v.value=null,b.value={kind:"progress",message:x.value.importing??"正在导入 Excel…"};try{const{importExcelTemplate:T}=await import("@agile-team/mach-report/xlsx");if(h!==A)return null;const D=typeof ye.value=="object"?ye.value:{},X=await T(i,{...D,...g,limits:{...D.limits,...g?.limits}});if(h!==A)return null;const F=j.paginateTemplate(structuredClone(X.template),{}).plan,q=j.validateRenderPlan(F);if(!q.ok)throw new Error(q.errors.map(Z=>Z.message).slice(0,3).join("; "));for(const Z of X.warnings){if(h!==A)return null;r("warning",Z)}return h!==A?null:(V.reset(),lt(),I.reset(),a.value=F,u.value=1,d.value="",b.value=X.warnings.length?{kind:"warning",message:X.warnings.join(";")}:null,k.value&&(k.value.scrollTop=0,k.value.scrollLeft=0),L=S.value?Ye:Ge,Ue(),r("template-import",X),h===A&&r("loaded",F.pages.length),X)}catch(T){if(h!==A)return null;const D=new re("import",T instanceof Error?T.message:"Excel 模板导入失败",T);throw b.value={kind:"error",message:D.message},H(D.message,"import",T),D}finally{h===A&&(P.value=!1)}}function jt(i){const g=i.target,h=g.files?.[0];g.value="",h&&He(h).catch(()=>{})}const I=pn({plan:a,gotoPage:ne,debounceMs:e.computed(()=>f.value.preview.searchDebounceMs),highlight:an,clearHighlights:on});function Ut(i){i.ctrlKey&&(i.preventDefault(),ze(Y.value*(i.deltaY<0?1.1:1/1.1)))}function Kt(i){if(!(i.target instanceof Element&&i.target.closest("input,textarea,select,[contenteditable='true']"))){if((i.ctrlKey||i.metaKey)&&i.key.toLowerCase()==="f"){i.preventDefault(),I.visible.value||I.toggle();return}switch(i.key){case"PageDown":i.preventDefault(),ne(u.value+1);break;case"PageUp":i.preventDefault(),ne(u.value-1);break;case"Home":i.preventDefault(),ne(1);break;case"End":i.preventDefault(),ne(O.value);break;case"+":case"=":i.preventDefault(),ze(Y.value*1.1);break;case"-":i.preventDefault(),ze(Y.value/1.1);break}}}function Gt(){try{localStorage.setItem(L,JSON.stringify({zoomMode:me.value==="fit"?"fit":Math.round(Y.value*100)}))}catch{}}e.watch([me,Y],Gt);let qe="";const ut=new WeakMap;function ct(i=!1){const g=I.activeMatch.value;if(!S.value||!g)return;const h=`${I.query.value}:${I.matchIndex.value}:${g.pageIndex}`;if(!i&&h===qe)return;const D=E.value?.querySelector(`[data-page="${g.pageIndex+1}"]`)?.querySelectorAll("mark.mrp-hit")[g.occurrence];D&&(D.scrollIntoView?.({block:"nearest",inline:"nearest"}),qe=h)}e.watchEffect(()=>{const i=a.value;if(!i)return;const g=I.activeMatch.value;I.matchIndex.value,g||(qe=""),at.value;const h=E.value;if(!h)return;h.querySelectorAll(".mrp-page-holder").forEach(D=>{const X=Number(D.dataset.page??0)-1,F=i.pages[X];if(!F||D.childElementCount>0&&ut.get(D)===F){if(D.firstElementChild){const Z=D.firstElementChild;I.clear(Z),I.apply(Z)}return}D.style.width=`${F.pageWidthMm*Ce}px`;const q=j.renderPage(F,96,{},document);I.apply(q),D.replaceChildren(q),ut.set(D,F)}),ct()},{flush:"post"}),e.watch(()=>I.query.value,i=>{i||E.value?.querySelectorAll(".mrp-page-holder").forEach(g=>{I.clear(g)})});const _=vn(a,{thumbsRoot:w,visible:B,renderThumbCanvas:i=>{try{const g=a.value.pages[i],h=Math.min(.2,116/Math.max(1,g.pageWidthMm*Ce)),{canvases:T}=j.renderPlanToCanvas(a.value,{start:i,end:i,dpr:h});return T[0]??null}catch{return null}}});e.watchEffect(()=>{_.schedule()},{flush:"post"});const Yt=e.computed(()=>o.debug),{debugStats:ue}=mn(Yt,{plan:a,pageCount:O,windowRange:ge,zoom:Y,loadMs:C.loadMs});function je(){Oe(k.value),_.schedule(),me.value==="fit"&&ot(),ct(!0)}function Ue(){ve(L===Ye?100:"fit");try{const i=JSON.parse(localStorage.getItem(L)??"{}");i.zoomMode==="fit"?ve("fit"):typeof i.zoomMode=="number"&&ve(i.zoomMode)}catch{}}return e.onMounted(()=>{window.addEventListener("resize",je),typeof ResizeObserver<"u"&&k.value&&(xe=new ResizeObserver(je),xe.observe(k.value)),Oe(k.value),Ue(),o.autoLoad&&se()}),e.onUnmounted(()=>{te=!0,V.reset(),P.value=!1,Te(),A++,J?.abort(),J=null,window.removeEventListener("resize",je),xe?.disconnect(),xe=null,_.destroy(),I.reset(),Ht()}),e.watch(()=>[JSON.stringify(W.value),JSON.stringify(o.params),ee.value],()=>{if(o.autoLoad){se();return}A++,J?.abort(),J=null,s.value=!1,d.value="",v.value=null,b.value=null,Pe()}),n({reload:se,print:Le,exportAs:We,openPdfWindow:Ae,gotoPage:ne,setParams:st,checkPdfFont:Ee,importExcel:He,getPlan:it,getChanges:V.getChanges,state:ae}),(i,g)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["mach-report-preview",{"mrp-wide-report":S.value}]),style:e.normalizeStyle(Lt.value)},[Q.value&&oe.value.length>0?(e.openBlock(),e.createBlock(Pt,{key:0,defs:oe.value,modelValue:le.value,"onUpdate:modelValue":g[0]||(g[0]=h=>le.value=h),messages:x.value,attempted:Ne.value,onQuery:Ot,onReset:zt},null,8,["defs","modelValue","messages","attempted"])):e.createCommentVNode("",!0),e.createVNode(Et,{"page-count":O.value,"current-page":u.value,"zoom-mode":e.unref(me),zoom:e.unref(Y),"show-export":$.value,"show-print":M.value,"show-pdf-window":z.value,messages:x.value,search:{visible:e.unref(I).visible.value,query:e.unref(I).query.value,matchIndex:e.unref(I).matchIndex.value,matchCount:e.unref(I).matchCount.value,searching:e.unref(I).searching.value},"thumbs-visible":B.value,"show-import":!!ye.value,busy:s.value||P.value||e.unref(V).saving.value,onGoto:ne,onZoom:e.unref(ve),onExport:g[1]||(g[1]=h=>We(h)),onPrint:Le,onPdfWindow:Ae,onSearchInput:e.unref(I).onInput,onSearchNav:e.unref(I).onNav,onSearchToggle:e.unref(I).toggle,onThumbsToggle:g[2]||(g[2]=h=>B.value=!B.value),onImportExcel:g[3]||(g[3]=h=>R.value?.click())},null,8,["page-count","current-page","zoom-mode","zoom","show-export","show-print","show-pdf-window","messages","search","thumbs-visible","show-import","busy","onZoom","onSearchInput","onSearchNav","onSearchToggle"]),ye.value?(e.openBlock(),e.createElementBlock("input",{key:1,ref_key:"importInputRef",ref:R,class:"mrp-import-input",type:"file",accept:".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",hidden:"",onChange:jt},null,544)):e.createCommentVNode("",!0),tt.value&&O.value>0?(e.openBlock(),e.createElementBlock("div",nr,e.toDisplayString(e.unref(V).saving.value?x.value.saving:x.value.editingHint),1)):e.createCommentVNode("",!0),b.value?(e.openBlock(),e.createElementBlock("div",{key:3,class:e.normalizeClass(["mrp-export-notice",`mrp-export-${b.value.kind}`]),role:"alert"},e.toDisplayString(b.value.message),3)):e.createCommentVNode("",!0),m.value.status==="error"&&($.value||z.value)?(e.openBlock(),e.createElementBlock("div",rr,[e.createTextVNode(e.toDisplayString(x.value.pdfFontUnavailable)+" ",1),e.createElementVNode("button",{type:"button",onClick:Nt},e.toDisplayString(x.value.retry),1)])):e.createCommentVNode("",!0),e.createElementVNode("div",or,[e.createElementVNode("div",{ref_key:"viewportRef",ref:k,class:"mrp-body",tabindex:"0",onWheel:Ut,onKeydown:Kt,onDblclick:g[4]||(g[4]=(...h)=>e.unref(V).onDoubleClick&&e.unref(V).onDoubleClick(...h)),onScrollPassive:g[5]||(g[5]=h=>e.unref(At)(h.target))},[s.value?(e.openBlock(),e.createElementBlock("div",ar,e.toDisplayString(x.value.loading),1)):d.value?(e.openBlock(),e.createElementBlock("div",lr,[e.createTextVNode(e.toDisplayString(d.value)+" ",1),e.createElementVNode("button",{class:"mrp-retry",type:"button",onClick:se},e.toDisplayString(x.value.retry),1)])):!a.value||O.value===0?(e.openBlock(),e.createElementBlock("div",sr,e.toDisplayString(x.value.empty),1)):(e.openBlock(),e.createElementBlock("div",{key:3,class:"mrp-scale",style:e.normalizeStyle({width:`${e.unref(Ve).w*e.unref(Y)}px`,height:`${e.unref(Ve).h*e.unref(Y)}px`})},[e.createElementVNode("div",{ref_key:"containerRef",ref:E,class:"mrp-scale-inner",style:e.normalizeStyle({transform:`scale(${e.unref(Y)})`,transformOrigin:"top left",width:`${e.unref(Ve).w}px`})},[e.unref(ge).padTopPx>0?(e.openBlock(),e.createElementBlock("div",{key:0,class:"mrp-spacer-top",style:e.normalizeStyle({height:`${e.unref(ge).padTopPx}px`}),"aria-hidden":"true"},null,4)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(at),h=>(e.openBlock(),e.createElementBlock("div",{key:h.index,class:"mrp-page-holder","data-page":h.index+1},null,8,ir))),128)),e.unref(ge).padBottomPx>0?(e.openBlock(),e.createElementBlock("div",{key:1,class:"mrp-spacer-bottom",style:e.normalizeStyle({height:`${e.unref(ge).padBottomPx}px`}),"aria-hidden":"true"},null,4)):e.createCommentVNode("",!0)],4)],4))],544),B.value&&O.value>0?(e.openBlock(),e.createElementBlock("aside",{key:0,ref_key:"thumbsRef",ref:w,class:"mrp-thumbs",onScrollPassive:g[6]||(g[6]=(...h)=>e.unref(_).onScroll&&e.unref(_).onScroll(...h))},[e.unref(_).windowRange.value.padTopPx>0?(e.openBlock(),e.createElementBlock("div",{key:0,class:"mrp-thumb-spacer",style:e.normalizeStyle({height:`${e.unref(_).windowRange.value.padTopPx}px`}),"aria-hidden":"true"},null,4)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(_).visibleThumbs.value,h=>(e.openBlock(),e.createElementBlock("div",{key:h.index,class:e.normalizeClass(["mrp-thumb",{"mrp-thumb-active":h.index+1===u.value}]),style:e.normalizeStyle({height:`${h.height+20}px`}),onClick:T=>ne(h.index+1)},[e.createElementVNode("div",{class:"mrp-thumb-box","data-thumb":h.index+1,style:e.normalizeStyle({height:`${h.height}px`})},null,12,cr),e.createElementVNode("span",dr,e.toDisplayString(h.index+1),1)],14,ur))),128)),e.unref(_).windowRange.value.padBottomPx>0?(e.openBlock(),e.createElementBlock("div",{key:1,class:"mrp-thumb-spacer",style:e.normalizeStyle({height:`${e.unref(_).windowRange.value.padBottomPx}px`}),"aria-hidden":"true"},null,4)):e.createCommentVNode("",!0)],544)):e.createCommentVNode("",!0)]),e.createElementVNode("div",fr,[e.renderSlot(i.$slots,"default",{},void 0,!0)]),e.unref(ue)?(e.openBlock(),e.createElementBlock("div",pr,[g[7]||(g[7]=e.createElementVNode("div",null,"mach-report debug",-1)),e.createElementVNode("div",null,"pages: "+e.toDisplayString(e.unref(ue).pages)+" | window: ["+e.toDisplayString(e.unref(ue).window)+"]",1),e.createElementVNode("div",null,"zoom: "+e.toDisplayString(e.unref(ue).zoom)+" | load: "+e.toDisplayString(e.unref(ue).loadMs),1),e.createElementVNode("div",null,"plan: "+e.toDisplayString(e.unref(ue).planKB)+"KB",1)])):e.createCommentVNode("",!0)],6))}}),Dt=et(mr,[["__scopeId","data-v-8dab9187"]]),vr=Object.freeze(Object.defineProperty({__proto__:null,default:Dt},Symbol.toStringTag,{value:"Module"}));exports.DEFAULT_MESSAGES=kt;exports.DEFAULT_THEME=Ct;exports.MachReportError=re;exports.PlanLoadError=$e;exports.ReportParamPanel=Pt;exports.ReportPreview=Dt;exports.ReportPreview$1=vr;exports.ReportToolbar=Et;exports.SILENT_LOGGER=Yn;exports.buildPrintDocument=_e;exports.buildWordHtml=yt;exports.createDefaultPdfExporter=Mt;exports.createFetchRequest=nn;exports.defineMachReportConfig=$t;exports.defineMachReportPreset=Gn;exports.joinReportIds=tn;exports.normalizeReportIds=Je;exports.printPlans=rn;exports.provideMachReportConfig=Zn;exports.resolveConfig=Bt;exports.themeToCssVars=St;exports.toErrorDetail=Ft;exports.useMachReportConfig=Rt;exports.usePageWindow=ht;exports.usePrintExport=wt;exports.useZoom=bt;
@@ -0,0 +1 @@
1
+ "use strict";const p=require("./render-plan-CCTL4F9v.cjs"),F=25.4,x=96;function T(o=x){return o/F}function D(o,t=x){return(o||0)*T(t)}function O(o,t=x){return o/T(t)}function B(o,t=x){return o*t/72}function k(o,t){const s=10**t;return Math.round(o*s)/s}const $={a3:{widthMm:297,heightMm:420},a4:{widthMm:210,heightMm:297},a5:{widthMm:148,heightMm:210},b4:{widthMm:250,heightMm:353},b5:{widthMm:176,heightMm:250}};function y(o,t=96,s=p.DEFAULT_FONT_PT){if(o?.fontSizePx!=null)return{fontSizePt:o.fontSizePx*72/t,fontSizePx:o.fontSizePx};const c=o?.fontSize??s;return{fontSizePt:c,fontSizePx:B(c,t)}}function N(o,t=p.DEFAULT_STROKE_COLOR){return{color:o?.borderColor??o?.lineColor??t,widthPt:o?.lineWidthPt??p.DEFAULT_BORDER_PT}}function U(o,t=p.DEFAULT_TEXT_COLOR){return o?.color??t}function G(o){return o?.lineHeight??p.LINE_HEIGHT}function K(o){const t=o?.borderTop!==!1,s=o?.borderRight!==!1,c=o?.borderBottom!==!1,l=o?.borderLeft!==!1;return{top:t,right:s,bottom:c,left:l,inner:t||s||c||l}}function W(o,t){const s={...o,...t};return t?.fontSize!=null&&t.fontSizePx==null&&delete s.fontSizePx,t?.fontSizePx!=null&&t.fontSize==null&&delete s.fontSize,s}function Z(o,t){const s=o.length;if(s===0)return[];const c=o.reduce((h,f)=>h+f,0),l=c>0&&t>0?t/c:1,i=[];let m=0;for(let h=0;h<s;h++){const f=Math.max(0,o[h]*l);i.push({pos:m,size:f}),m+=f}return i}function b(o,t,s){return o?.length?Z(o,t):Array.from({length:s},(c,l)=>({pos:t*l/s,size:t/s}))}function q(o,t,s){const c=o.cells??[],l=Math.max(c.length,1),i=o.colWidthsMm?.length??Math.max(1,...c.map(n=>Array.isArray(n)?n.length:0)),m=b(o.colWidthsMm,t,i),h=n=>n<=0?0:n>=i?m[m.length-1].pos+m[m.length-1].size:m[n].pos,f=b(o.rowHeightsMm,s,l),d=n=>n<=0?0:n>=l?f[f.length-1].pos+f[f.length-1].size:f[n].pos,w=new Set,E=(n,r)=>`${n}:${r}`,_=[],z=new Set,C=new Set,v=(n,r)=>`v${n}:${r}`,A=(n,r)=>`h${n}:${r}`;c.forEach((n,r)=>{if(!Array.isArray(n))return;let e=0;for(const S of n){for(;e<i&&w.has(E(r,e));)e++;if(e>=i)break;const H=Math.max(1,Math.min(S?.colSpan??1,i-e)),I=Math.max(1,S?.rowSpan??1),g=Math.min(l,r+I),P=Math.min(i,e+H);for(let u=r;u<g;u++)for(let a=e;a<P;a++)w.add(E(u,a));for(let u=e+1;u<P;u++)for(let a=r;a<g;a++)z.add(v(u,a));for(let u=r+1;u<g;u++)for(let a=e;a<P;a++)C.add(A(u,a));const L=h(e),R=d(r);_.push({ri:r,ci:e,cell:S??{},xMm:L,yMm:R,widthMm:h(P)-L,heightMm:d(g)-R}),e=P}});const M=[];for(let n=1;n<i;n++){let r=-1;for(let e=0;e<=l;e++){const S=e<l&&!z.has(v(n,e));S&&r<0&&(r=e),!S&&r>=0&&(M.push({kind:"v",pos:h(n),from:d(r),to:d(e)}),r=-1)}}for(let n=1;n<l;n++){let r=-1;for(let e=0;e<=i;e++){const S=e<i&&!C.has(A(n,e));S&&r<0&&(r=e),!S&&r>=0&&(M.push({kind:"h",pos:d(n),from:h(r),to:h(e)}),r=-1)}}return{columns:m,rows:f,cells:_,edges:M}}exports.CSS_DPI=x;exports.MM_PER_INCH=F;exports.PAPER_SIZES=$;exports.mergeComponentStyles=W;exports.mmToPx=D;exports.mmToPxFactor=T;exports.ptToPx=B;exports.pxToMm=O;exports.resolveBoxBorders=K;exports.resolveFontSize=y;exports.resolveGridLayout=q;exports.resolveLineHeight=G;exports.resolveStroke=N;exports.resolveTextColor=U;exports.round=k;
@@ -1,4 +1,4 @@
1
- import { D as F, c as O, a as B, L as H, b as $ } from "./defaults-D4o0NCLo.js";
1
+ import { D as F, d as O, a as B, L as H, c as $ } from "./render-plan-CXBWRog4.js";
2
2
  const k = 25.4, M = 96;
3
3
  function R(t = M) {
4
4
  return t / k;
@@ -60,14 +60,14 @@ function U(t, o) {
60
60
  }
61
61
  return a;
62
62
  }
63
- function L(t, o, s) {
63
+ function b(t, o, s) {
64
64
  return t?.length ? U(t, o) : Array.from({ length: s }, (c, i) => ({
65
65
  pos: o * i / s,
66
66
  size: o / s
67
67
  }));
68
68
  }
69
69
  function V(t, o, s) {
70
- const c = t.cells ?? [], i = Math.max(c.length, 1), a = t.colWidthsMm?.length ?? Math.max(1, ...c.map((n) => Array.isArray(n) ? n.length : 0)), m = L(t.colWidthsMm, o, a), l = (n) => n <= 0 ? 0 : n >= a ? m[m.length - 1].pos + m[m.length - 1].size : m[n].pos, f = L(t.rowHeightsMm, s, i), S = (n) => n <= 0 ? 0 : n >= i ? f[f.length - 1].pos + f[f.length - 1].size : f[n].pos, x = /* @__PURE__ */ new Set(), w = (n, r) => `${n}:${r}`, T = [], z = /* @__PURE__ */ new Set(), E = /* @__PURE__ */ new Set(), _ = (n, r) => `v${n}:${r}`, b = (n, r) => `h${n}:${r}`;
70
+ const c = t.cells ?? [], i = Math.max(c.length, 1), a = t.colWidthsMm?.length ?? Math.max(1, ...c.map((n) => Array.isArray(n) ? n.length : 0)), m = b(t.colWidthsMm, o, a), l = (n) => n <= 0 ? 0 : n >= a ? m[m.length - 1].pos + m[m.length - 1].size : m[n].pos, f = b(t.rowHeightsMm, s, i), S = (n) => n <= 0 ? 0 : n >= i ? f[f.length - 1].pos + f[f.length - 1].size : f[n].pos, x = /* @__PURE__ */ new Set(), w = (n, r) => `${n}:${r}`, T = [], z = /* @__PURE__ */ new Set(), E = /* @__PURE__ */ new Set(), _ = (n, r) => `v${n}:${r}`, A = (n, r) => `h${n}:${r}`;
71
71
  c.forEach((n, r) => {
72
72
  if (!Array.isArray(n)) return;
73
73
  let e = 0;
@@ -81,16 +81,16 @@ function V(t, o, s) {
81
81
  for (let h = e + 1; h < p; h++)
82
82
  for (let u = r; u < g; u++) z.add(_(h, u));
83
83
  for (let h = r + 1; h < g; h++)
84
- for (let u = e; u < p; u++) E.add(b(h, u));
85
- const A = l(e), C = S(r);
84
+ for (let u = e; u < p; u++) E.add(A(h, u));
85
+ const C = l(e), L = S(r);
86
86
  T.push({
87
87
  ri: r,
88
88
  ci: e,
89
89
  cell: d ?? {},
90
- xMm: A,
91
- yMm: C,
92
- widthMm: l(p) - A,
93
- heightMm: S(g) - C
90
+ xMm: C,
91
+ yMm: L,
92
+ widthMm: l(p) - C,
93
+ heightMm: S(g) - L
94
94
  }), e = p;
95
95
  }
96
96
  });
@@ -105,7 +105,7 @@ function V(t, o, s) {
105
105
  for (let n = 1; n < i; n++) {
106
106
  let r = -1;
107
107
  for (let e = 0; e <= a; e++) {
108
- const d = e < a && !E.has(b(n, e));
108
+ const d = e < a && !E.has(A(n, e));
109
109
  d && r < 0 && (r = e), !d && r >= 0 && (P.push({ kind: "h", pos: S(n), from: l(r), to: l(e) }), r = -1);
110
110
  }
111
111
  }
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./defaults-DOO1yHwx.cjs"),h=require("./grid-geometry-bkciiZ4Q.cjs"),B=require("./render-plan-CfJ3wf1l.cjs"),N=require("./textwrap-oD-t4b4B.cjs"),ze=require("./page-window-index-DEjnM6IB.cjs"),je=require("./report-params-D1gZ1DME.cjs");function re(e){if(!e||e.kind==="date")return;const t=e.digits;if(!(t!==void 0&&(!Number.isInteger(t)||t<0||t>100))){if(e.kind==="percent"){const n=t??2;return`0${n?`.${"0".repeat(n)}`:""}%`}return t===void 0?e.thousands?"#,##0.###############":void 0:`${e.thousands?"#,##0":"0"}${t?`.${"0".repeat(t)}`:""}`}}function be(e){const t=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/.exec(e.trim());if(t){const i=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(i.getTime())?null:i}const n=new Date(e);return Number.isNaN(n.getTime())?null:n}function ie(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function We(e,t){const n=i=>String(i).padStart(2,"0");return t.replace(/YYYY/g,String(e.getFullYear())).replace(/MM/g,n(e.getMonth()+1)).replace(/DD/g,n(e.getDate())).replace(/hh/g,n(e.getHours())).replace(/mm/g,n(e.getMinutes())).replace(/ss/g,n(e.getSeconds()))}function Ve(e,t,n){return n!=null?t?ie(e,n):e.toFixed(n):t?ie(e):String(e)}function K(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function ae(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{const n=K(e);return n==null?String(e):Ve(n,t.thousands===!0,t.digits)}case"percent":{const n=K(e);return n==null?String(e):`${ie(n*100,t.digits??2)}%`}case"date":{const n=t.pattern??"YYYY-MM-DD",i=e instanceof Date?e:be(String(e));return i?We(i,n):String(e)}default:return String(e)}}function we(e,t){const n=e[t.field];if(n==null||n==="")return!1;if(typeof t.value=="number"){const r=K(n);if(r==null)return!1;switch(t.op){case">":return r>t.value;case">=":return r>=t.value;case"<":return r<t.value;case"<=":return r<=t.value;case"==":return r===t.value;case"!=":return r!==t.value}}const i=String(n),o=String(t.value);switch(t.op){case"==":return i===o;case"!=":return i!==o;case">":return i>o;case">=":return i>=o;case"<":return i<o;case"<=":return i<=o}return!1}const Ge=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Je(e,t,n,i){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&i.push({path:`${n}.${t}`,message:`应为有限数字,实际 ${JSON.stringify(o)}`})}function Ue(e,t,n){if(e!==void 0){const i=`${t}.table`;if(!j(e))n.push({path:i,message:"逻辑表来源应为对象"});else{(typeof e.id!="string"||!e.id.trim())&&n.push({path:`${i}.id`,message:"逻辑表 ID 应为非空字符串"});const o=e.role;["header","body","group-header","subtotal","grand-total"].includes(o)||n.push({path:`${i}.role`,message:"未知逻辑表行角色"});const r=e.rowIndex;(typeof r!="number"||!Number.isInteger(r)||(o==="header"?r!==-1:r<0))&&n.push({path:`${i}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(a=>typeof a!="string"))&&n.push({path:`${i}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&n.push({path:`${i}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&n.push({path:`${i}.title`,message:"逻辑表名称应为字符串"})}}}function qe(e,t,n,i){if(e!==void 0)if(!j(e)||!Array.isArray(e.cells))n.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const o=e.paddingMm;o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0)&&n.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((r,a)=>{if(!Array.isArray(r)){n.push({path:`${t}.grid.cells.${a}`,message:"行应为数组"});return}r.forEach((s,l)=>{s!=null&&j(s)&&Array.isArray(s.children)&&s.children.forEach((d,m)=>{Q(d,`${t}.grid.cells.${a}.${l}.children.${m}`,n,i)})})})}}function Ye(e,t,n){e!==void 0&&(Array.isArray(e)?e.forEach((i,o)=>{(!j(i)||!Array.isArray(i.segments))&&n.push({path:`${t}.richParagraphs.${o}`,message:"段落缺少 segments 数组"})}):n.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"}))}function Q(e,t,n,i=[]){if(!j(e)){n.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?n.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Ge.has(o)||i.push({path:`${t}.kind`,message:`未知组件类型 ${JSON.stringify(o)},将以兜底方式渲染`});for(const r of["leftMm","topMm","widthMm","heightMm"])Je(e,r,t,n);typeof e.leftMm=="number"&&e.leftMm<-100&&n.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const r of["widthMm","heightMm"])typeof e[r]=="number"&&e[r]<0&&n.push({path:`${t}.${r}`,message:"组件尺寸不能为负数"});Ue(e.table,t,n),qe(e.grid,t,n,i),Ye(e.richParagraphs,t,n)}function Se(e,t,n,i=[]){if(!j(e)){n.push({path:t,message:"页应为对象"});return}const o=e.pageWidthMm,r=e.pageHeightMm;(typeof o!="number"||!Number.isFinite(o)||o<=0)&&n.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${JSON.stringify(o)}`}),(typeof r!="number"||!(r>0&&r<5e3))&&n.push({path:`${t}.pageHeightMm`,message:`页高非法: ${JSON.stringify(r)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&n.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const a=e.components;Array.isArray(a)?Array.isArray(a)&&a.forEach((s,l)=>Q(s,`${t}.components.${l}`,n,i)):n.push({path:`${t}.components`,message:"components 应为数组"})}function se(e){const t=[],n=[],i=j(e)?e.pages:void 0;if(!Array.isArray(i))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{i.forEach((r,a)=>Se(r,`$.pages.${a}`,t,n)),i.length>2e3&&n.push({path:"$.pages",message:`页数异常大(${i.length} 页),渲染与打印耗时可能显著增加`});const o=i.reduce((r,a)=>r+(j(a)&&Array.isArray(a.components)?a.components.length:0),0);o>5e4&&n.push({path:"$.pages",message:`组件总数异常大(${o} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:n}}function Ke(e){const t=se(e);if(!t.ok){const n=t.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ");throw new Error(`渲染计划校验失败(${t.errors.length} 处): ${n}`)}return e.pages}function Xe(e){return{widthMm:e.widthMm,heightMm:e.heightMm,marginTopMm:e.marginTopMm??0,marginBottomMm:e.marginBottomMm??0,marginLeftMm:e.marginLeftMm??0,marginRightMm:e.marginRightMm??0,components:[]}}function Ze(e,t){return t.heightMm-(e.layout==="wide"?t.marginBottomMm:e.marginBottomMm??t.marginBottomMm)}function $e(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number")return String(e);if(typeof e=="boolean")return e?"是":"否";if(e instanceof Date)return e.toISOString().slice(0,10);try{return JSON.stringify(e)}catch{return String(e)}}function ve(e,t){let n=e.textMetrics.get(t);if(!n){const i=h.resolveFontSize(t).fontSizePt;n={measureOptions:{fontSizePt:i,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:i*(t.lineHeight??_.LINE_HEIGHT)*25.4/72},e.textMetrics.set(t,n)}return n}function Te(e,t){return t?.kind==="number"||t?.kind==="percent"?"right":t?.kind==="date"||e instanceof Date||typeof e=="boolean"?"center":typeof e=="number"&&Number.isFinite(e)?"right":"left"}function Qe(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function et(e,t){const n=e.fontSizePt??_.DEFAULT_FONT_PT,i=e.paddingMm??1,o=e.columns.map(c=>c.align??c.style?.align??e.align??"left"),r=e.columns.map((c,u)=>({...h.mergeComponentStyles({fontSize:n,verticalAlign:"middle"},c.style),align:o[u]==="auto"?"left":o[u]})),a=r.map((c,u)=>o[u]==="auto"?{left:c,center:{...c,align:"center"},right:{...c,align:"right"}}:void 0),s=e.columns.map((c,u)=>c.rules?.map(y=>{const b=a[u];if(b)return{left:h.mergeComponentStyles(b.left,y.style),center:h.mergeComponentStyles(b.center,y.style),right:h.mergeComponentStyles(b.right,y.style)};const w=h.mergeComponentStyles(r[u],y.style);return{left:w,center:w,right:w}})),l=e.columns.map(c=>{let u=h.mergeComponentStyles({fontSize:n,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},c.style);return e.headerAlign!==void 0&&(u.align=e.headerAlign),u=h.mergeComponentStyles(u,e.headerStyle),c.headerAlign!==void 0&&(u.align=c.headerAlign),h.mergeComponentStyles(u,c.headerStyle)}),d=e.columns.map(c=>c.header);let m=e.rowHeightMm??0;for(let c=0;c<d.length;c++){const u=l[c],y=h.resolveFontSize(u).fontSizePt,b=N.wrapText(d[c],e.columns[c].widthMm-i*2,{fontSizePt:y,bold:u.bold,letterSpacingPt:u.letterSpacing},t),w=y*(u.lineHeight??_.LINE_HEIGHT)*25.4/72;m=Math.max(m,Math.max(b.length,1)*w+i*2)}const f=d.map((c,u)=>({text:c,style:l[u]})),p=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},g=e.columns.map(c=>c.widthMm);return{fontSizePt:n,paddingMm:i,cellStyles:r,autoStyles:a,ruleStyles:s,textMetrics:new WeakMap,numberFormats:e.columns.map(c=>re(c.format)),borderStyle:p,headerHeightMm:m,headerGrid:{cells:[f],colWidthsMm:g,rowHeightsMm:[m],paddingMm:i},colWidthsMm:g,columns:e.columns}}function pe(e,t,n){const i=e.columns;let o=e.rowHeightFloorMm;const r=new Array(i.length);for(let a=0;a<i.length;a++){const s=i[a],l=t[s.field],d=e.autoStyles[a]?Te(l,s.format):"left";let m=e.autoStyles[a]?.[d]??e.cellStyles[a];if(s.rules)for(let y=0;y<s.rules.length;y++){const b=s.rules[y];if(we(t,b.when)){m=e.ruleStyles[a][y][d];break}}const f=s.format?ae(l,s.format):$e(l),p=ve(e,m),g=N.wrapText(f,s.widthMm-e.paddingMm*2,p.measureOptions,n);o=Math.max(o,g.length*p.lineMm+e.paddingMm*2);const c=Qe(l),u={text:f,style:m};c!==void 0&&(u.value=c),typeof c=="number"&&e.numberFormats[a]!==void 0&&(u.numberFormat=e.numberFormats[a]),r[a]=u}return{grid:{cells:[r],colWidthsMm:e.colWidthsMm,rowHeightsMm:[o],paddingMm:e.paddingMm},heightMm:o}}function*tt(e,t){if(!t){for(const i of e)yield{kind:"row",row:i};return}const n=new Map;for(const i of e){const o=$e(i[t.field]),r=n.get(o);r?r.push(i):n.set(o,[i])}for(const[i,o]of n){yield{kind:"groupHeader",label:(t.headerTemplate??"{value}").replace(/\{value\}/g,i),firstRow:o[0]};for(const r of o)yield{kind:"row",row:r};t.subtotal?.length&&(yield{kind:"subtotal",label:t.subtotalLabel??"小计",rows:o})}}function nt(e,t){let n=0;for(const i of e){const o=typeof i[t]=="number"?i[t]:Number(i[t]);Number.isFinite(o)&&(n+=o)}return n}function Ee(e,t,n){return new Map(n.map(i=>{const o=e.find(a=>a.field===i)?.format??{kind:"number",thousands:!0},r=nt(t,i);return[i,{text:ae(r,o),value:r,numberFormat:re(o)}]}))}function Pe(e,t){const n=e.findIndex(i=>t.includes(i.field));return n>0?n:1}function oe(e,t,n,i,o,r){const a=[],s=Math.max(1,Math.min(r,e.columns.length)),l=h.mergeComponentStyles({fontSize:e.fontSizePt},o);a.push({text:n,colSpan:s,style:{bold:!0,...l}});for(let f=s;f<e.columns.length;f++){const p=e.columns[f],g=i.get(p.field),c=e.autoStyles[f]?.[Te(g?.value,p.format)]??e.cellStyles[f];a.push({...g,text:g?.text??"",style:h.mergeComponentStyles(c,o)})}let d=e.rowHeightFloorMm,m=0;for(const f of a){let p=0;const g=m+(f.colSpan??1);for(;m<g;m++)p+=e.colWidthsMm[m]??0;const c=ve(e,f.style),u=N.wrapText(f.text??"",p-e.paddingMm*2,c.measureOptions,t);d=Math.max(d,u.length*c.lineMm+e.paddingMm*2)}return{grid:{cells:[a],colWidthsMm:e.colWidthsMm,rowHeightsMm:[d],paddingMm:e.paddingMm},heightMm:d}}function it(e,t,n){const{templatePage:i,current:o,warnings:r,nextId:a,pushCurrent:s}=n,l=()=>Ze(i,o),d=o.marginTopMm,m={id:n.tableId,columnKeys:e.columns.map(S=>S.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}};let f=0;const p={kind:"rect",leftMm:e.leftMm,topMm:0,widthMm:e.widthMm,heightMm:t.headerHeightMm,grid:t.headerGrid,nid:a("listh"),table:{...m,role:"header",rowIndex:-1},style:t.borderStyle},g=S=>o.components.push({...p,topMm:S});let c=e.topMm;g(c),c+=t.headerHeightMm+n.mmPerRow;function u(){const S=i.layout==="wide"?0:e.topMm;return e.headerEveryPage!==!1?S+t.headerHeightMm:i.layout==="wide"?0:d}function y(){const S=i.layout==="wide"?0:o.marginBottomMm;return i.heightMm-S-u()}function b(S){if(c+S<=l())return;s(),o.components=[],o.heightMm=i.heightMm,i.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const D=i.layout==="wide"?0:e.topMm;e.headerEveryPage!==!1?(g(D),c=D+t.headerHeightMm):c=i.layout==="wide"?0:d}function w(S,D,V){const z=y();S.heightMm>z&&r.push(`列表 ${e.id??e.dataset} 行高 ${S.heightMm.toFixed(2)}mm 超出单页可用高度 ${z.toFixed(2)}mm,预览与打印可能截断内容`),b(S.heightMm),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:c,widthMm:e.widthMm,heightMm:S.heightMm,grid:S.grid,nid:a(D),table:{...m,role:V,rowIndex:f++},style:t.borderStyle}),c+=S.heightMm}function k(S){S<=y()&&b(S)}return{keepTogether:k,placeGridRow:w}}function ot(e,t,n,i,o){if(!e.grandTotal)return;const r=typeof e.grandTotal=="object"?e.grandTotal:void 0,a=r?.fields??e.groupBy?.subtotal??[];if(a.length===0){i.warnings.push(`列表 ${e.id??""} 配置了 grandTotal 但未提供合计字段(groupBy.subtotal 或 grandTotal.fields)`);return}const s=oe(n,i.measurer,r?.label??"合计",Ee(e.columns,t,a),r?.style??{},Pe(e.columns,a));o.placeGridRow(s,"listgt","grand-total")}function rt(e,t,n){const i=e.columns.reduce((d,m)=>d+m.widthMm,0),o=i>e.widthMm?e.widthMm/i:1,r=o===1?e:{...e,columns:e.columns.map(d=>({...d,widthMm:d.widthMm*o}))},a={...et(r,n.measurer),rowHeightFloorMm:r.rowHeightMm??0},s=it(r,a,n);let l;for(const d of tt(t,r.groupBy))if(d.kind==="row")s.placeGridRow(l??pe(a,d.row,n.measurer),"listr","body"),l=void 0;else if(d.kind==="groupHeader"){const m=oe(a,n.measurer,d.label,new Map,r.groupBy?.headerStyle??{},r.columns.length);l=pe(a,d.firstRow,n.measurer),r.groupBy?.keepWithNext!==!1&&s.keepTogether(m.heightMm+l.heightMm),s.placeGridRow(m,"listg","group-header")}else{const m=r.groupBy?.subtotal??[],f=oe(a,n.measurer,d.label,Ee(r.columns,d.rows,m),r.groupBy?.subtotalStyle??{},Pe(r.columns,m));s.placeGridRow(f,"listst","subtotal")}ot(r,t,a,n,s)}function ye(e){return e.kind==="text"&&typeof e.text=="string"&&(e.text.includes("{page}")||e.text.includes("{totalPages}"))}function at(e,t,n,i,o,r){const a={pageWidthMm:t.widthMm,pageHeightMm:t.heightMm,...e.layout===void 0?{}:{layout:e.layout},marginTopMm:t.marginTopMm,marginBottomMm:t.marginBottomMm,marginLeftMm:t.marginLeftMm,marginRightMm:t.marginRightMm,components:t.components};i.push(a);for(const s of n){const l={...s,text:String(s.text??"").replace(/\{page\}/g,String(i.length))};a.components.push(l),l.text.includes("{totalPages}")&&o.push(l)}if(e.layout==="wide"){const s=a.components.reduce((l,d)=>Math.max(l,d.topMm+d.heightMm),0);a.marginBottomMm=r?e.marginBottomMm??0:0,a.pageHeightMm=Math.max(1,s+a.marginBottomMm)}}function ke(e,t,n={}){const i=typeof n=="number"?{mmPerRow:n}:n,o=[],r=[],a=[];let s=0;const l=d=>`${d}_${(++s).toString(36)}`;for(const[d,m]of e.pages.entries()){const f=Xe(m),p=m.components.filter(ye),g=(c=!1)=>at(m,f,p,r,a,c);for(const[c,u]of m.components.entries()){if(ye(u))continue;if(u.kind!=="list"){f.components.push(u);continue}const y=t[u.dataset];Array.isArray(y)||o.push(`数据集 ${u.dataset} 未提供数据,列表 ${u.id??""} 输出为空`),rt(u,Array.isArray(y)?y:[],{templatePage:m,current:f,warnings:o,nextId:l,pushCurrent:g,measurer:i.measurer??N.heuristicMeasurer,mmPerRow:i.mmPerRow??0,tableId:`table:${d}:${c}`})}g(!0)}for(const d of a)d.text=d.text.replace(/\{totalPages\}/g,String(r.length));return{plan:{schemaVersion:B.RENDER_PLAN_SCHEMA_VERSION,pages:r},warnings:o}}const st={root:"mr-root",page:"mr-page",comp:"mr-comp",text:"mr-text",lines:"mr-lines",line:"mr-line",rich:"mr-rich",paragraph:"mr-paragraph",segment:"mr-segment",image:"mr-image",shape:"mr-shape",grid:"mr-grid",row:"mr-row",cell:"mr-cell",unknown:"mr-unknown"};function P(e,t){return t?.classNames?.[e]??st[e]}class lt{constructor(){this.props=[]}add(t,n){return n==null||n===!1||n===""?this:(this.props.push([t,String(n)]),this)}mm(t,n,i,o=2){return this.add(t,`${h.round(h.mmToPx(n,i),o)}px`)}toString(){let t="";for(const[n,i]of this.props)t+=`${n}:${i};`;return t}applyTo(t){const n=this.toString();n&&(t.style.cssText=n)}}function T(e,t="unset"){return new lt().add("all",t).add("display",e).add("box-sizing","border-box")}function Ae(e,t,n){e.add("color",t.color).add("font-family",t.fontFamily).add("font-weight",t.bold!=null?t.bold?"700":"400":void 0).add("font-style",t.italic!=null?t.italic?"italic":"normal":void 0).add("text-decoration",t.underline!=null?t.underline?"underline":"none":void 0).add("letter-spacing",t.letterSpacing!=null?`${t.letterSpacing}pt`:void 0).add("line-height",String(h.resolveLineHeight(t))).add("text-align",t.align);const i=h.resolveFontSize(t,n);e.add("font-size",`${h.round(i.fontSizePx,2)}px`)}function dt(e,t,n){const i=t.style??{};Ae(e,i,n),e.add("background-color",i.backgroundColor).add("opacity",i.opacity!=null?String(i.opacity):void 0).add("transform",i.rotateDeg?`rotate(${i.rotateDeg}deg)`:void 0)}function mt(e,t,n,i,o,r){const a=e.cell,s=r.createElement("td");s.className=P("cell",o),s.setAttribute("role",t.table?.role==="header"?"columnheader":"cell"),a.colSpan&&(s.colSpan=a.colSpan),a.rowSpan&&(s.rowSpan=a.rowSpan);const l=h.mergeComponentStyles(t.style,a.style),d=T("block").add("position","absolute").mm("left",e.xMm,i).mm("top",e.yMm,i).mm("width",e.widthMm,i).mm("height",e.heightMm,i).add("background-color",l.backgroundColor).add("vertical-align",l.verticalAlign??"middle");Ae(d,l,i),d.applyTo(s);const m=r.createElement("div");m.className="mr-cell-content",T("flex").add("position","absolute").mm("left",n,i).mm("right",n,i).mm("top",n,i).mm("bottom",n,i).add("flex-direction","column").add("justify-content",l.verticalAlign==="top"?"flex-start":l.verticalAlign==="bottom"?"flex-end":"center").add("overflow-wrap","anywhere").add("overflow","hidden").applyTo(m),a.text!=null&&m.append(a.text);for(const f of a.children??[])m.appendChild(le(f,i,o,r));return s.appendChild(m),s}function ct(e,t,n,i){const o=h.resolveBoxBorders(t.style),r=o.inner?[...e.edges]:[];o.top&&r.push({kind:"h",pos:0,from:0,to:t.widthMm}),o.bottom&&r.push({kind:"h",pos:t.heightMm,from:0,to:t.widthMm}),o.left&&r.push({kind:"v",pos:0,from:0,to:t.heightMm}),o.right&&r.push({kind:"v",pos:t.widthMm,from:0,to:t.heightMm});const a=h.resolveStroke(t.style),s=`${h.round(a.widthPt*n/72,2)}px solid ${a.color}`;return r.map(l=>{const d=i.createElement("div");d.className="mr-grid-edge",d.setAttribute("aria-hidden","true");const m=l.kind==="h";return T("block").add("position","absolute").add("pointer-events","none").mm("left",m?l.from:l.pos,n).mm("top",m?l.pos:l.from,n).mm("width",m?l.to-l.from:0,n).mm("height",m?0:l.to-l.from,n).add(m?"border-top":"border-left",s).applyTo(d),d})}function ft(e,t,n,i,o){const r=o.createElement("table");r.className=P("grid",i),r.setAttribute("role","table"),T("block").add("position","relative").add("width","100%").add("height","100%").applyTo(r);const a=h.resolveGridLayout(e,t.widthMm,t.heightMm),s=o.createElement("tbody");T("contents").applyTo(s),r.appendChild(s);const l=e.cells.map(()=>{const m=o.createElement("tr");return m.className=P("row",i),m.setAttribute("role","row"),T("contents").applyTo(m),s.appendChild(m),m});for(const m of a.cells)l[m.ri].appendChild(mt(m,t,e.paddingMm??.5,n,i,o));const d=o.createElement("div");return T("block").add("position","relative").add("width","100%").add("height","100%").applyTo(d),d.append(r,...ct(a,t,n,o)),d}function ht(e,t,n,i){const o=i.createElement("div");o.className=P("paragraph",n),T("block").add("text-align",e.align).add("line-height",e.lineHeight!=null?String(e.lineHeight):void 0).mm("margin-top",e.spaceBeforeMm??0,t).mm("margin-bottom",e.spaceAfterMm??0,t).mm("text-indent",e.indentMm??0,t).applyTo(o);for(const r of e.segments||[]){const a=i.createElement("span");a.className=P("segment",n),a.textContent=r.kind==="field"?r.field??"":r.text??"";const s=T("inline");if(r.style){const l=r.style;s.add("color",l.color).add("font-family",l.fontFamily).add("font-weight",l.bold!=null?l.bold?"700":"400":void 0).add("font-style",l.italic!=null?l.italic?"italic":"normal":void 0).add("text-decoration",l.underline!=null?l.underline?"underline":"none":void 0),(l.fontSize!=null||l.fontSizePx!=null)&&s.add("font-size",`${h.round(h.resolveFontSize(l,t).fontSizePx,2)}px`)}s.applyTo(a),o.appendChild(a)}return o}function ut(e,t,n,i){if(B.isRichText(e)){const o=i.createElement("div");o.className=P("rich",n),T("block").applyTo(o);for(const r of e.richParagraphs)o.appendChild(ht(r,t,n,i));return o}if(Array.isArray(e.lines)&&e.lines.length>0){const o=i.createElement("div");o.className=P("lines",n),T("block").applyTo(o);for(const r of e.lines){const a=i.createElement("div");a.className=P("line",n),a.textContent=r,T("block").add("white-space","pre").add("min-height","1lh").applyTo(a),o.appendChild(a)}return o}return e.text??""}function gt(e,t,n,i){const o=i.createElement("div");o.className=P("text",n);const r=e.style||{};return T("flex").add("width","100%").add("height","100%").add("flex-direction","column").add("justify-content",r.verticalAlign==="middle"?"center":r.verticalAlign==="bottom"?"flex-end":"flex-start").add("overflow-wrap","anywhere").add("overflow","hidden").applyTo(o),o.append(ut(e,t,n,i)),o}function pt(e,t,n){const i=n.createElement("img");return i.className=P("image",t),i.src=e.imageData,T("block").add("width","100%").add("height","100%").add("object-fit","contain").applyTo(i),i.alt=e.kind,i}function Me(e,t,n,i){const o=i.createElement("div");o.className=P("shape",n);const r=e.style||{},a=h.resolveStroke(r),s=h.resolveBoxBorders(r),l=`${h.round(a.widthPt*t/72,2)}px solid ${a.color}`,d=T("block");return e.grid?d.add("position","relative"):e.kind==="rect"?(s.top&&d.add("border-top",l),s.right&&d.add("border-right",l),s.bottom&&d.add("border-bottom",l),s.left&&d.add("border-left",l)):e.kind==="ellipse"?(s.inner&&d.add("border",l).add("border-radius","50%"),r.backgroundColor&&d.add("background-color",r.backgroundColor)):e.kind==="line"&&d.add("height","0").add("border-top",l),d.add("box-sizing","border-box").add("width","100%").add("height","100%"),d.applyTo(o),o}function le(e,t,n,i){const o=i.createElement("div");o.className=`${P("comp",n)} mr-kind-${e.kind}`;const r=T("block").add("position","absolute").mm("left",e.leftMm,t).mm("top",e.topMm,t).mm("width",e.widthMm,t).mm("height",e.heightMm,t).add("box-sizing","border-box");if(dt(r,e,t),r.applyTo(o),B.isImageBackedComponent(e))return o.appendChild(pt(e,n,i)),o;if(e.kind==="text")return o.appendChild(gt(e,t,n,i)),o;if(e.grid){const s=Me(e,t,n,i);return s.appendChild(ft(e.grid,e,t,n,i)),o.appendChild(s),o}if(e.kind==="line"||e.kind==="rect"||e.kind==="ellipse"||e.kind==="chart")return o.appendChild(Me(e,t,n,i)),o;const a=i.createElement("div");return a.className=P("unknown",n),T("block").applyTo(a),a.textContent=e.fallbackText??"",o.appendChild(a),o}function xe(e,t,n,i){const o=i.createElement("div");o.className=P("page",n),T("block","initial").add("position","relative").add("font-family",'"Microsoft YaHei", sans-serif').add("font-size",`${h.round(h.resolveFontSize(void 0,t).fontSizePx,2)}px`).add("line-height",String(h.resolveLineHeight(void 0))).add("white-space","pre-wrap").add("direction","ltr").mm("width",e.pageWidthMm,t).mm("height",e.pageHeightMm,t).add("background-color","#fff").add("color",_.DEFAULT_TEXT_COLOR).add("overflow","hidden").add("box-sizing","border-box").applyTo(o);for(const r of e.components)o.appendChild(le(r,t,n,i));return o}function yt(e,t,n={}){const i=n.dpi??96,o=t.createElement("div");return o.className=P("root",n),T("block").applyTo(o),o.dataset.schemaVersion=e.schemaVersion,e.pages.forEach(r=>{o.appendChild(xe(r,i,n,t))}),o}function Ce(e){return ze.createPageWindowIndex(e.pageHeightsPx,e.gapPx).window(e.viewportHeightPx,e.scrollTopPx,e.overscan)}const de=96/25.4;function me(e,t=96){const n=t/96*de;return{widthPx:Math.max(1,Math.round(e.pageWidthMm*n)),heightPx:Math.max(1,Math.round(e.pageHeightMm*n))}}function Mt(e,t,n){const i=document.createElement("canvas"),{widthPx:o,heightPx:r}=me(e,n);i.width=Math.round(o*t),i.height=Math.round(r*t),i.style.width=`${o}px`,i.style.height=`${r}px`;const a=i.getContext("2d");if(!a)throw new Error("当前环境不支持 Canvas 2D(测试需真浏览器,见 e2e/canvas.spec.ts)");return a.scale(t,t),a.fillStyle="#ffffff",a.fillRect(0,0,o,r),{canvas:i,ctx:a}}function bt(e,t=96){return h.resolveFontSize(e,t).fontSizePx}function Ne(e,t,n,i,o,r,a,s="top"){e.font=`${t.italic?"italic ":""}${t.bold?"bold ":""}${t.fontSizePx}px ${a}`,e.fillStyle=t.color,e.textBaseline="alphabetic";const l=t.fontSizePx*t.lineHeight,d=t.text===""?[""]:t.text.split(`
2
- `),m=d.length*l;let f=i;s==="middle"?f=i+(r-m)/2:s==="bottom"&&(f=i+r-m),d.forEach((p,g)=>{e.textAlign=t.align==="center"?"center":t.align==="right"?"right":"left";const c=t.align==="center"?n+o/2:t.align==="right"?n+o:n;e.fillText(p,c,f+g*l+t.fontSizePx*.8,o)}),e.textAlign="left"}function wt(e,t,n,i,o,r,a,s,l){const d=h.resolveBoxBorders(n.style);if(!d.inner)return;const m=h.resolveStroke(n.style);e.strokeStyle=m.color,e.lineWidth=h.ptToPx(m.widthPt,l);for(const f of t.edges)e.beginPath(),f.kind==="v"?(e.moveTo(i+f.pos*s,o+f.from*s),e.lineTo(i+f.pos*s,o+f.to*s)):(e.moveTo(i+f.from*s,o+f.pos*s),e.lineTo(i+f.to*s,o+f.pos*s)),e.stroke();Re(e,d,i,o,r,a)}function Re(e,t,n,i,o,r){e.beginPath(),t.top&&(e.moveTo(n,i),e.lineTo(n+o,i)),t.right&&(e.moveTo(n+o,i),e.lineTo(n+o,i+r)),t.bottom&&(e.moveTo(n+o,i+r),e.lineTo(n,i+r)),t.left&&(e.moveTo(n,i+r),e.lineTo(n,i)),e.stroke()}function St(e,t,n,i,o,r,a,s,l,d,m){const f=h.resolveGridLayout(t,r/s,a/s);for(const g of f.cells){const c=g.cell.style?.backgroundColor??n.style?.backgroundColor;c&&(e.fillStyle=c,e.fillRect(i+g.xMm*s,o+g.yMm*s,g.widthMm*s,g.heightMm*s))}wt(e,f,n,i,o,r,a,s,l);const p=t.paddingMm??.5;for(const g of f.cells){const c=g.cell.text??"";if(!c)continue;const u=h.mergeComponentStyles(n.style,g.cell.style),y=h.resolveFontSize(u,l),b=Math.max(0,g.widthMm-2*p),w=N.wrapText(c,b,{fontSizePt:y.fontSizePt,bold:u.bold},m).join(`
3
- `);Ne(e,{text:w,fontSizePx:y.fontSizePx,bold:u.bold??!1,italic:u.italic,color:h.resolveTextColor(u,_.DEFAULT_TEXT_COLOR),align:u.align??"left",lineHeight:h.resolveLineHeight(u)},i+(g.xMm+p)*s,o+(g.yMm+p)*s,b*s,Math.max(0,g.heightMm-2*p)*s,u.fontFamily??d,u.verticalAlign??"middle")}}function $t(e,t,n,i,o,r,a,s,l){const d=t.style??{},m=h.resolveFontSize(d,a),f=B.isRichText(t)?t.richParagraphs.map(p=>p.segments.map(g=>g.text??g.field??"").join("")).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("./render-plan-CCTL4F9v.cjs"),u=require("./grid-geometry-BNIvw52m.cjs"),N=require("./textwrap-oD-t4b4B.cjs"),Ke=require("./page-window-index-DEjnM6IB.cjs"),qe=require("./report-params-D1gZ1DME.cjs"),Se=require("./number-format-CZ2T_5kF.cjs");function se(e){if(!e||e.kind==="date")return;const t=e.digits;if(!(t!==void 0&&(!Number.isInteger(t)||t<0||t>100))){if(e.kind==="percent"){const n=t??2;return`0${n?`.${"0".repeat(n)}`:""}%`}return t===void 0?e.thousands?"#,##0.###############":void 0:`${e.thousands?"#,##0":"0"}${t?`.${"0".repeat(t)}`:""}`}}function $e(e){const t=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/.exec(e.trim());if(t){const r=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(r.getTime())?null:r}const n=new Date(e);return Number.isNaN(n.getTime())?null:n}function ie(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function Ye(e,t){const n=r=>String(r).padStart(2,"0");return t.replace(/YYYY/g,String(e.getFullYear())).replace(/MM/g,n(e.getMonth()+1)).replace(/DD/g,n(e.getDate())).replace(/hh/g,n(e.getHours())).replace(/mm/g,n(e.getMinutes())).replace(/ss/g,n(e.getSeconds()))}function Xe(e,t,n){return n!=null?t?ie(e,n):e.toFixed(n):t?ie(e):String(e)}function Y(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function le(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{const n=Y(e);return n==null?String(e):Xe(n,t.thousands===!0,t.digits)}case"percent":{const n=Y(e);return n==null?String(e):`${ie(n*100,t.digits??2)}%`}case"date":{const n=t.pattern??"YYYY-MM-DD",r=e instanceof Date?e:$e(String(e));return r?Ye(r,n):String(e)}default:return String(e)}}function Te(e,t){const n=e[t.field];if(n==null||n==="")return!1;if(typeof t.value=="number"){const i=Y(n);if(i==null)return!1;switch(t.op){case">":return i>t.value;case">=":return i>=t.value;case"<":return i<t.value;case"<=":return i<=t.value;case"==":return i===t.value;case"!=":return i!==t.value}}const r=String(n),o=String(t.value);switch(t.op){case"==":return r===o;case"!=":return r!==o;case">":return r>o;case">=":return r>=o;case"<":return r<o;case"<=":return r<=o}return!1}function Ee(e,t,n){e.editable!==void 0&&typeof e.editable!="boolean"&&n.push({path:`${t}.editable`,message:"编辑控制应为布尔值"}),e.valueType!==void 0&&!["text","number","boolean"].includes(e.valueType)&&n.push({path:`${t}.valueType`,message:"编辑类型应为 text、number 或 boolean"})}function Ze(e,t,n){Ee(e,t,n),e.formula!==void 0&&typeof e.formula!="string"&&n.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}const Qe=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function et(e,t,n,r){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&r.push({path:`${n}.${t}`,message:`应为有限数字,实际 ${JSON.stringify(o)}`})}function tt(e,t,n){if(e!==void 0){const r=`${t}.table`;if(!j(e))n.push({path:r,message:"逻辑表来源应为对象"});else{(typeof e.id!="string"||!e.id.trim())&&n.push({path:`${r}.id`,message:"逻辑表 ID 应为非空字符串"});const o=e.role;["header","body","group-header","subtotal","grand-total"].includes(o)||n.push({path:`${r}.role`,message:"未知逻辑表行角色"});const i=e.rowIndex;(typeof i!="number"||!Number.isInteger(i)||(o==="header"?i!==-1:i<0))&&n.push({path:`${r}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(a=>typeof a!="string"))&&n.push({path:`${r}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&n.push({path:`${r}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&n.push({path:`${r}.title`,message:"逻辑表名称应为字符串"})}}}function nt(e,t,n,r){if(e!==void 0)if(!j(e)||!Array.isArray(e.cells))n.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const o=e.paddingMm;o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0)&&n.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((i,a)=>{if(!Array.isArray(i)){n.push({path:`${t}.grid.cells.${a}`,message:"行应为数组"});return}i.forEach((s,l)=>{if(s==null)return;const d=`${t}.grid.cells.${a}.${l}`;if(!j(s)){n.push({path:d,message:"网格单元格应为对象或 null"});return}Ze(s,d,n),Array.isArray(s.children)&&s.children.forEach((c,m)=>{Q(c,`${t}.grid.cells.${a}.${l}.children.${m}`,n,r)})})})}}function rt(e,t,n){e!==void 0&&(Array.isArray(e)?e.forEach((r,o)=>{(!j(r)||!Array.isArray(r.segments))&&n.push({path:`${t}.richParagraphs.${o}`,message:"段落缺少 segments 数组"})}):n.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"}))}function Q(e,t,n,r=[]){if(!j(e)){n.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?n.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Qe.has(o)||r.push({path:`${t}.kind`,message:`未知组件类型 ${JSON.stringify(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])et(e,i,t,n);typeof e.leftMm=="number"&&e.leftMm<-100&&n.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const i of["widthMm","heightMm"])typeof e[i]=="number"&&e[i]<0&&n.push({path:`${t}.${i}`,message:"组件尺寸不能为负数"});tt(e.table,t,n),nt(e.grid,t,n,r),rt(e.richParagraphs,t,n)}function xe(e,t,n,r=[]){if(!j(e)){n.push({path:t,message:"页应为对象"});return}const o=e.pageWidthMm,i=e.pageHeightMm;(typeof o!="number"||!Number.isFinite(o)||o<=0)&&n.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${JSON.stringify(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&n.push({path:`${t}.pageHeightMm`,message:`页高非法: ${JSON.stringify(i)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&n.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const a=e.components;Array.isArray(a)?Array.isArray(a)&&a.forEach((s,l)=>Q(s,`${t}.components.${l}`,n,r)):n.push({path:`${t}.components`,message:"components 应为数组"})}function de(e){const t=[],n=[],r=j(e)?e.pages:void 0;if(!Array.isArray(r))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{r.forEach((i,a)=>xe(i,`$.pages.${a}`,t,n)),r.length>2e3&&n.push({path:"$.pages",message:`页数异常大(${r.length} 页),渲染与打印耗时可能显著增加`});const o=r.reduce((i,a)=>i+(j(a)&&Array.isArray(a.components)?a.components.length:0),0);o>5e4&&n.push({path:"$.pages",message:`组件总数异常大(${o} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:n}}function ot(e){const t=de(e);if(!t.ok){const n=t.errors.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ");throw new Error(`渲染计划校验失败(${t.errors.length} 处): ${n}`)}return e.pages}function it(e){return{widthMm:e.widthMm,heightMm:e.heightMm,marginTopMm:e.marginTopMm??0,marginBottomMm:e.marginBottomMm??0,marginLeftMm:e.marginLeftMm??0,marginRightMm:e.marginRightMm??0,components:[]}}function at(e,t){return t.heightMm-(e.layout==="wide"?t.marginBottomMm:e.marginBottomMm??t.marginBottomMm)}function Pe(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number")return String(e);if(typeof e=="boolean")return e?"是":"否";if(e instanceof Date)return e.toISOString().slice(0,10);try{return JSON.stringify(e)}catch{return String(e)}}function ke(e,t){let n=e.textMetrics.get(t);if(!n){const r=u.resolveFontSize(t).fontSizePt;n={measureOptions:{fontSizePt:r,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:r*(t.lineHeight??$.LINE_HEIGHT)*25.4/72},e.textMetrics.set(t,n)}return n}function Ae(e,t){return t?.kind==="number"||t?.kind==="percent"?"right":t?.kind==="date"||e instanceof Date||typeof e=="boolean"?"center":typeof e=="number"&&Number.isFinite(e)?"right":"left"}function st(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function lt(e,t){const n=e.fontSizePt??$.DEFAULT_FONT_PT,r=e.paddingMm??1,o=e.columns.map(f=>f.align??f.style?.align??e.align??"left"),i=e.columns.map((f,h)=>({...u.mergeComponentStyles({fontSize:n,verticalAlign:"middle"},f.style),align:o[h]==="auto"?"left":o[h]})),a=i.map((f,h)=>o[h]==="auto"?{left:f,center:{...f,align:"center"},right:{...f,align:"right"}}:void 0),s=e.columns.map((f,h)=>f.rules?.map(y=>{const M=a[h];if(M)return{left:u.mergeComponentStyles(M.left,y.style),center:u.mergeComponentStyles(M.center,y.style),right:u.mergeComponentStyles(M.right,y.style)};const w=u.mergeComponentStyles(i[h],y.style);return{left:w,center:w,right:w}})),l=e.columns.map(f=>{let h=u.mergeComponentStyles({fontSize:n,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},f.style);return e.headerAlign!==void 0&&(h.align=e.headerAlign),h=u.mergeComponentStyles(h,e.headerStyle),f.headerAlign!==void 0&&(h.align=f.headerAlign),u.mergeComponentStyles(h,f.headerStyle)}),d=e.columns.map(f=>f.header);let c=e.rowHeightMm??0;for(let f=0;f<d.length;f++){const h=l[f],y=u.resolveFontSize(h).fontSizePt,M=N.wrapText(d[f],e.columns[f].widthMm-r*2,{fontSizePt:y,bold:h.bold,letterSpacingPt:h.letterSpacing},t),w=y*(h.lineHeight??$.LINE_HEIGHT)*25.4/72;c=Math.max(c,Math.max(M.length,1)*w+r*2)}const m=d.map((f,h)=>({text:f,style:l[h]})),p=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},g=e.columns.map(f=>f.widthMm);return{fontSizePt:n,paddingMm:r,cellStyles:i,autoStyles:a,ruleStyles:s,textMetrics:new WeakMap,numberFormats:e.columns.map(f=>se(f.format)),borderStyle:p,headerHeightMm:c,headerGrid:{cells:[m],colWidthsMm:g,rowHeightsMm:[c],paddingMm:r},colWidthsMm:g,columns:e.columns}}function dt(e,t,n){const r=t.format?.kind==="number"||t.format?.kind==="percent";t.valueType!==void 0?e.valueType=t.valueType:r&&(e.valueType="number"),t.editable!==void 0&&(e.editable=t.editable),(typeof e.value=="number"||e.value==null)&&n!==void 0&&(e.numberFormat=n)}function Me(e,t,n){const r=e.columns;let o=e.rowHeightFloorMm;const i=new Array(r.length);for(let a=0;a<r.length;a++){const s=r[a],l=t[s.field],d=e.autoStyles[a]?Ae(l,s.format):"left";let c=e.autoStyles[a]?.[d]??e.cellStyles[a];if(s.rules)for(let y=0;y<s.rules.length;y++){const M=s.rules[y];if(Te(t,M.when)){c=e.ruleStyles[a][y][d];break}}const m=s.format?le(l,s.format):Pe(l),p=ke(e,c),g=N.wrapText(m,s.widthMm-e.paddingMm*2,p.measureOptions,n);o=Math.max(o,g.length*p.lineMm+e.paddingMm*2);const f=st(l),h={text:m,style:c};f!==void 0&&(h.value=f),dt(h,s,e.numberFormats[a]),i[a]=h}return{grid:{cells:[i],colWidthsMm:e.colWidthsMm,rowHeightsMm:[o],paddingMm:e.paddingMm},heightMm:o}}function*ct(e,t){if(!t){for(const r of e)yield{kind:"row",row:r};return}const n=new Map;for(const r of e){const o=Pe(r[t.field]),i=n.get(o);i?i.push(r):n.set(o,[r])}for(const[r,o]of n){yield{kind:"groupHeader",label:(t.headerTemplate??"{value}").replace(/\{value\}/g,r),firstRow:o[0]};for(const i of o)yield{kind:"row",row:i};t.subtotal?.length&&(yield{kind:"subtotal",label:t.subtotalLabel??"小计",rows:o})}}function mt(e,t){let n=0;for(const r of e){const o=typeof r[t]=="number"?r[t]:Number(r[t]);Number.isFinite(o)&&(n+=o)}return n}function Ce(e,t,n){return new Map(n.map(r=>{const o=e.find(a=>a.field===r)?.format??{kind:"number",thousands:!0},i=mt(t,r);return[r,{text:le(i,o),value:i,numberFormat:se(o)}]}))}function Re(e,t){const n=e.findIndex(r=>t.includes(r.field));return n>0?n:1}function ae(e,t,n,r,o,i){const a=[],s=Math.max(1,Math.min(i,e.columns.length)),l=u.mergeComponentStyles({fontSize:e.fontSizePt},o);a.push({text:n,colSpan:s,style:{bold:!0,...l}});for(let m=s;m<e.columns.length;m++){const p=e.columns[m],g=r.get(p.field),f=e.autoStyles[m]?.[Ae(g?.value,p.format)]??e.cellStyles[m];a.push({...g,text:g?.text??"",style:u.mergeComponentStyles(f,o)})}let d=e.rowHeightFloorMm,c=0;for(const m of a){let p=0;const g=c+(m.colSpan??1);for(;c<g;c++)p+=e.colWidthsMm[c]??0;const f=ke(e,m.style),h=N.wrapText(m.text??"",p-e.paddingMm*2,f.measureOptions,t);d=Math.max(d,h.length*f.lineMm+e.paddingMm*2)}return{grid:{cells:[a],colWidthsMm:e.colWidthsMm,rowHeightsMm:[d],paddingMm:e.paddingMm},heightMm:d}}function ft(e,t,n){const{templatePage:r,current:o,warnings:i,nextId:a,pushCurrent:s}=n,l=()=>at(r,o),d=o.marginTopMm,c={id:n.tableId,columnKeys:e.columns.map(v=>v.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}};let m=0;const p={kind:"rect",leftMm:e.leftMm,topMm:0,widthMm:e.widthMm,heightMm:t.headerHeightMm,grid:t.headerGrid,nid:a("listh"),table:{...c,role:"header",rowIndex:-1},style:t.borderStyle},g=v=>o.components.push({...p,topMm:v});let f=e.topMm;g(f),f+=t.headerHeightMm+n.mmPerRow;function h(){const v=r.layout==="wide"?0:e.topMm;return e.headerEveryPage!==!1?v+t.headerHeightMm:r.layout==="wide"?0:d}function y(){const v=r.layout==="wide"?0:o.marginBottomMm;return r.heightMm-v-h()}function M(v){if(f+v<=l())return;s(),o.components=[],o.heightMm=r.heightMm,r.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const D=r.layout==="wide"?0:e.topMm;e.headerEveryPage!==!1?(g(D),f=D+t.headerHeightMm):f=r.layout==="wide"?0:d}function w(v,D,V){const z=y();v.heightMm>z&&i.push(`列表 ${e.id??e.dataset} 行高 ${v.heightMm.toFixed(2)}mm 超出单页可用高度 ${z.toFixed(2)}mm,预览与打印可能截断内容`),M(v.heightMm),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:f,widthMm:e.widthMm,heightMm:v.heightMm,grid:v.grid,nid:a(D),table:{...c,role:V,rowIndex:m++},style:t.borderStyle}),f+=v.heightMm}function k(v){v<=y()&&M(v)}return{keepTogether:k,placeGridRow:w}}function ut(e,t,n,r,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,a=i?.fields??e.groupBy?.subtotal??[];if(a.length===0){r.warnings.push(`列表 ${e.id??""} 配置了 grandTotal 但未提供合计字段(groupBy.subtotal 或 grandTotal.fields)`);return}const s=ae(n,r.measurer,i?.label??"合计",Ce(e.columns,t,a),i?.style??{},Re(e.columns,a));o.placeGridRow(s,"listgt","grand-total")}function ht(e,t,n){const r=e.columns.reduce((d,c)=>d+c.widthMm,0),o=r>e.widthMm?e.widthMm/r:1,i=o===1?e:{...e,columns:e.columns.map(d=>({...d,widthMm:d.widthMm*o}))},a={...lt(i,n.measurer),rowHeightFloorMm:i.rowHeightMm??0},s=ft(i,a,n);let l;for(const d of ct(t,i.groupBy))if(d.kind==="row")s.placeGridRow(l??Me(a,d.row,n.measurer),"listr","body"),l=void 0;else if(d.kind==="groupHeader"){const c=ae(a,n.measurer,d.label,new Map,i.groupBy?.headerStyle??{},i.columns.length);l=Me(a,d.firstRow,n.measurer),i.groupBy?.keepWithNext!==!1&&s.keepTogether(c.heightMm+l.heightMm),s.placeGridRow(c,"listg","group-header")}else{const c=i.groupBy?.subtotal??[],m=ae(a,n.measurer,d.label,Ce(i.columns,d.rows,c),i.groupBy?.subtotalStyle??{},Re(i.columns,c));s.placeGridRow(m,"listst","subtotal")}ut(i,t,a,n,s)}function we(e){return e.kind==="text"&&typeof e.text=="string"&&(e.text.includes("{page}")||e.text.includes("{totalPages}"))}function gt(e,t,n,r,o,i){const a={pageWidthMm:t.widthMm,pageHeightMm:t.heightMm,...e.layout===void 0?{}:{layout:e.layout},marginTopMm:t.marginTopMm,marginBottomMm:t.marginBottomMm,marginLeftMm:t.marginLeftMm,marginRightMm:t.marginRightMm,components:t.components};r.push(a);for(const s of n){const l={...s,text:String(s.text??"").replace(/\{page\}/g,String(r.length))};a.components.push(l),l.text.includes("{totalPages}")&&o.push(l)}if(e.layout==="wide"){const s=a.components.reduce((l,d)=>Math.max(l,d.topMm+d.heightMm),0);a.marginBottomMm=i?e.marginBottomMm??0:0,a.pageHeightMm=Math.max(1,s+a.marginBottomMm)}}function Ne(e,t,n={}){const r=typeof n=="number"?{mmPerRow:n}:n,o=[],i=[],a=[];let s=0;const l=d=>`${d}_${(++s).toString(36)}`;for(const[d,c]of e.pages.entries()){const m=it(c),p=c.components.filter(we),g=(f=!1)=>gt(c,m,p,i,a,f);for(const[f,h]of c.components.entries()){if(we(h))continue;if(h.kind!=="list"){m.components.push(h);continue}const y=t[h.dataset];Array.isArray(y)||o.push(`数据集 ${h.dataset} 未提供数据,列表 ${h.id??""} 输出为空`),ht(h,Array.isArray(y)?y:[],{templatePage:c,current:m,warnings:o,nextId:l,pushCurrent:g,measurer:r.measurer??N.heuristicMeasurer,mmPerRow:r.mmPerRow??0,tableId:`table:${d}:${f}`})}g(!0)}for(const d of a)d.text=d.text.replace(/\{totalPages\}/g,String(i.length));return{plan:{schemaVersion:$.RENDER_PLAN_SCHEMA_VERSION,pages:i},warnings:o}}const pt={root:"mr-root",page:"mr-page",comp:"mr-comp",text:"mr-text",lines:"mr-lines",line:"mr-line",rich:"mr-rich",paragraph:"mr-paragraph",segment:"mr-segment",image:"mr-image",shape:"mr-shape",grid:"mr-grid",row:"mr-row",cell:"mr-cell",unknown:"mr-unknown"};function P(e,t){return t?.classNames?.[e]??pt[e]}class yt{constructor(){this.props=[]}add(t,n){return n==null||n===!1||n===""?this:(this.props.push([t,String(n)]),this)}mm(t,n,r,o=2){return this.add(t,`${u.round(u.mmToPx(n,r),o)}px`)}toString(){let t="";for(const[n,r]of this.props)t+=`${n}:${r};`;return t}applyTo(t){const n=this.toString();n&&(t.style.cssText=n)}}function E(e,t="unset"){return new yt().add("all",t).add("display",e).add("box-sizing","border-box")}function Ie(e,t,n){e.add("color",t.color).add("font-family",t.fontFamily).add("font-weight",t.bold!=null?t.bold?"700":"400":void 0).add("font-style",t.italic!=null?t.italic?"italic":"normal":void 0).add("text-decoration",t.underline!=null?t.underline?"underline":"none":void 0).add("letter-spacing",t.letterSpacing!=null?`${t.letterSpacing}pt`:void 0).add("line-height",String(u.resolveLineHeight(t))).add("text-align",t.align);const r=u.resolveFontSize(t,n);e.add("font-size",`${u.round(r.fontSizePx,2)}px`)}function bt(e,t,n){const r=t.style??{};Ie(e,r,n),e.add("background-color",r.backgroundColor).add("opacity",r.opacity!=null?String(r.opacity):void 0).add("transform",r.rotateDeg?`rotate(${r.rotateDeg}deg)`:void 0)}function Mt(e,t,n,r,o,i){const a=e.cell,s=i.createElement("td");s.className=P("cell",o),s.dataset.mrRowIndex=String(e.ri),s.dataset.mrColumnIndex=String(e.ci),s.setAttribute("role",t.table?.role==="header"?"columnheader":"cell"),a.colSpan&&(s.colSpan=a.colSpan),a.rowSpan&&(s.rowSpan=a.rowSpan);const l=u.mergeComponentStyles(t.style,a.style),d=E("block").add("position","absolute").mm("left",e.xMm,r).mm("top",e.yMm,r).mm("width",e.widthMm,r).mm("height",e.heightMm,r).add("background-color",l.backgroundColor).add("vertical-align",l.verticalAlign??"middle");Ie(d,l,r),d.applyTo(s);const c=i.createElement("div");c.className="mr-cell-content",E("flex").add("position","absolute").mm("left",n,r).mm("right",n,r).mm("top",n,r).mm("bottom",n,r).add("flex-direction","column").add("justify-content",l.verticalAlign==="top"?"flex-start":l.verticalAlign==="bottom"?"flex-end":"center").add("overflow-wrap","anywhere").add("overflow","hidden").applyTo(c),a.text!=null&&c.append(a.text);for(const m of a.children??[])c.appendChild(ce(m,r,o,i));return s.appendChild(c),s}function wt(e,t,n,r){const o=u.resolveBoxBorders(t.style),i=o.inner?[...e.edges]:[];o.top&&i.push({kind:"h",pos:0,from:0,to:t.widthMm}),o.bottom&&i.push({kind:"h",pos:t.heightMm,from:0,to:t.widthMm}),o.left&&i.push({kind:"v",pos:0,from:0,to:t.heightMm}),o.right&&i.push({kind:"v",pos:t.widthMm,from:0,to:t.heightMm});const a=u.resolveStroke(t.style),s=`${u.round(a.widthPt*n/72,2)}px solid ${a.color}`;return i.map(l=>{const d=r.createElement("div");d.className="mr-grid-edge",d.setAttribute("aria-hidden","true");const c=l.kind==="h";return E("block").add("position","absolute").add("pointer-events","none").mm("left",c?l.from:l.pos,n).mm("top",c?l.pos:l.from,n).mm("width",c?l.to-l.from:0,n).mm("height",c?0:l.to-l.from,n).add(c?"border-top":"border-left",s).applyTo(d),d})}function vt(e,t,n,r,o){const i=o.createElement("table");i.className=P("grid",r),i.setAttribute("role","table"),E("block").add("position","relative").add("width","100%").add("height","100%").applyTo(i);const a=u.resolveGridLayout(e,t.widthMm,t.heightMm),s=o.createElement("tbody");E("contents").applyTo(s),i.appendChild(s);const l=e.cells.map(()=>{const c=o.createElement("tr");return c.className=P("row",r),c.setAttribute("role","row"),E("contents").applyTo(c),s.appendChild(c),c});for(const c of a.cells)l[c.ri].appendChild(Mt(c,t,e.paddingMm??.5,n,r,o));const d=o.createElement("div");return E("block").add("position","relative").add("width","100%").add("height","100%").applyTo(d),d.append(i,...wt(a,t,n,o)),d}function St(e,t,n,r){const o=r.createElement("div");o.className=P("paragraph",n),E("block").add("text-align",e.align).add("line-height",e.lineHeight!=null?String(e.lineHeight):void 0).mm("margin-top",e.spaceBeforeMm??0,t).mm("margin-bottom",e.spaceAfterMm??0,t).mm("text-indent",e.indentMm??0,t).applyTo(o);for(const i of e.segments||[]){const a=r.createElement("span");a.className=P("segment",n),a.textContent=i.kind==="field"?i.field??"":i.text??"";const s=E("inline");if(i.style){const l=i.style;s.add("color",l.color).add("font-family",l.fontFamily).add("font-weight",l.bold!=null?l.bold?"700":"400":void 0).add("font-style",l.italic!=null?l.italic?"italic":"normal":void 0).add("text-decoration",l.underline!=null?l.underline?"underline":"none":void 0),(l.fontSize!=null||l.fontSizePx!=null)&&s.add("font-size",`${u.round(u.resolveFontSize(l,t).fontSizePx,2)}px`)}s.applyTo(a),o.appendChild(a)}return o}function $t(e,t,n,r){if($.isRichText(e)){const o=r.createElement("div");o.className=P("rich",n),E("block").applyTo(o);for(const i of e.richParagraphs)o.appendChild(St(i,t,n,r));return o}if(Array.isArray(e.lines)&&e.lines.length>0){const o=r.createElement("div");o.className=P("lines",n),E("block").applyTo(o);for(const i of e.lines){const a=r.createElement("div");a.className=P("line",n),a.textContent=i,E("block").add("white-space","pre").add("min-height","1lh").applyTo(a),o.appendChild(a)}return o}return e.text??""}function Tt(e,t,n,r){const o=r.createElement("div");o.className=P("text",n);const i=e.style||{};return E("flex").add("width","100%").add("height","100%").add("flex-direction","column").add("justify-content",i.verticalAlign==="middle"?"center":i.verticalAlign==="bottom"?"flex-end":"flex-start").add("overflow-wrap","anywhere").add("overflow","hidden").applyTo(o),o.append($t(e,t,n,r)),o}function Et(e,t,n){const r=n.createElement("img");return r.className=P("image",t),r.src=e.imageData,E("block").add("width","100%").add("height","100%").add("object-fit","contain").applyTo(r),r.alt=e.kind,r}function ve(e,t,n,r){const o=r.createElement("div");o.className=P("shape",n);const i=e.style||{},a=u.resolveStroke(i),s=u.resolveBoxBorders(i),l=`${u.round(a.widthPt*t/72,2)}px solid ${a.color}`,d=E("block");return e.grid?d.add("position","relative"):e.kind==="rect"?(s.top&&d.add("border-top",l),s.right&&d.add("border-right",l),s.bottom&&d.add("border-bottom",l),s.left&&d.add("border-left",l)):e.kind==="ellipse"?(s.inner&&d.add("border",l).add("border-radius","50%"),i.backgroundColor&&d.add("background-color",i.backgroundColor)):e.kind==="line"&&d.add("height","0").add("border-top",l),d.add("box-sizing","border-box").add("width","100%").add("height","100%"),d.applyTo(o),o}function ce(e,t,n,r){const o=r.createElement("div");o.className=`${P("comp",n)} mr-kind-${e.kind}`;const i=E("block").add("position","absolute").mm("left",e.leftMm,t).mm("top",e.topMm,t).mm("width",e.widthMm,t).mm("height",e.heightMm,t).add("box-sizing","border-box");if(bt(i,e,t),i.applyTo(o),$.isImageBackedComponent(e))return o.appendChild(Et(e,n,r)),o;if(e.kind==="text")return o.appendChild(Tt(e,t,n,r)),o;if(e.grid){const s=ve(e,t,n,r);return s.appendChild(vt(e.grid,e,t,n,r)),o.appendChild(s),o}if(e.kind==="line"||e.kind==="rect"||e.kind==="ellipse"||e.kind==="chart")return o.appendChild(ve(e,t,n,r)),o;const a=r.createElement("div");return a.className=P("unknown",n),E("block").applyTo(a),a.textContent=e.fallbackText??"",o.appendChild(a),o}function Le(e,t,n,r){const o=r.createElement("div");return o.className=P("page",n),E("block","initial").add("position","relative").add("font-family",'"Microsoft YaHei", sans-serif').add("font-size",`${u.round(u.resolveFontSize(void 0,t).fontSizePx,2)}px`).add("line-height",String(u.resolveLineHeight(void 0))).add("white-space","pre-wrap").add("direction","ltr").mm("width",e.pageWidthMm,t).mm("height",e.pageHeightMm,t).add("background-color","#fff").add("color",$.DEFAULT_TEXT_COLOR).add("overflow","hidden").add("box-sizing","border-box").applyTo(o),e.components.forEach((i,a)=>{const s=ce(i,t,n,r);s.dataset.mrComponentIndex=String(a),o.appendChild(s)}),o}function xt(e,t,n={}){const r=n.dpi??96,o=t.createElement("div");return o.className=P("root",n),E("block").applyTo(o),o.dataset.schemaVersion=e.schemaVersion,e.pages.forEach(i=>{o.appendChild(Le(i,r,n,t))}),o}function Oe(e){return Ke.createPageWindowIndex(e.pageHeightsPx,e.gapPx).window(e.viewportHeightPx,e.scrollTopPx,e.overscan)}const me=96/25.4;function fe(e,t=96){const n=t/96*me;return{widthPx:Math.max(1,Math.round(e.pageWidthMm*n)),heightPx:Math.max(1,Math.round(e.pageHeightMm*n))}}function Pt(e,t,n){const r=document.createElement("canvas"),{widthPx:o,heightPx:i}=fe(e,n);r.width=Math.round(o*t),r.height=Math.round(i*t),r.style.width=`${o}px`,r.style.height=`${i}px`;const a=r.getContext("2d");if(!a)throw new Error("当前环境不支持 Canvas 2D(测试需真浏览器,见 e2e/canvas.spec.ts)");return a.scale(t,t),a.fillStyle="#ffffff",a.fillRect(0,0,o,i),{canvas:r,ctx:a}}function kt(e,t=96){return u.resolveFontSize(e,t).fontSizePx}function Fe(e,t,n,r,o,i,a,s="top"){e.font=`${t.italic?"italic ":""}${t.bold?"bold ":""}${t.fontSizePx}px ${a}`,e.fillStyle=t.color,e.textBaseline="alphabetic";const l=t.fontSizePx*t.lineHeight,d=t.text===""?[""]:t.text.split(`
2
+ `),c=d.length*l;let m=r;s==="middle"?m=r+(i-c)/2:s==="bottom"&&(m=r+i-c),d.forEach((p,g)=>{e.textAlign=t.align==="center"?"center":t.align==="right"?"right":"left";const f=t.align==="center"?n+o/2:t.align==="right"?n+o:n;e.fillText(p,f,m+g*l+t.fontSizePx*.8,o)}),e.textAlign="left"}function At(e,t,n,r,o,i,a,s,l){const d=u.resolveBoxBorders(n.style);if(!d.inner)return;const c=u.resolveStroke(n.style);e.strokeStyle=c.color,e.lineWidth=u.ptToPx(c.widthPt,l);for(const m of t.edges)e.beginPath(),m.kind==="v"?(e.moveTo(r+m.pos*s,o+m.from*s),e.lineTo(r+m.pos*s,o+m.to*s)):(e.moveTo(r+m.from*s,o+m.pos*s),e.lineTo(r+m.to*s,o+m.pos*s)),e.stroke();_e(e,d,r,o,i,a)}function _e(e,t,n,r,o,i){e.beginPath(),t.top&&(e.moveTo(n,r),e.lineTo(n+o,r)),t.right&&(e.moveTo(n+o,r),e.lineTo(n+o,r+i)),t.bottom&&(e.moveTo(n+o,r+i),e.lineTo(n,r+i)),t.left&&(e.moveTo(n,r+i),e.lineTo(n,r)),e.stroke()}function Ct(e,t,n,r,o,i,a,s,l,d,c){const m=u.resolveGridLayout(t,i/s,a/s);for(const g of m.cells){const f=g.cell.style?.backgroundColor??n.style?.backgroundColor;f&&(e.fillStyle=f,e.fillRect(r+g.xMm*s,o+g.yMm*s,g.widthMm*s,g.heightMm*s))}At(e,m,n,r,o,i,a,s,l);const p=t.paddingMm??.5;for(const g of m.cells){const f=g.cell.text??"";if(!f)continue;const h=u.mergeComponentStyles(n.style,g.cell.style),y=u.resolveFontSize(h,l),M=Math.max(0,g.widthMm-2*p),w=N.wrapText(f,M,{fontSizePt:y.fontSizePt,bold:h.bold},c).join(`
3
+ `);Fe(e,{text:w,fontSizePx:y.fontSizePx,bold:h.bold??!1,italic:h.italic,color:u.resolveTextColor(h,$.DEFAULT_TEXT_COLOR),align:h.align??"left",lineHeight:u.resolveLineHeight(h)},r+(g.xMm+p)*s,o+(g.yMm+p)*s,M*s,Math.max(0,g.heightMm-2*p)*s,h.fontFamily??d,h.verticalAlign??"middle")}}function Rt(e,t,n,r,o,i,a,s,l){const d=t.style??{},c=u.resolveFontSize(d,a),m=$.isRichText(t)?t.richParagraphs.map(p=>p.segments.map(g=>g.text??g.field??"").join("")).join(`
4
4
  `):t.lines?.length?t.lines.join(`
5
- `):N.wrapText(t.text??"",t.widthMm,{fontSizePt:m.fontSizePt,bold:d.bold},l).join(`
6
- `);Ne(e,{text:f,fontSizePx:m.fontSizePx,bold:d.bold??!1,italic:d.italic,color:h.resolveTextColor(d),align:d.align??"left",lineHeight:h.resolveLineHeight(d)},n,i,o,r,d.fontFamily??s,d.verticalAlign)}function Le(e,t,n,i,o,r){const a=t.leftMm*n,s=t.topMm*n,l=t.widthMm*n,d=t.heightMm*n,m=t.style??{};if(t.grid){St(e,t.grid,t,a,s,l,d,n,i,o,r);return}switch(t.kind){case"text":{$t(e,t,a,s,l,d,i,o,r);break}case"rect":{const f=h.resolveStroke(m),p=h.resolveBoxBorders(m);m.backgroundColor&&(e.fillStyle=m.backgroundColor,e.fillRect(a,s,l,d)),p.inner&&(e.strokeStyle=f.color,e.lineWidth=h.ptToPx(f.widthPt,i),Re(e,p,a,s,l,d));break}case"line":{const f=h.resolveStroke({...m,borderColor:m.lineColor??m.borderColor});e.strokeStyle=f.color,e.lineWidth=h.ptToPx(f.widthPt,i),e.beginPath(),e.moveTo(a,s+d/2),e.lineTo(a+l,s+d/2),e.stroke();break}case"ellipse":{const f=h.resolveStroke(m);e.strokeStyle=f.color,e.lineWidth=h.ptToPx(f.widthPt,i),m.backgroundColor&&(e.fillStyle=m.backgroundColor,e.beginPath(),e.ellipse(a+l/2,s+d/2,l/2,d/2,0,0,Math.PI*2),e.fill()),e.beginPath(),e.ellipse(a+l/2,s+d/2,l/2,d/2,0,0,Math.PI*2),e.stroke();break}}}async function vt(e,t={}){if(typeof document>"u")throw new Error("renderPlanToImages 需要浏览器环境(SSR/Node 请在客户端钩子中调用)");const{format:n="png",quality:i=.92,...o}=t,{canvases:r}=Oe(e,o),a=n==="jpeg"?"image/jpeg":"image/png",s=[];for(const l of r)s.push(await new Promise(d=>l.toBlob(m=>d(m),a,i))??new Blob([],{type:a}));return{blobs:s}}function Oe(e,t={}){if(typeof document>"u")throw new Error("renderPlanToCanvas 需要浏览器环境(SSR 请在客户端钩子中调用)");const n=t.dpr??(typeof devicePixelRatio=="number"?devicePixelRatio:1),i=t.dpi??96,o=i/96*de,r=t.fontFamily??'"Microsoft YaHei", sans-serif',a=t.measurer??N.heuristicMeasurer,s=Math.max(0,t.start??0),l=Math.min(e.pages.length-1,t.end??e.pages.length-1),d=[];for(let m=s;m<=l;m++){const f=e.pages[m],{canvas:p,ctx:g}=Mt(f,n,i);for(const c of f.components)Le(g,c,o,i,r,a);d.push(p)}return{canvases:d}}function Tt(e,t={}){const n=t.dpr??(typeof devicePixelRatio=="number"?devicePixelRatio:1),i=t.dpi??96,o=i/96*de,r=t.fontFamily??'"Microsoft YaHei", sans-serif',a=t.measurer??N.heuristicMeasurer,s=t.overscan??1,l=t.gapPx??18,d=t.pagesPerFrame??1,m=e.pages.map(M=>M.pageHeightMm*o),f=Math.max(1,...e.pages.map(M=>M.pageWidthMm*o)),p={start:0,end:-1};let g=null,c=null,u=null,y=null,b=[],w=0,k=[];function S(){const M=g;M.innerHTML="",c=document.createElement("div"),c.style.cssText=`width:${f}px;margin:0 auto;`,u=document.createElement("div"),y=document.createElement("div"),c.appendChild(u),b=[];const R=Math.min(e.pages.length,3+s*2);for(let F=0;F<R;F++){const $=document.createElement("div");$.style.cssText=`margin:0 auto ${l}px;box-shadow:0 2px 8px rgba(0,0,0,.35);background:#fff;`,c.appendChild($),b.push($)}c.appendChild(y),M.appendChild(c)}function D(M,R){const F=e.pages[R],{widthPx:$,heightPx:A}=me(F,i);let L=M.firstElementChild;(!L||L.tagName!=="CANVAS")&&(L=document.createElement("canvas"),M.innerHTML="",M.appendChild(L)),L.width=Math.round($*n),L.height=Math.round(A*n),L.style.width=`${$}px`,L.style.height=`${A}px`;const G=L.getContext("2d");if(G){G.setTransform(1,0,0,1,0,0),G.scale(n,n),G.fillStyle="#ffffff",G.fillRect(0,0,$,A);for(const De of F.components)Le(G,De,o,i,r,a);L.dataset.canvasPage=String(R),M.style.height=`${A}px`,M.style.width=`${$}px`}}function V(M){p.start=M.start,p.end=M.end,u.style.height=`${M.start*l+m.slice(0,M.start).reduce(($,A)=>$+A,0)}px`;const R=e.pages.length-1-M.end;y.style.height=`${R*l+m.slice(M.end+1).reduce(($,A)=>$+A,0)}px`;const F=M.end-M.start+1;b.forEach(($,A)=>{if(A<F){$.style.display="";const L=M.start+A;$.style.height=`${m[L]??0}px`}else $.style.display="none"}),k=[];for(let $=M.start;$<=M.end;$++){const A=b[$-M.start];if(!A)continue;A.firstElementChild?.dataset?.canvasPage!==String($)&&k.push($)}z()}function z(){w||k.length===0||(w=requestAnimationFrame(()=>{w=0;let M=Math.max(1,d);for(;k.length>0&&M-- >0;){const R=k.shift(),F=b[R-p.start];F&&D(F,R)}k.length>0&&z()}))}function q(){w||(w=requestAnimationFrame(()=>{w=0;const M=g,R=Ce({pageHeightsPx:m,viewportHeightPx:M.clientHeight,scrollTopPx:M.scrollTop,overscan:s,gapPx:l});R.start!==p.start||R.end!==p.end?V(R):z()}))}let Y=null;return{attach(M){if(typeof document>"u")throw new Error("createCanvasPager 需要浏览器环境(SSR 请在客户端钩子中调用 attach)");g=M,S(),M.addEventListener("scroll",q,{passive:!0}),typeof ResizeObserver<"u"&&(Y=new ResizeObserver(()=>q()),Y.observe(M)),q()},destroy(){w&&cancelAnimationFrame(w),w=0,Y?.disconnect(),Y=null,g?.removeEventListener("scroll",q),k=[],c?.remove(),g=null},window(){return{...p}}}}function ce(e,t,n){let i,o;if(typeof e=="string"){const r=h.PAPER_SIZES[e];if(!r)throw new Error(`未知纸张预设 "${e}"(可用:${Object.keys(h.PAPER_SIZES).join("/")})`);i=r.widthMm,o=r.heightMm}else typeof e=="number"?(i=e,o=t??297):(i=e.widthMm,o=e.heightMm);return n?{widthMm:o,heightMm:i}:{widthMm:i,heightMm:o}}class _e{constructor(){this.pages=[],this.pending=null,this.templateParams=void 0}params(t){return this.templateParams=t,this}page(t="a4",n={},i){this.collect();const r=i!=null&&!("margins"in i)&&!("landscape"in i)&&("marginTopMm"in i||"marginBottomMm"in i||"marginLeftMm"in i||"marginRightMm"in i)?{margins:i}:typeof n=="number"?i??{}:n,{widthMm:a,heightMm:s}=ce(t,typeof n=="number"?n:void 0,r.landscape),l=r.margins??{};return this.pending=new Fe(this,{widthMm:a,heightMm:s,marginTopMm:l.marginTopMm??10,marginBottomMm:l.marginBottomMm??10,marginLeftMm:l.marginLeftMm??10,marginRightMm:l.marginRightMm??10}),this.pending}collect(){this.pending&&(this.pages.push(this.pending.buildPage()),this.pending=null)}build(){if(this.collect(),this.pages.length===0)throw new Error("模板至少需要一页:先调用 .page() 添加内容");return this.templateParams?{params:this.templateParams,pages:this.pages}:{pages:this.pages}}}class Fe{constructor(t,n){this.parent=t,this.page=n,this.components=[]}text(t,n={},i={}){return this.components.push({kind:"text",leftMm:n.leftMm??0,topMm:n.topMm??0,widthMm:n.widthMm??60,heightMm:n.heightMm??8,text:t,style:i}),this}list(t,n,i,o={}){return this.components.push({kind:"list",leftMm:n.leftMm??10,topMm:n.topMm??30,widthMm:n.widthMm??180,dataset:t,columns:i,...o}),this}rect(t,n={}){return this.components.push({kind:"rect",...t,style:n}),this}line(t,n,i,o={}){return this.components.push({kind:"line",leftMm:t,topMm:n,widthMm:i,heightMm:.5,style:o}),this}barcode(t,n){return this.components.push({kind:"barcode",leftMm:n.leftMm??0,topMm:n.topMm??0,widthMm:n.widthMm??40,heightMm:n.heightMm??12,fallbackText:t}),this}qrcode(t,n,i,o){return this.components.push({kind:"qrcode",leftMm:i,topMm:o,widthMm:n,heightMm:n,fallbackText:t}),this}buildPage(){return{...this.page,components:this.components}}done(){return this.parent}build(){return this.done().build()}}function Et(){return new _e}function O(e,t,n=!1){if(!Number.isFinite(e)||(n?e<0:e<=0))throw new Error(`${t} 必须是有限${n?"非负":"正"}数`)}function X(e,t,n){if(e!==void 0&&!["left","center","right","justify",...n?["auto"]:[]].includes(e))throw new Error(`${t} 必须是 left/center/right/justify${n?"/auto":""}`)}function Pt(e){const t=e.layout??"page";if(t!=="page"&&t!=="wide")throw new Error("layout 必须是 page 或 wide");if(t==="wide"&&(e.paper!==void 0||e.landscape!==void 0))throw new Error('宽表布局不能同时指定 paper 或 landscape;标准纸型请使用 layout: "page"');if(t!=="wide"&&e.columnWidthMm!==void 0)throw new Error('columnWidthMm 仅适用于 layout: "wide"');const n=e.columnWidthMm??30;return O(n,"columnWidthMm"),{layout:t,columnWidthMm:n}}function kt(e){const t=e.paper===void 0?"a4":e.paper;if(typeof t!="string"&&(typeof t!="object"||t===null)||e.landscape!==void 0&&typeof e.landscape!="boolean")throw new Error("paper 必须是纸张预设名或 { widthMm, heightMm } 对象,landscape 必须是布尔值");if(typeof t=="string"&&!Object.prototype.hasOwnProperty.call(h.PAPER_SIZES,t))throw new Error(`未知纸张预设 "${t}"(可用:${Object.keys(h.PAPER_SIZES).join("/")})`);const n=ce(t,void 0,e.landscape),i=n.widthMm,o=n.heightMm;return O(i,"纸张 widthMm"),O(o,"纸张 heightMm"),{widthMm:i,heightMm:o}}function At(e){if(e.margins!==void 0&&(!e.margins||typeof e.margins!="object"||Array.isArray(e.margins)))throw new Error("margins 必须是页边距对象");const t=e.margins??{},n={marginTopMm:t.marginTopMm===void 0?10:t.marginTopMm,marginBottomMm:t.marginBottomMm===void 0?10:t.marginBottomMm,marginLeftMm:t.marginLeftMm===void 0?10:t.marginLeftMm,marginRightMm:t.marginRightMm===void 0?10:t.marginRightMm};for(const[i,o]of Object.entries(n))O(o,i,!0);return n}function xt(e,t){const n=e.dataset===void 0?"detail":e.dataset;if(typeof n!="string"||!n.trim())throw new Error("dataset 必须是非空字符串");if(e.title!==void 0&&typeof e.title!="string")throw new Error("title 必须是字符串");const i=e.titleHeightMm===void 0?10:e.titleHeightMm,o=e.titleGapMm===void 0?4:e.titleGapMm;O(i,"titleHeightMm"),O(o,"titleGapMm",!0);const r=e.title!==void 0&&e.title.length>0,a=r?i+o:0;if(a>=t)throw new Error("标题高度与间距占满页面,必须为表格保留可用高度");return{dataset:n,titleHeightMm:i,hasTitle:r,titleSpaceMm:a}}function Ct(e){if(e.listOptions!==void 0&&(!e.listOptions||typeof e.listOptions!="object"||Array.isArray(e.listOptions)))throw new Error("listOptions 必须是列表配置对象");const t=e.listOptions??{};X(t.align,"listOptions.align",!0),X(t.headerAlign,"listOptions.headerAlign",!1);for(const n of["fontSizePt","rowHeightMm","paddingMm"]){const i=t[n];i!==void 0&&O(i,`listOptions.${n}`,n==="paddingMm")}return t}function Nt(e){let t=0,n=0;for(const[i,o]of e.entries()){if(!o||typeof o.header!="string"||typeof o.field!="string"||!o.field.trim())throw new Error(`columns[${i}] 需要字符串 header 与非空 field`);X(o.align,`columns[${i}].align`,!0),X(o.headerAlign,`columns[${i}].headerAlign`,!1),o.flex!==void 0&&O(o.flex,`columns[${i}].flex`),o.widthMm!==void 0?(O(o.widthMm,`columns[${i}].widthMm`),t+=o.widthMm):n=Math.max(n,o.flex??1)}return{fixedWidthMm:t,maxFlex:n}}function Rt(e,t,n,i){const{fixedWidthMm:o,maxFlex:r}=Nt(e.columns);if(t==="page"&&o>i)throw new Error(`固定列宽 ${o}mm 超出页面可用宽度 ${i}mm`);const a=i-o;if(t==="page"&&r>0&&a<=0)throw new Error("固定列占满页面可用宽度,自动列需要正的剩余宽度");const s=r>0?e.columns.reduce((d,m)=>d+(m.widthMm===void 0?(m.flex??1)/r:0),0):0;return{columns:e.columns.map(({widthMm:d,flex:m,...f},p)=>{const g=d??(t==="wide"?n*(m??1):a*((m??1)/r)/s);return O(g,`columns[${p}] 分配后的 widthMm`),{...f,widthMm:g}}),fixedWidthMm:o,maxFlex:r}}function Lt(e){if(!e||typeof e!="object")throw new Error("标准明细模板需要 options 对象");if(!Array.isArray(e.columns)||e.columns.length===0)throw new Error("columns 至少需要一列");const{layout:t,columnWidthMm:n}=Pt(e),i=kt(e);let o=i.widthMm;const r=i.heightMm,a=At(e);let s=o-a.marginLeftMm-a.marginRightMm;const l=r-a.marginTopMm-a.marginBottomMm;if(t==="page"&&s<=0||l<=0)throw new Error("页边距占满纸张,必须保留正的可用宽度和高度");const{dataset:d,titleHeightMm:m,hasTitle:f,titleSpaceMm:p}=xt(e,l),g=Ct(e),{columns:c,fixedWidthMm:u,maxFlex:y}=Rt(e,t,n,s);t==="wide"&&(s=c.reduce((w,k)=>w+k.widthMm,0),O(s,"宽表总列宽"),o=s+a.marginLeftMm+a.marginRightMm,O(o,"宽表总宽度"));const b={widthMm:o,heightMm:r,...a,components:[],...t==="wide"?{layout:t}:{}};return f&&b.components.push({kind:"text",text:e.title,leftMm:a.marginLeftMm,topMm:a.marginTopMm,widthMm:s,heightMm:m,style:{fontSize:16,bold:!0,align:"center",verticalAlign:"middle",...e.titleStyle}}),b.components.push({align:"auto",headerAlign:"center",...g,kind:"list",...t==="wide"?{layout:t}:{},...f?{title:e.title}:{},dataset:d,columns:c,leftMm:a.marginLeftMm,topMm:a.marginTopMm+p,widthMm:t==="wide"||y>0?s:u}),e.params===void 0?{pages:[b]}:{params:e.params,pages:[b]}}const fe="1.0";class W extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(n=>`${n.path}: ${n.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Ot=new Set(["__proto__","prototype","constructor"]),_t=new Set(["schemaVersion","id","name","revision","description","template"]),Ft=new Set(["left","center","right","justify"]),ne=2e5,Ht=64,he=1e7;function v(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function It(e,t,n){const i=Object.getPrototypeOf(e),o=Array.isArray(e);if(o?i!==Array.prototype:i!==Object.prototype&&i!==null)return n.push({path:t,message:"模板对象必须使用普通 JSON 对象原型"}),!1;if(o){const r=Object.keys(e);if(r.length!==e.length||r.some(a=>!/^(0|[1-9]\d*)$/.test(a)||Number(a)>=e.length))return n.push({path:t,message:"模板数组不能包含空位或额外属性"}),!1}return Object.getOwnPropertySymbols(e).length>0?(n.push({path:t,message:"模板不能包含 Symbol 键"}),!1):!0}function Bt(e,t,n,i){return Ot.has(e)?(i.push({path:n,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(i.push({path:n,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function Dt(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function ue(e,t){const n=new Set;let i=0,o=0,r=!1;const a=(s,l,d)=>{if(!r){if(++i>ne){i===ne+1&&t.push({path:l,message:"模板超过 JSON 节点安全上限"});return}if(d>Ht){t.push({path:l,message:"模板嵌套层级过深"});return}if(typeof s=="string"){o+=s.length,o>he&&(r=!0,t.push({path:l,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!Dt(s)){if(!s||typeof s!="object"){t.push({path:l,message:"模板只允许 JSON 值,不允许函数、undefined 或非有限数字"});return}if(n.has(s)){t.push({path:l,message:"模板不能包含循环引用"});return}if(It(s,l,t)){n.add(s);for(const[m,f]of Object.entries(Object.getOwnPropertyDescriptors(s))){if(Array.isArray(s)&&m==="length")continue;const p=`${l}.${m}`;if(Bt(m,f,p,t)&&a(f.value,p,d+1),i>ne||r)break}n.delete(s)}}}};a(e,"$",0)}function E(e,t,n,i,o=!1){const r=e[t];r===void 0&&!o||(typeof r!="string"||o&&!r.trim())&&i.push({path:`${n}.${t}`,message:o?"应为非空字符串":"应为字符串"})}function x(e,t,n,i,o=0,r=!1){const a=e[t];a===void 0&&!r||(typeof a!="number"||!Number.isFinite(a)||a<o)&&i.push({path:`${n}.${t}`,message:`应为大于等于 ${o} 的有限数字`})}function U(e,t,n,i){e[t]!==void 0&&typeof e[t]!="boolean"&&i.push({path:`${n}.${t}`,message:"应为布尔值"})}function J(e,t,n,i=!1){e!==void 0&&!Ft.has(e)&&!(i&&e==="auto")&&n.push({path:t,message:`未知对齐方式${i?"(支持 auto)":""}`})}function I(e,t,n){if(e!==void 0){if(!v(e)){n.push({path:t,message:"样式应为对象"});return}J(e.align,`${t}.align`,n),e.verticalAlign!==void 0&&!["top","middle","bottom"].includes(e.verticalAlign)&&n.push({path:`${t}.verticalAlign`,message:"未知垂直对齐方式"});for(const i of["fontSize","fontSizePx","lineWidthPt","lineHeight"])x(e,i,t,n);for(const i of["letterSpacing","rotateDeg"])x(e,i,t,n,-1/0);x(e,"opacity",t,n),typeof e.opacity=="number"&&e.opacity>1&&n.push({path:`${t}.opacity`,message:"透明度不能大于 1"});for(const i of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])U(e,i,t,n);for(const i of["fontFamily","color","backgroundColor","lineColor","borderColor"])E(e,i,t,n)}}function zt(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push({path:t,message:"参数定义应为数组"});return}const i=new Set;e.forEach((o,r)=>{const a=`${t}.${r}`;if(!v(o)){n.push({path:a,message:"参数定义应为对象"});return}E(o,"field",a,n,!0),typeof o.field=="string"&&(i.has(o.field)&&n.push({path:`${a}.field`,message:"参数名重复"}),i.add(o.field)),o.type!==void 0&&!["text","number","date","select"].includes(o.type)&&n.push({path:`${a}.type`,message:"未知参数类型"});for(const s of["label","defaultValue","placeholder"])E(o,s,a,n);U(o,"required",a,n),o.options!==void 0&&(Array.isArray(o.options)?o.options.forEach((s,l)=>{const d=`${a}.options.${l}`;if(!v(s))n.push({path:d,message:"选项应为对象"});else for(const m of["label","value"])typeof s[m]!="string"&&n.push({path:`${d}.${m}`,message:"选项标签与值应为字符串(允许空白选项)"})}):n.push({path:`${a}.options`,message:"选项应为数组"}))})}function jt(e,t,n){if(!Array.isArray(e)||e.length===0){n.push({path:t,message:"列表至少需要一列"});return}e.forEach((i,o)=>{const r=`${t}.${o}`;if(!v(i)){n.push({path:r,message:"列应为对象"});return}if(typeof i.header!="string"&&n.push({path:`${r}.header`,message:"表头应为字符串(允许空白表头)"}),E(i,"field",r,n,!0),x(i,"widthMm",r,n,Number.MIN_VALUE,!0),I(i.style,`${r}.style`,n),I(i.headerStyle,`${r}.headerStyle`,n),J(i.align,`${r}.align`,n,!0),J(i.headerAlign,`${r}.headerAlign`,n),i.format!==void 0)if(!v(i.format)||!["number","percent","date"].includes(i.format.kind))n.push({path:`${r}.format`,message:"未知列格式"});else{const a=i.format.digits;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>100)&&n.push({path:`${r}.format.digits`,message:"小数位应为 0–100 的整数"}),U(i.format,"thousands",`${r}.format`,n),E(i.format,"pattern",`${r}.format`,n)}i.rules!==void 0&&(Array.isArray(i.rules)?i.rules.forEach((a,s)=>{const l=`${r}.rules.${s}`;if(!v(a)||!v(a.when)){n.push({path:l,message:"条件格式缺少 when 对象"});return}E(a.when,"field",`${l}.when`,n,!0),[">",">=","<","<=","==","!="].includes(a.when.op)||n.push({path:`${l}.when.op`,message:"未知条件运算符"}),typeof a.when.value!="number"&&typeof a.when.value!="string"&&n.push({path:`${l}.when.value`,message:"条件值应为数字或字符串"}),I(a.style,`${l}.style`,n)}):n.push({path:`${r}.rules`,message:"条件格式应为数组"}))})}function Wt(e,t,n){if(e!==void 0){if(!v(e)){n.push({path:t,message:"分组应为对象"});return}E(e,"field",t,n,!0);for(const i of["headerTemplate","subtotalLabel"])E(e,i,t,n);for(const i of["headerStyle","subtotalStyle"])I(e[i],`${t}.${i}`,n);U(e,"keepWithNext",t,n),e.subtotal!==void 0&&(!Array.isArray(e.subtotal)||e.subtotal.some(i=>typeof i!="string"))&&n.push({path:`${t}.subtotal`,message:"小计字段应为字符串数组"})}}function Vt(e,t,n){if(!(e===void 0||typeof e=="boolean")){if(!v(e)){n.push({path:t,message:"合计应为布尔值或对象"});return}E(e,"label",t,n),I(e.style,`${t}.style`,n),e.fields!==void 0&&(!Array.isArray(e.fields)||e.fields.some(i=>typeof i!="string"))&&n.push({path:`${t}.fields`,message:"合计字段应为字符串数组"})}}function Gt(e,t,n){for(const i of["leftMm","topMm"])x(e,i,t,n,-1/0,!0);x(e,"widthMm",t,n,Number.MIN_VALUE,!0),E(e,"dataset",t,n,!0),E(e,"title",t,n),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&n.push({path:`${t}.layout`,message:"布局应为 page 或 wide"}),jt(e.columns,`${t}.columns`,n);for(const i of["fontSizePt","rowHeightMm"])x(e,i,t,n,Number.MIN_VALUE);x(e,"paddingMm",t,n);for(const i of["headerBold","headerEveryPage","border"])U(e,i,t,n);E(e,"headerBackgroundColor",t,n),J(e.align,`${t}.align`,n,!0),J(e.headerAlign,`${t}.headerAlign`,n),I(e.headerStyle,`${t}.headerStyle`,n),Wt(e.groupBy,`${t}.groupBy`,n),Vt(e.grandTotal,`${t}.grandTotal`,n)}function He(e,t,n){I(e.style,`${t}.style`,n);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])E(e,o,t,n);if(e.lines!==void 0&&(!Array.isArray(e.lines)||e.lines.some(o=>typeof o!="string"))&&n.push({path:`${t}.lines`,message:"文本行应为字符串数组"}),Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((o,r)=>{if(!v(o))return;const a=`${t}.richParagraphs.${r}`;J(o.align,`${a}.align`,n);for(const s of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])x(o,s,a,n);Array.isArray(o.segments)&&o.segments.forEach((s,l)=>{const d=`${a}.segments.${l}`;if(!v(s)){n.push({path:d,message:"富文本片段应为对象"});return}s.kind!==void 0&&s.kind!=="text"&&s.kind!=="field"&&n.push({path:`${d}.kind`,message:"未知富文本片段类型"});for(const m of["text","field"])E(s,m,d,n);I(s.style,`${d}.style`,n)})}),!v(e.grid))return;const i=e.grid;x(i,"gapMm",`${t}.grid`,n),x(i,"paddingMm",`${t}.grid`,n);for(const o of["colWidthsMm","rowHeightsMm"]){const r=i[o];r!==void 0&&(!Array.isArray(r)||r.some(a=>typeof a!="number"||!Number.isFinite(a)||a<0))&&n.push({path:`${t}.grid.${o}`,message:"网格尺寸应为有限非负数字数组"})}Array.isArray(i.cells)&&i.cells.forEach((o,r)=>{Array.isArray(o)&&o.forEach((a,s)=>{const l=`${t}.grid.cells.${r}.${s}`;if(a!==null){if(!v(a)){n.push({path:l,message:"网格单元格应为对象或 null"});return}for(const d of["text","rawText","numberFormat"])E(a,d,l,n);for(const d of["colSpan","rowSpan"]){const m=a[d];m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<=0)&&n.push({path:`${l}.${d}`,message:"跨度应为正整数"})}a.value!==void 0&&a.value!==null&&!["string","number","boolean"].includes(typeof a.value)&&n.push({path:`${l}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),I(a.style,`${l}.style`,n),a.children!==void 0&&(Array.isArray(a.children)?a.children.forEach((d,m)=>{v(d)&&He(d,`${l}.children.${m}`,n)}):n.push({path:`${l}.children`,message:"嵌套组件应为数组"}))}})})}function ge(e){const t=[],n=[];return ue(e,t),t.length?{ok:!1,errors:t,warnings:n}:(v(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==B.RENDER_PLAN_SCHEMA_VERSION&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),zt(e.params,"$.params",t),!Array.isArray(e.pages)||e.pages.length===0?t.push({path:"$.pages",message:"模板至少需要一页"}):e.pages.forEach((i,o)=>{const r=`$.pages.${o}`;if(!v(i)){t.push({path:r,message:"页应为对象"});return}x(i,"widthMm",r,t,Number.MIN_VALUE,!0),x(i,"heightMm",r,t,Number.MIN_VALUE,!0),i.layout!==void 0&&i.layout!=="page"&&i.layout!=="wide"&&t.push({path:`${r}.layout`,message:"布局应为 page 或 wide"}),typeof i.heightMm=="number"&&i.heightMm>=5e3&&t.push({path:`${r}.heightMm`,message:"页高应小于 5000mm"});for(const a of["marginTopMm","marginBottomMm","marginLeftMm","marginRightMm"])x(i,a,r,t);typeof i.widthMm=="number"&&Number(i.marginLeftMm??0)+Number(i.marginRightMm??0)>=i.widthMm&&t.push({path:r,message:"横向页边距占满页面"}),typeof i.heightMm=="number"&&Number(i.marginTopMm??0)+Number(i.marginBottomMm??0)>=i.heightMm&&t.push({path:r,message:"纵向页边距占满页面"}),Array.isArray(i.components)?i.components.forEach((a,s)=>{const l=`${r}.components.${s}`;v(a)&&a.kind==="list"?Gt(a,l,t):(Q(a,l,t,n),v(a)&&He(a,l,t))}):t.push({path:`${r}.components`,message:"组件应为数组"})})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:n})}function Ie(e){const t=[],n=[];if(ue(e,t),t.length)return{ok:!1,errors:t,warnings:n};if(!v(e))t.push({path:"$",message:"模板文档应为对象"});else{for(const o of Object.keys(e))_t.has(o)||t.push({path:`$.${o}`,message:"模板文档存在未知字段;只保存模板与描述,不保存取数或业务数据"});e.schemaVersion!==fe&&t.push({path:"$.schemaVersion",message:"不支持的模板文档版本"});for(const o of["id","name"])E(e,o,"$",t,!0);for(const o of["revision","description"])E(e,o,"$",t);const i=ge(e.template);t.push(...i.errors.map(o=>({...o,path:`$.template${o.path.slice(1)}`}))),n.push(...i.warnings.map(o=>({...o,path:`$.template${o.path.slice(1)}`})))}return{ok:t.length===0,errors:t,warnings:n}}function ee(e){const t=Ie(e);if(!t.ok)throw new W(t.errors)}function Jt(e){const t=[];if(ue(e,t),t.length)throw new W(t);const n={...e,schemaVersion:e.schemaVersion??fe};return ee(n),Z(n)}function Ut(e){let t=e;if(typeof e=="string"){if(e.length>he)throw new W([{path:"$",message:"模板 JSON 超过 1000 万字符的导出/导入上限"}]);try{t=JSON.parse(e)}catch{throw new W([{path:"$",message:"模板 JSON 语法无效"}])}}return ee(t),Z(t)}function qt(e){ee(e);const t=JSON.stringify(e,null,2);if(t.length>he)throw new W([{path:"$",message:"模板 JSON 超过 1000 万字符的导出/导入上限"}]);return t}function Z(e){return JSON.parse(JSON.stringify(e))}function Yt(e=[]){const t=new Map,n={get:i=>{const o=t.get(i);return o?Z(o):void 0},list:()=>Array.from(t.values(),({template:i,...o})=>({...o})),register:(i,o={})=>{if(ee(i),t.has(i.id)&&!o.replace)throw new W([{path:"$.id",message:`模板 ID ${i.id} 已注册;更新需显式 replace:true`}]);t.set(i.id,Z(i))},remove:i=>t.delete(i)};for(const i of e)n.register(i);return n}function Kt(e){if(!("mapData"in e))return e;const{load:t,mapData:n,...i}=e;return{...i,load:async o=>{const r=await t(o);H(o.signal);try{return n(r,o)}catch(a){throw new C("validate",`报表 ${o.reportId} 数据映射失败`,a)}}}}class C extends Error{constructor(t,n,i){super(n),this.name="ReportSourceError",this.code=t,this.cause=i}}function te(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function H(e){if(e?.aborted)throw te(e)}function Be(e,t){return t?new Promise((n,i)=>{const o=()=>t.removeEventListener("abort",r),r=()=>{o(),i(te(t))};t.addEventListener("abort",r,{once:!0}),t.aborted&&r(),Promise.resolve(e).then(a=>{o(),n(a)},a=>{o(),i(a)})}):Promise.resolve(e)}function Xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new C("validate",`报表 ${t} 的数据集应为对象`);for(const[n,i]of Object.entries(e))if(!Array.isArray(i)||i.some(o=>!o||typeof o!="object"||Array.isArray(o)))throw new C("validate",`报表 ${t} 的数据集 ${n} 应为对象数组`)}async function Zt(e,t,n){const{reportId:i,signal:o}=t;try{const r=await Be(e(t),o);H(o);const a=ge(r);if(!a.ok)throw new C("validate",`报表 ${i} 模板校验失败:${a.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")}`);return n.push(...a.warnings.map(s=>`${i}: ${s.path}: ${s.message}`)),r}catch(r){throw o?.aborted?te(o):r instanceof C?r:r instanceof W?new C("validate",`报表 ${i} 模板校验失败:${r.message}`,r):new C("fetch",`报表 ${i} 模板加载失败:${r instanceof Error?r.message:String(r)}`,r)}}async function Qt(e,t,n,i){let o;try{o=await Be(e.load?e.load(t):e.datasets??{},i)}catch(r){throw i?.aborted?te(i):r instanceof C?r:new C("fetch",`报表 ${n} 取数失败:${r instanceof Error?r.message:String(r)}`,r)}return H(i),Xt(o,n),o}function en(e,t,n,i){try{return ke(e,t,n.pagination)}catch(o){throw new C("validate",`报表 ${i} 排版失败:${o instanceof Error?o.message:String(o)}`,o)}}function tn(e,t,n,i){const o=new Map,r=a=>{let s=o.get(a);return s===void 0&&(s=JSON.stringify([n,i,a]),o.set(a,s)),s};for(const a of t.pages)e.push({...a,components:a.components.map(s=>s.table?{...s,table:{...s.table,id:r(s.table.id)}}:s)})}function nn(e,t={}){function n(o){const r=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!r)throw new C("config",`未注册报表 ${o}`);return r}return Object.assign(async({reportIds:o,params:r,signal:a,onWarning:s})=>{H(a);const l=[...o],d={...r};if(l.length===0)throw new C("config","缺少报表 ID");const m=l.map(n),f=[],p=[];for(const[y,b]of m.entries()){H(a);const w=l[y],k={reportId:w,params:{...d},signal:a},S=typeof b.template=="function"?await Zt(b.template,k,p):b.template,D=await Qt(b,k,w,a);H(a);const V=en(S,D,b,w);tn(f,V.plan,y,w),p.push(...V.warnings.map(z=>`${w}: ${z}`))}H(a);const g={schemaVersion:B.RENDER_PLAN_SCHEMA_VERSION,pages:f},c=se(g);if(!c.ok)throw new C("validate",`渲染计划校验失败:${c.errors.slice(0,3).map(y=>`${y.path}: ${y.message}`).join("; ")}`);p.push(...c.warnings.map(y=>`${y.path}: ${y.message}`));const u=s??t.onWarning??(y=>console.warn("[mach-report]",y));for(const y of p)H(a),u(y);return H(a),g},{getParamDefs:o=>je.getReportParamDefs(e,o)})}exports.DEFAULT_BORDER_PT=_.DEFAULT_BORDER_PT;exports.DEFAULT_FONT_PT=_.DEFAULT_FONT_PT;exports.DEFAULT_STROKE_COLOR=_.DEFAULT_STROKE_COLOR;exports.DEFAULT_TEXT_COLOR=_.DEFAULT_TEXT_COLOR;exports.LINE_HEIGHT=_.LINE_HEIGHT;exports.SCHEMA_VERSION_MACH=_.SCHEMA_VERSION_MACH;exports.CSS_DPI=h.CSS_DPI;exports.MM_PER_INCH=h.MM_PER_INCH;exports.PAPER_SIZES=h.PAPER_SIZES;exports.mergeComponentStyles=h.mergeComponentStyles;exports.mmToPx=h.mmToPx;exports.mmToPxFactor=h.mmToPxFactor;exports.ptToPx=h.ptToPx;exports.pxToMm=h.pxToMm;exports.resolveBoxBorders=h.resolveBoxBorders;exports.resolveFontSize=h.resolveFontSize;exports.resolveGridLayout=h.resolveGridLayout;exports.resolveLineHeight=h.resolveLineHeight;exports.resolveStroke=h.resolveStroke;exports.resolveTextColor=h.resolveTextColor;exports.round=h.round;exports.RENDER_PLAN_SCHEMA_VERSION=B.RENDER_PLAN_SCHEMA_VERSION;exports.isImageBackedComponent=B.isImageBackedComponent;exports.isRichText=B.isRichText;exports.charWidthEm=N.charWidthEm;exports.createCanvasMeasurer=N.createCanvasMeasurer;exports.createHeuristicMeasurer=N.createHeuristicMeasurer;exports.heuristicMeasurer=N.heuristicMeasurer;exports.measureTextMm=N.measureTextMm;exports.wrapText=N.wrapText;exports.PageBuilder=Fe;exports.REPORT_TEMPLATE_DOCUMENT_VERSION=fe;exports.ReportSourceError=C;exports.ReportTemplateError=W;exports.TemplateBuilder=_e;exports.assertRenderPlan=Ke;exports.classOf=P;exports.computePageWindow=Ce;exports.createCanvasPager=Tt;exports.createReportSource=nn;exports.createTableTemplate=Lt;exports.createTemplate=Et;exports.createTemplateRegistry=Yt;exports.defineReport=Kt;exports.defineReportTemplate=Jt;exports.evalStyleRule=we;exports.formatValue=ae;exports.measurePageSizePx=me;exports.paginateTemplate=ke;exports.parseDateLocal=be;exports.parseReportTemplate=Ut;exports.planFontSizePx=bt;exports.renderComponent=le;exports.renderPage=xe;exports.renderPlan=yt;exports.renderPlanToCanvas=Oe;exports.renderPlanToImages=vt;exports.resolvePaper=ce;exports.serializeReportTemplate=qt;exports.toExcelNumberFormat=re;exports.toNumber=K;exports.validateComponent=Q;exports.validatePage=Se;exports.validateRenderPlan=se;exports.validateReportTemplate=ge;exports.validateReportTemplateDocument=Ie;
5
+ `):N.wrapText(t.text??"",t.widthMm,{fontSizePt:c.fontSizePt,bold:d.bold},l).join(`
6
+ `);Fe(e,{text:m,fontSizePx:c.fontSizePx,bold:d.bold??!1,italic:d.italic,color:u.resolveTextColor(d),align:d.align??"left",lineHeight:u.resolveLineHeight(d)},n,r,o,i,d.fontFamily??s,d.verticalAlign)}function He(e,t,n,r,o,i){const a=t.leftMm*n,s=t.topMm*n,l=t.widthMm*n,d=t.heightMm*n,c=t.style??{};if(t.grid){Ct(e,t.grid,t,a,s,l,d,n,r,o,i);return}switch(t.kind){case"text":{Rt(e,t,a,s,l,d,r,o,i);break}case"rect":{const m=u.resolveStroke(c),p=u.resolveBoxBorders(c);c.backgroundColor&&(e.fillStyle=c.backgroundColor,e.fillRect(a,s,l,d)),p.inner&&(e.strokeStyle=m.color,e.lineWidth=u.ptToPx(m.widthPt,r),_e(e,p,a,s,l,d));break}case"line":{const m=u.resolveStroke({...c,borderColor:c.lineColor??c.borderColor});e.strokeStyle=m.color,e.lineWidth=u.ptToPx(m.widthPt,r),e.beginPath(),e.moveTo(a,s+d/2),e.lineTo(a+l,s+d/2),e.stroke();break}case"ellipse":{const m=u.resolveStroke(c);e.strokeStyle=m.color,e.lineWidth=u.ptToPx(m.widthPt,r),c.backgroundColor&&(e.fillStyle=c.backgroundColor,e.beginPath(),e.ellipse(a+l/2,s+d/2,l/2,d/2,0,0,Math.PI*2),e.fill()),e.beginPath(),e.ellipse(a+l/2,s+d/2,l/2,d/2,0,0,Math.PI*2),e.stroke();break}}}async function Nt(e,t={}){if(typeof document>"u")throw new Error("renderPlanToImages 需要浏览器环境(SSR/Node 请在客户端钩子中调用)");const{format:n="png",quality:r=.92,...o}=t,{canvases:i}=Be(e,o),a=n==="jpeg"?"image/jpeg":"image/png",s=[];for(const l of i)s.push(await new Promise(d=>l.toBlob(c=>d(c),a,r))??new Blob([],{type:a}));return{blobs:s}}function Be(e,t={}){if(typeof document>"u")throw new Error("renderPlanToCanvas 需要浏览器环境(SSR 请在客户端钩子中调用)");const n=t.dpr??(typeof devicePixelRatio=="number"?devicePixelRatio:1),r=t.dpi??96,o=r/96*me,i=t.fontFamily??'"Microsoft YaHei", sans-serif',a=t.measurer??N.heuristicMeasurer,s=Math.max(0,t.start??0),l=Math.min(e.pages.length-1,t.end??e.pages.length-1),d=[];for(let c=s;c<=l;c++){const m=e.pages[c],{canvas:p,ctx:g}=Pt(m,n,r);for(const f of m.components)He(g,f,o,r,i,a);d.push(p)}return{canvases:d}}function It(e,t={}){const n=t.dpr??(typeof devicePixelRatio=="number"?devicePixelRatio:1),r=t.dpi??96,o=r/96*me,i=t.fontFamily??'"Microsoft YaHei", sans-serif',a=t.measurer??N.heuristicMeasurer,s=t.overscan??1,l=t.gapPx??18,d=t.pagesPerFrame??1,c=e.pages.map(b=>b.pageHeightMm*o),m=Math.max(1,...e.pages.map(b=>b.pageWidthMm*o)),p={start:0,end:-1};let g=null,f=null,h=null,y=null,M=[],w=0,k=[];function v(){const b=g;b.innerHTML="",f=document.createElement("div"),f.style.cssText=`width:${m}px;margin:0 auto;`,h=document.createElement("div"),y=document.createElement("div"),f.appendChild(h),M=[];const I=Math.min(e.pages.length,3+s*2);for(let F=0;F<I;F++){const S=document.createElement("div");S.style.cssText=`margin:0 auto ${l}px;box-shadow:0 2px 8px rgba(0,0,0,.35);background:#fff;`,f.appendChild(S),M.push(S)}f.appendChild(y),b.appendChild(f)}function D(b,I){const F=e.pages[I],{widthPx:S,heightPx:A}=fe(F,r);let L=b.firstElementChild;(!L||L.tagName!=="CANVAS")&&(L=document.createElement("canvas"),b.innerHTML="",b.appendChild(L)),L.width=Math.round(S*n),L.height=Math.round(A*n),L.style.width=`${S}px`,L.style.height=`${A}px`;const G=L.getContext("2d");if(G){G.setTransform(1,0,0,1,0,0),G.scale(n,n),G.fillStyle="#ffffff",G.fillRect(0,0,S,A);for(const Ue of F.components)He(G,Ue,o,r,i,a);L.dataset.canvasPage=String(I),b.style.height=`${A}px`,b.style.width=`${S}px`}}function V(b){p.start=b.start,p.end=b.end,h.style.height=`${b.start*l+c.slice(0,b.start).reduce((S,A)=>S+A,0)}px`;const I=e.pages.length-1-b.end;y.style.height=`${I*l+c.slice(b.end+1).reduce((S,A)=>S+A,0)}px`;const F=b.end-b.start+1;M.forEach((S,A)=>{if(A<F){S.style.display="";const L=b.start+A;S.style.height=`${c[L]??0}px`}else S.style.display="none"}),k=[];for(let S=b.start;S<=b.end;S++){const A=M[S-b.start];if(!A)continue;A.firstElementChild?.dataset?.canvasPage!==String(S)&&k.push(S)}z()}function z(){w||k.length===0||(w=requestAnimationFrame(()=>{w=0;let b=Math.max(1,d);for(;k.length>0&&b-- >0;){const I=k.shift(),F=M[I-p.start];F&&D(F,I)}k.length>0&&z()}))}function K(){w||(w=requestAnimationFrame(()=>{w=0;const b=g,I=Oe({pageHeightsPx:c,viewportHeightPx:b.clientHeight,scrollTopPx:b.scrollTop,overscan:s,gapPx:l});I.start!==p.start||I.end!==p.end?V(I):z()}))}let q=null;return{attach(b){if(typeof document>"u")throw new Error("createCanvasPager 需要浏览器环境(SSR 请在客户端钩子中调用 attach)");g=b,v(),b.addEventListener("scroll",K,{passive:!0}),typeof ResizeObserver<"u"&&(q=new ResizeObserver(()=>K()),q.observe(b)),K()},destroy(){w&&cancelAnimationFrame(w),w=0,q?.disconnect(),q=null,g?.removeEventListener("scroll",K),k=[],f?.remove(),g=null},window(){return{...p}}}}function ue(e,t,n){let r,o;if(typeof e=="string"){const i=u.PAPER_SIZES[e];if(!i)throw new Error(`未知纸张预设 "${e}"(可用:${Object.keys(u.PAPER_SIZES).join("/")})`);r=i.widthMm,o=i.heightMm}else typeof e=="number"?(r=e,o=t??297):(r=e.widthMm,o=e.heightMm);return n?{widthMm:o,heightMm:r}:{widthMm:r,heightMm:o}}class De{constructor(){this.pages=[],this.pending=null,this.templateParams=void 0}params(t){return this.templateParams=t,this}page(t="a4",n={},r){this.collect();const i=r!=null&&!("margins"in r)&&!("landscape"in r)&&("marginTopMm"in r||"marginBottomMm"in r||"marginLeftMm"in r||"marginRightMm"in r)?{margins:r}:typeof n=="number"?r??{}:n,{widthMm:a,heightMm:s}=ue(t,typeof n=="number"?n:void 0,i.landscape),l=i.margins??{};return this.pending=new ze(this,{widthMm:a,heightMm:s,marginTopMm:l.marginTopMm??10,marginBottomMm:l.marginBottomMm??10,marginLeftMm:l.marginLeftMm??10,marginRightMm:l.marginRightMm??10}),this.pending}collect(){this.pending&&(this.pages.push(this.pending.buildPage()),this.pending=null)}build(){if(this.collect(),this.pages.length===0)throw new Error("模板至少需要一页:先调用 .page() 添加内容");return this.templateParams?{params:this.templateParams,pages:this.pages}:{pages:this.pages}}}class ze{constructor(t,n){this.parent=t,this.page=n,this.components=[]}text(t,n={},r={}){return this.components.push({kind:"text",leftMm:n.leftMm??0,topMm:n.topMm??0,widthMm:n.widthMm??60,heightMm:n.heightMm??8,text:t,style:r}),this}list(t,n,r,o={}){return this.components.push({kind:"list",leftMm:n.leftMm??10,topMm:n.topMm??30,widthMm:n.widthMm??180,dataset:t,columns:r,...o}),this}rect(t,n={}){return this.components.push({kind:"rect",...t,style:n}),this}line(t,n,r,o={}){return this.components.push({kind:"line",leftMm:t,topMm:n,widthMm:r,heightMm:.5,style:o}),this}barcode(t,n){return this.components.push({kind:"barcode",leftMm:n.leftMm??0,topMm:n.topMm??0,widthMm:n.widthMm??40,heightMm:n.heightMm??12,fallbackText:t}),this}qrcode(t,n,r,o){return this.components.push({kind:"qrcode",leftMm:r,topMm:o,widthMm:n,heightMm:n,fallbackText:t}),this}buildPage(){return{...this.page,components:this.components}}done(){return this.parent}build(){return this.done().build()}}function Lt(){return new De}function O(e,t,n=!1){if(!Number.isFinite(e)||(n?e<0:e<=0))throw new Error(`${t} 必须是有限${n?"非负":"正"}数`)}function X(e,t,n){if(e!==void 0&&!["left","center","right","justify",...n?["auto"]:[]].includes(e))throw new Error(`${t} 必须是 left/center/right/justify${n?"/auto":""}`)}function Ot(e){const t=e.layout??"page";if(t!=="page"&&t!=="wide")throw new Error("layout 必须是 page 或 wide");if(t==="wide"&&(e.paper!==void 0||e.landscape!==void 0))throw new Error('宽表布局不能同时指定 paper 或 landscape;标准纸型请使用 layout: "page"');if(t!=="wide"&&e.columnWidthMm!==void 0)throw new Error('columnWidthMm 仅适用于 layout: "wide"');const n=e.columnWidthMm??30;return O(n,"columnWidthMm"),{layout:t,columnWidthMm:n}}function Ft(e){const t=e.paper===void 0?"a4":e.paper;if(typeof t!="string"&&(typeof t!="object"||t===null)||e.landscape!==void 0&&typeof e.landscape!="boolean")throw new Error("paper 必须是纸张预设名或 { widthMm, heightMm } 对象,landscape 必须是布尔值");if(typeof t=="string"&&!Object.prototype.hasOwnProperty.call(u.PAPER_SIZES,t))throw new Error(`未知纸张预设 "${t}"(可用:${Object.keys(u.PAPER_SIZES).join("/")})`);const n=ue(t,void 0,e.landscape),r=n.widthMm,o=n.heightMm;return O(r,"纸张 widthMm"),O(o,"纸张 heightMm"),{widthMm:r,heightMm:o}}function _t(e){if(e.margins!==void 0&&(!e.margins||typeof e.margins!="object"||Array.isArray(e.margins)))throw new Error("margins 必须是页边距对象");const t=e.margins??{},n={marginTopMm:t.marginTopMm===void 0?10:t.marginTopMm,marginBottomMm:t.marginBottomMm===void 0?10:t.marginBottomMm,marginLeftMm:t.marginLeftMm===void 0?10:t.marginLeftMm,marginRightMm:t.marginRightMm===void 0?10:t.marginRightMm};for(const[r,o]of Object.entries(n))O(o,r,!0);return n}function Ht(e,t){const n=e.dataset===void 0?"detail":e.dataset;if(typeof n!="string"||!n.trim())throw new Error("dataset 必须是非空字符串");if(e.title!==void 0&&typeof e.title!="string")throw new Error("title 必须是字符串");const r=e.titleHeightMm===void 0?10:e.titleHeightMm,o=e.titleGapMm===void 0?4:e.titleGapMm;O(r,"titleHeightMm"),O(o,"titleGapMm",!0);const i=e.title!==void 0&&e.title.length>0,a=i?r+o:0;if(a>=t)throw new Error("标题高度与间距占满页面,必须为表格保留可用高度");return{dataset:n,titleHeightMm:r,hasTitle:i,titleSpaceMm:a}}function Bt(e){if(e.listOptions!==void 0&&(!e.listOptions||typeof e.listOptions!="object"||Array.isArray(e.listOptions)))throw new Error("listOptions 必须是列表配置对象");const t=e.listOptions??{};X(t.align,"listOptions.align",!0),X(t.headerAlign,"listOptions.headerAlign",!1);for(const n of["fontSizePt","rowHeightMm","paddingMm"]){const r=t[n];r!==void 0&&O(r,`listOptions.${n}`,n==="paddingMm")}return t}function Dt(e){let t=0,n=0;for(const[r,o]of e.entries()){if(!o||typeof o.header!="string"||typeof o.field!="string"||!o.field.trim())throw new Error(`columns[${r}] 需要字符串 header 与非空 field`);X(o.align,`columns[${r}].align`,!0),X(o.headerAlign,`columns[${r}].headerAlign`,!1),o.flex!==void 0&&O(o.flex,`columns[${r}].flex`),o.widthMm!==void 0?(O(o.widthMm,`columns[${r}].widthMm`),t+=o.widthMm):n=Math.max(n,o.flex??1)}return{fixedWidthMm:t,maxFlex:n}}function zt(e,t,n,r){const{fixedWidthMm:o,maxFlex:i}=Dt(e.columns);if(t==="page"&&o>r)throw new Error(`固定列宽 ${o}mm 超出页面可用宽度 ${r}mm`);const a=r-o;if(t==="page"&&i>0&&a<=0)throw new Error("固定列占满页面可用宽度,自动列需要正的剩余宽度");const s=i>0?e.columns.reduce((d,c)=>d+(c.widthMm===void 0?(c.flex??1)/i:0),0):0;return{columns:e.columns.map(({widthMm:d,flex:c,...m},p)=>{const g=d??(t==="wide"?n*(c??1):a*((c??1)/i)/s);return O(g,`columns[${p}] 分配后的 widthMm`),{...m,widthMm:g}}),fixedWidthMm:o,maxFlex:i}}function jt(e){if(!e||typeof e!="object")throw new Error("标准明细模板需要 options 对象");if(!Array.isArray(e.columns)||e.columns.length===0)throw new Error("columns 至少需要一列");const{layout:t,columnWidthMm:n}=Ot(e),r=Ft(e);let o=r.widthMm;const i=r.heightMm,a=_t(e);let s=o-a.marginLeftMm-a.marginRightMm;const l=i-a.marginTopMm-a.marginBottomMm;if(t==="page"&&s<=0||l<=0)throw new Error("页边距占满纸张,必须保留正的可用宽度和高度");const{dataset:d,titleHeightMm:c,hasTitle:m,titleSpaceMm:p}=Ht(e,l),g=Bt(e),{columns:f,fixedWidthMm:h,maxFlex:y}=zt(e,t,n,s);t==="wide"&&(s=f.reduce((w,k)=>w+k.widthMm,0),O(s,"宽表总列宽"),o=s+a.marginLeftMm+a.marginRightMm,O(o,"宽表总宽度"));const M={widthMm:o,heightMm:i,...a,components:[],...t==="wide"?{layout:t}:{}};return m&&M.components.push({kind:"text",text:e.title,leftMm:a.marginLeftMm,topMm:a.marginTopMm,widthMm:s,heightMm:c,style:{fontSize:16,bold:!0,align:"center",verticalAlign:"middle",...e.titleStyle}}),M.components.push({align:"auto",headerAlign:"center",...g,kind:"list",...t==="wide"?{layout:t}:{},...m?{title:e.title}:{},dataset:d,columns:f,leftMm:a.marginLeftMm,topMm:a.marginTopMm+p,widthMm:t==="wide"||y>0?s:h}),e.params===void 0?{pages:[M]}:{params:e.params,pages:[M]}}const he="1.0";class W extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(n=>`${n.path}: ${n.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Wt=new Set(["__proto__","prototype","constructor"]),Vt=new Set(["schemaVersion","id","name","revision","description","template"]),Gt=new Set(["left","center","right","justify"]),oe=2e5,Jt=64,ge=1e7;function T(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ut(e,t,n){const r=Object.getPrototypeOf(e),o=Array.isArray(e);if(o?r!==Array.prototype:r!==Object.prototype&&r!==null)return n.push({path:t,message:"模板对象必须使用普通 JSON 对象原型"}),!1;if(o){const i=Object.keys(e);if(i.length!==e.length||i.some(a=>!/^(0|[1-9]\d*)$/.test(a)||Number(a)>=e.length))return n.push({path:t,message:"模板数组不能包含空位或额外属性"}),!1}return Object.getOwnPropertySymbols(e).length>0?(n.push({path:t,message:"模板不能包含 Symbol 键"}),!1):!0}function Kt(e,t,n,r){return Wt.has(e)?(r.push({path:n,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(r.push({path:n,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function qt(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function pe(e,t){const n=new Set;let r=0,o=0,i=!1;const a=(s,l,d)=>{if(!i){if(++r>oe){r===oe+1&&t.push({path:l,message:"模板超过 JSON 节点安全上限"});return}if(d>Jt){t.push({path:l,message:"模板嵌套层级过深"});return}if(typeof s=="string"){o+=s.length,o>ge&&(i=!0,t.push({path:l,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!qt(s)){if(!s||typeof s!="object"){t.push({path:l,message:"模板只允许 JSON 值,不允许函数、undefined 或非有限数字"});return}if(n.has(s)){t.push({path:l,message:"模板不能包含循环引用"});return}if(Ut(s,l,t)){n.add(s);for(const[c,m]of Object.entries(Object.getOwnPropertyDescriptors(s))){if(Array.isArray(s)&&c==="length")continue;const p=`${l}.${c}`;if(Kt(c,m,p,t)&&a(m.value,p,d+1),r>oe||i)break}n.delete(s)}}}};a(e,"$",0)}function x(e,t,n,r,o=!1){const i=e[t];i===void 0&&!o||(typeof i!="string"||o&&!i.trim())&&r.push({path:`${n}.${t}`,message:o?"应为非空字符串":"应为字符串"})}function C(e,t,n,r,o=0,i=!1){const a=e[t];a===void 0&&!i||(typeof a!="number"||!Number.isFinite(a)||a<o)&&r.push({path:`${n}.${t}`,message:`应为大于等于 ${o} 的有限数字`})}function U(e,t,n,r){e[t]!==void 0&&typeof e[t]!="boolean"&&r.push({path:`${n}.${t}`,message:"应为布尔值"})}function J(e,t,n,r=!1){e!==void 0&&!Gt.has(e)&&!(r&&e==="auto")&&n.push({path:t,message:`未知对齐方式${r?"(支持 auto)":""}`})}function B(e,t,n){if(e!==void 0){if(!T(e)){n.push({path:t,message:"样式应为对象"});return}J(e.align,`${t}.align`,n),e.verticalAlign!==void 0&&!["top","middle","bottom"].includes(e.verticalAlign)&&n.push({path:`${t}.verticalAlign`,message:"未知垂直对齐方式"});for(const r of["fontSize","fontSizePx","lineWidthPt","lineHeight"])C(e,r,t,n);for(const r of["letterSpacing","rotateDeg"])C(e,r,t,n,-1/0);C(e,"opacity",t,n),typeof e.opacity=="number"&&e.opacity>1&&n.push({path:`${t}.opacity`,message:"透明度不能大于 1"});for(const r of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])U(e,r,t,n);for(const r of["fontFamily","color","backgroundColor","lineColor","borderColor"])x(e,r,t,n)}}function Yt(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push({path:t,message:"参数定义应为数组"});return}const r=new Set;e.forEach((o,i)=>{const a=`${t}.${i}`;if(!T(o)){n.push({path:a,message:"参数定义应为对象"});return}x(o,"field",a,n,!0),typeof o.field=="string"&&(r.has(o.field)&&n.push({path:`${a}.field`,message:"参数名重复"}),r.add(o.field)),o.type!==void 0&&!["text","number","date","select"].includes(o.type)&&n.push({path:`${a}.type`,message:"未知参数类型"});for(const s of["label","defaultValue","placeholder"])x(o,s,a,n);U(o,"required",a,n),o.options!==void 0&&(Array.isArray(o.options)?o.options.forEach((s,l)=>{const d=`${a}.options.${l}`;if(!T(s))n.push({path:d,message:"选项应为对象"});else for(const c of["label","value"])typeof s[c]!="string"&&n.push({path:`${d}.${c}`,message:"选项标签与值应为字符串(允许空白选项)"})}):n.push({path:`${a}.options`,message:"选项应为数组"}))})}function Xt(e,t,n){if(!Array.isArray(e)||e.length===0){n.push({path:t,message:"列表至少需要一列"});return}e.forEach((r,o)=>{const i=`${t}.${o}`;if(!T(r)){n.push({path:i,message:"列应为对象"});return}if(Ee(r,i,n),typeof r.header!="string"&&n.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),x(r,"field",i,n,!0),C(r,"widthMm",i,n,Number.MIN_VALUE,!0),B(r.style,`${i}.style`,n),B(r.headerStyle,`${i}.headerStyle`,n),J(r.align,`${i}.align`,n,!0),J(r.headerAlign,`${i}.headerAlign`,n),r.format!==void 0)if(!T(r.format)||!["number","percent","date"].includes(r.format.kind))n.push({path:`${i}.format`,message:"未知列格式"});else{const a=r.format.digits;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>100)&&n.push({path:`${i}.format.digits`,message:"小数位应为 0–100 的整数"}),U(r.format,"thousands",`${i}.format`,n),x(r.format,"pattern",`${i}.format`,n)}r.rules!==void 0&&(Array.isArray(r.rules)?r.rules.forEach((a,s)=>{const l=`${i}.rules.${s}`;if(!T(a)||!T(a.when)){n.push({path:l,message:"条件格式缺少 when 对象"});return}x(a.when,"field",`${l}.when`,n,!0),[">",">=","<","<=","==","!="].includes(a.when.op)||n.push({path:`${l}.when.op`,message:"未知条件运算符"}),typeof a.when.value!="number"&&typeof a.when.value!="string"&&n.push({path:`${l}.when.value`,message:"条件值应为数字或字符串"}),B(a.style,`${l}.style`,n)}):n.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function Zt(e,t,n){if(e!==void 0){if(!T(e)){n.push({path:t,message:"分组应为对象"});return}x(e,"field",t,n,!0);for(const r of["headerTemplate","subtotalLabel"])x(e,r,t,n);for(const r of["headerStyle","subtotalStyle"])B(e[r],`${t}.${r}`,n);U(e,"keepWithNext",t,n),e.subtotal!==void 0&&(!Array.isArray(e.subtotal)||e.subtotal.some(r=>typeof r!="string"))&&n.push({path:`${t}.subtotal`,message:"小计字段应为字符串数组"})}}function Qt(e,t,n){if(!(e===void 0||typeof e=="boolean")){if(!T(e)){n.push({path:t,message:"合计应为布尔值或对象"});return}x(e,"label",t,n),B(e.style,`${t}.style`,n),e.fields!==void 0&&(!Array.isArray(e.fields)||e.fields.some(r=>typeof r!="string"))&&n.push({path:`${t}.fields`,message:"合计字段应为字符串数组"})}}function en(e,t,n){for(const r of["leftMm","topMm"])C(e,r,t,n,-1/0,!0);C(e,"widthMm",t,n,Number.MIN_VALUE,!0),x(e,"dataset",t,n,!0),x(e,"title",t,n),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&n.push({path:`${t}.layout`,message:"布局应为 page 或 wide"}),Xt(e.columns,`${t}.columns`,n);for(const r of["fontSizePt","rowHeightMm"])C(e,r,t,n,Number.MIN_VALUE);C(e,"paddingMm",t,n);for(const r of["headerBold","headerEveryPage","border"])U(e,r,t,n);x(e,"headerBackgroundColor",t,n),J(e.align,`${t}.align`,n,!0),J(e.headerAlign,`${t}.headerAlign`,n),B(e.headerStyle,`${t}.headerStyle`,n),Zt(e.groupBy,`${t}.groupBy`,n),Qt(e.grandTotal,`${t}.grandTotal`,n)}function je(e,t,n){B(e.style,`${t}.style`,n);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])x(e,o,t,n);if(e.lines!==void 0&&(!Array.isArray(e.lines)||e.lines.some(o=>typeof o!="string"))&&n.push({path:`${t}.lines`,message:"文本行应为字符串数组"}),Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((o,i)=>{if(!T(o))return;const a=`${t}.richParagraphs.${i}`;J(o.align,`${a}.align`,n);for(const s of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])C(o,s,a,n);Array.isArray(o.segments)&&o.segments.forEach((s,l)=>{const d=`${a}.segments.${l}`;if(!T(s)){n.push({path:d,message:"富文本片段应为对象"});return}s.kind!==void 0&&s.kind!=="text"&&s.kind!=="field"&&n.push({path:`${d}.kind`,message:"未知富文本片段类型"});for(const c of["text","field"])x(s,c,d,n);B(s.style,`${d}.style`,n)})}),!T(e.grid))return;const r=e.grid;C(r,"gapMm",`${t}.grid`,n),C(r,"paddingMm",`${t}.grid`,n);for(const o of["colWidthsMm","rowHeightsMm"]){const i=r[o];i!==void 0&&(!Array.isArray(i)||i.some(a=>typeof a!="number"||!Number.isFinite(a)||a<0))&&n.push({path:`${t}.grid.${o}`,message:"网格尺寸应为有限非负数字数组"})}Array.isArray(r.cells)&&r.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((a,s)=>{const l=`${t}.grid.cells.${i}.${s}`;if(a!==null){if(!T(a)){n.push({path:l,message:"网格单元格应为对象或 null"});return}for(const d of["text","rawText","numberFormat"])x(a,d,l,n);for(const d of["colSpan","rowSpan"]){const c=a[d];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<=0)&&n.push({path:`${l}.${d}`,message:"跨度应为正整数"})}a.value!==void 0&&a.value!==null&&!["string","number","boolean"].includes(typeof a.value)&&n.push({path:`${l}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),B(a.style,`${l}.style`,n),a.children!==void 0&&(Array.isArray(a.children)?a.children.forEach((d,c)=>{T(d)&&je(d,`${l}.children.${c}`,n)}):n.push({path:`${l}.children`,message:"嵌套组件应为数组"}))}})})}function ye(e){const t=[],n=[];return pe(e,t),t.length?{ok:!1,errors:t,warnings:n}:(T(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==$.RENDER_PLAN_SCHEMA_VERSION&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),Yt(e.params,"$.params",t),!Array.isArray(e.pages)||e.pages.length===0?t.push({path:"$.pages",message:"模板至少需要一页"}):e.pages.forEach((r,o)=>{const i=`$.pages.${o}`;if(!T(r)){t.push({path:i,message:"页应为对象"});return}C(r,"widthMm",i,t,Number.MIN_VALUE,!0),C(r,"heightMm",i,t,Number.MIN_VALUE,!0),r.layout!==void 0&&r.layout!=="page"&&r.layout!=="wide"&&t.push({path:`${i}.layout`,message:"布局应为 page 或 wide"}),typeof r.heightMm=="number"&&r.heightMm>=5e3&&t.push({path:`${i}.heightMm`,message:"页高应小于 5000mm"});for(const a of["marginTopMm","marginBottomMm","marginLeftMm","marginRightMm"])C(r,a,i,t);typeof r.widthMm=="number"&&Number(r.marginLeftMm??0)+Number(r.marginRightMm??0)>=r.widthMm&&t.push({path:i,message:"横向页边距占满页面"}),typeof r.heightMm=="number"&&Number(r.marginTopMm??0)+Number(r.marginBottomMm??0)>=r.heightMm&&t.push({path:i,message:"纵向页边距占满页面"}),Array.isArray(r.components)?r.components.forEach((a,s)=>{const l=`${i}.components.${s}`;T(a)&&a.kind==="list"?en(a,l,t):(Q(a,l,t,n),T(a)&&je(a,l,t))}):t.push({path:`${i}.components`,message:"组件应为数组"})})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:n})}function We(e){const t=[],n=[];if(pe(e,t),t.length)return{ok:!1,errors:t,warnings:n};if(!T(e))t.push({path:"$",message:"模板文档应为对象"});else{for(const o of Object.keys(e))Vt.has(o)||t.push({path:`$.${o}`,message:"模板文档存在未知字段;只保存模板与描述,不保存取数或业务数据"});e.schemaVersion!==he&&t.push({path:"$.schemaVersion",message:"不支持的模板文档版本"});for(const o of["id","name"])x(e,o,"$",t,!0);for(const o of["revision","description"])x(e,o,"$",t);const r=ye(e.template);t.push(...r.errors.map(o=>({...o,path:`$.template${o.path.slice(1)}`}))),n.push(...r.warnings.map(o=>({...o,path:`$.template${o.path.slice(1)}`})))}return{ok:t.length===0,errors:t,warnings:n}}function ee(e){const t=We(e);if(!t.ok)throw new W(t.errors)}function tn(e){const t=[];if(pe(e,t),t.length)throw new W(t);const n={...e,schemaVersion:e.schemaVersion??he};return ee(n),Z(n)}function nn(e){let t=e;if(typeof e=="string"){if(e.length>ge)throw new W([{path:"$",message:"模板 JSON 超过 1000 万字符的导出/导入上限"}]);try{t=JSON.parse(e)}catch{throw new W([{path:"$",message:"模板 JSON 语法无效"}])}}return ee(t),Z(t)}function rn(e){ee(e);const t=JSON.stringify(e,null,2);if(t.length>ge)throw new W([{path:"$",message:"模板 JSON 超过 1000 万字符的导出/导入上限"}]);return t}function Z(e){return JSON.parse(JSON.stringify(e))}function on(e=[]){const t=new Map,n={get:r=>{const o=t.get(r);return o?Z(o):void 0},list:()=>Array.from(t.values(),({template:r,...o})=>({...o})),register:(r,o={})=>{if(ee(r),t.has(r.id)&&!o.replace)throw new W([{path:"$.id",message:`模板 ID ${r.id} 已注册;更新需显式 replace:true`}]);t.set(r.id,Z(r))},remove:r=>t.delete(r)};for(const r of e)n.register(r);return n}function an(e){if(!("mapData"in e))return e;const{load:t,mapData:n,...r}=e;return{...r,load:async o=>{const i=await t(o);H(o.signal);try{return n(i,o)}catch(a){throw new R("validate",`报表 ${o.reportId} 数据映射失败`,a)}}}}class R extends Error{constructor(t,n,r){super(n),this.name="ReportSourceError",this.code=t,this.cause=r}}function te(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function H(e){if(e?.aborted)throw te(e)}function Ve(e,t){return t?new Promise((n,r)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),r(te(t))};t.addEventListener("abort",i,{once:!0}),t.aborted&&i(),Promise.resolve(e).then(a=>{o(),n(a)},a=>{o(),r(a)})}):Promise.resolve(e)}function sn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new R("validate",`报表 ${t} 的数据集应为对象`);for(const[n,r]of Object.entries(e))if(!Array.isArray(r)||r.some(o=>!o||typeof o!="object"||Array.isArray(o)))throw new R("validate",`报表 ${t} 的数据集 ${n} 应为对象数组`)}async function ln(e,t,n){const{reportId:r,signal:o}=t;try{const i=await Ve(e(t),o);H(o);const a=ye(i);if(!a.ok)throw new R("validate",`报表 ${r} 模板校验失败:${a.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ")}`);return n.push(...a.warnings.map(s=>`${r}: ${s.path}: ${s.message}`)),i}catch(i){throw o?.aborted?te(o):i instanceof R?i:i instanceof W?new R("validate",`报表 ${r} 模板校验失败:${i.message}`,i):new R("fetch",`报表 ${r} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function dn(e,t,n,r){let o;try{o=await Ve(e.load?e.load(t):e.datasets??{},r)}catch(i){throw r?.aborted?te(r):i instanceof R?i:new R("fetch",`报表 ${n} 取数失败:${i instanceof Error?i.message:String(i)}`,i)}return H(r),sn(o,n),o}function cn(e,t,n,r){try{return Ne(e,t,n.pagination)}catch(o){throw new R("validate",`报表 ${r} 排版失败:${o instanceof Error?o.message:String(o)}`,o)}}function mn(e,t,n,r){const o=new Map,i=a=>{let s=o.get(a);return s===void 0&&(s=JSON.stringify([n,r,a]),o.set(a,s)),s};for(const a of t.pages)e.push({...a,components:a.components.map(s=>s.table?{...s,table:{...s.table,id:i(s.table.id)}}:s)})}function fn(e,t={}){function n(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new R("config",`未注册报表 ${o}`);return i}return Object.assign(async({reportIds:o,params:i,signal:a,onWarning:s})=>{H(a);const l=[...o],d={...i};if(l.length===0)throw new R("config","缺少报表 ID");const c=l.map(n),m=[],p=[];for(const[y,M]of c.entries()){H(a);const w=l[y],k={reportId:w,params:{...d},signal:a},v=typeof M.template=="function"?await ln(M.template,k,p):M.template,D=await dn(M,k,w,a);H(a);const V=cn(v,D,M,w);mn(m,V.plan,y,w),p.push(...V.warnings.map(z=>`${w}: ${z}`))}H(a);const g={schemaVersion:$.RENDER_PLAN_SCHEMA_VERSION,pages:m},f=de(g);if(!f.ok)throw new R("validate",`渲染计划校验失败:${f.errors.slice(0,3).map(y=>`${y.path}: ${y.message}`).join("; ")}`);p.push(...f.warnings.map(y=>`${y.path}: ${y.message}`));const h=s??t.onWarning??(y=>console.warn("[mach-report]",y));for(const y of p)H(a),h(y);return H(a),g},{getParamDefs:o=>qe.getReportParamDefs(e,o)})}function un(e){return[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function Ge(e,t,n){const r=e.grid;if(!r)return null;const o=r.cells[t];if(!o)return null;const a=u.resolveGridLayout(r,e.widthMm,e.heightMm).cells.filter(l=>l.ri===t).findIndex(l=>l.ci===n),s=o[a];return s?{cell:s,sourceColumnIndex:a}:null}function hn(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function gn(e,t){return e.valueType?e.valueType:typeof t=="number"?"number":typeof t=="boolean"?"boolean":t===null&&e.numberFormat&&/[0#?]/.test(e.numberFormat)?"number":"text"}function pn(e,t){if(e.editable===!1)return"cell";if(e.formula!==void 0)return"formula";if(e.children?.length)return"complex";if(t.table&&t.table.role!=="body"&&e.editable!==!0)return"structure"}function yn(e,t){const n=e.table;if(n)return{id:n.id,rowIndex:n.rowIndex+t.rowIndex,role:n.role,columnKey:n.columnKeys[t.columnIndex]}}function ne(e,t){if(!un(t))return null;const n=e.pages[t.pageIndex]?.components[t.componentIndex];if(!n)return null;const r=Ge(n,t.rowIndex,t.columnIndex);if(!r)return null;const{cell:o}=r,i=hn(o),a=pn(o,n);return{address:{...t},cell:o,component:n,value:i,valueType:gn(o,i),table:yn(n,t),editable:a===void 0,readOnlyReason:a}}class _ extends Error{constructor(t){super(`Invalid report cell edit: ${t}`),this.code=t,this.name="ReportCellEditError"}}function bn(e,t){let n=e.trim();const r=t&&n.endsWith("%");if(r&&(n=n.slice(0,-1).trim()),/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(n)&&(n=n.replace(/,/g,"")),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(n))throw new _("number");return Number(n)/(r?100:1)}function Mn(e,t){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e!="string"&&typeof e!="number")throw new _("number");const n=typeof e=="number"?e:bn(e,Se.isExcelPercentageFormat(t.cell.numberFormat));if(!Number.isFinite(n)||Number.isInteger(n)&&!Number.isSafeInteger(n))throw new _("number");return n}function wn(e){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e=="boolean")return e;const t=String(e).trim().toLowerCase();if(["true","yes","是","1"].includes(t))return!0;if(["false","no","否","0"].includes(t))return!1;throw new _("boolean")}function be(e,t){return e.valueType==="number"?Mn(t,e):e.valueType==="boolean"?wn(t):t===null?null:String(t)}function vn(e,t){const n=t.cell.text,o=[["是","否"],["TRUE","FALSE"],["True","False"],["true","false"],["1","0"]].find(i=>i.includes(n??""));return o?o[e?0:1]:String(e)}function re(e,t){return t===null?"":typeof t=="boolean"?vn(t,e):typeof t=="number"?Se.formatExcelNumber(t,e.cell.numberFormat):String(t)}function Sn(e,t,n){const r=ne(e,t);if(!r)throw new _("missing");if(!r.editable)throw new _("readonly");const o=be(r,n);return{address:{...t},table:r.table,previousValue:r.value,previousText:r.cell.text??"",value:o,text:re(r,o)}}function $n(e,t){const n=e.table,r=t.table;return!n||!r||n.columnKey===void 0?!1:n.id===r.id&&n.rowIndex===r.rowIndex&&n.role===r.role&&n.columnKey===r.columnKey}function Je(e,t,n){const r=e.grid,{rowIndex:o,columnIndex:i}=t.address,a=Ge(e,o,i),s=[...r.cells],l=[...s[o]],d=re(t,n.value),c={...a.cell,value:n.value,text:d,rawText:d};return l[a.sourceColumnIndex]=c,s[o]=l,{...e,grid:{...r,cells:s}}}function Tn(e,t){const n=e.table?.columnKeys,r=t.table?.columnKey;return n&&r!==void 0?n.flatMap((o,i)=>o===r?[i]:[]):[]}function En(e,t,n,r,o,i){const a=t.table,s=o.table;if(!a||!s||a.id!==s.id||a.role!==s.role||!t.grid)return t;const l=s.rowIndex-a.rowIndex;if(l<0||l>=t.grid.cells.length)return t;let d=t;for(const c of Tn(t,o)){const m=ne(e,{pageIndex:n,componentIndex:r,rowIndex:l,columnIndex:c});m?.editable&&$n(o,m)&&(d=Je(d,m,i))}return d}function xn(e,t,n,r,o,i){const a=o.address;return o.table?.columnKey!==void 0?En(e,t,n,r,o,i):a.pageIndex===n&&a.componentIndex===r?Je(t,o,i):t}function Pn(e,t){const n=ne(e,t.address);if(!n)throw new _("missing");if(!n.editable)throw new _("readonly");if(!Object.is(n.value,t.previousValue)||(n.cell.text??"")!==t.previousText)throw new _("conflict");const r=be(n,t.value),o={...t,value:r,text:re(n,r)};if(Object.is(r,n.value)&&o.text===n.cell.text)return e;const i=e.pages.map((a,s)=>{const l=a.components.map((d,c)=>xn(e,d,s,c,n,o));return l.every((d,c)=>d===a.components[c])?a:{...a,components:l}});return{...e,pages:i}}exports.DEFAULT_BORDER_PT=$.DEFAULT_BORDER_PT;exports.DEFAULT_FONT_PT=$.DEFAULT_FONT_PT;exports.DEFAULT_STROKE_COLOR=$.DEFAULT_STROKE_COLOR;exports.DEFAULT_TEXT_COLOR=$.DEFAULT_TEXT_COLOR;exports.LINE_HEIGHT=$.LINE_HEIGHT;exports.RENDER_PLAN_SCHEMA_VERSION=$.RENDER_PLAN_SCHEMA_VERSION;exports.SCHEMA_VERSION_MACH=$.SCHEMA_VERSION_MACH;exports.isImageBackedComponent=$.isImageBackedComponent;exports.isRichText=$.isRichText;exports.CSS_DPI=u.CSS_DPI;exports.MM_PER_INCH=u.MM_PER_INCH;exports.PAPER_SIZES=u.PAPER_SIZES;exports.mergeComponentStyles=u.mergeComponentStyles;exports.mmToPx=u.mmToPx;exports.mmToPxFactor=u.mmToPxFactor;exports.ptToPx=u.ptToPx;exports.pxToMm=u.pxToMm;exports.resolveBoxBorders=u.resolveBoxBorders;exports.resolveFontSize=u.resolveFontSize;exports.resolveGridLayout=u.resolveGridLayout;exports.resolveLineHeight=u.resolveLineHeight;exports.resolveStroke=u.resolveStroke;exports.resolveTextColor=u.resolveTextColor;exports.round=u.round;exports.charWidthEm=N.charWidthEm;exports.createCanvasMeasurer=N.createCanvasMeasurer;exports.createHeuristicMeasurer=N.createHeuristicMeasurer;exports.heuristicMeasurer=N.heuristicMeasurer;exports.measureTextMm=N.measureTextMm;exports.wrapText=N.wrapText;exports.PageBuilder=ze;exports.REPORT_TEMPLATE_DOCUMENT_VERSION=he;exports.ReportCellEditError=_;exports.ReportSourceError=R;exports.ReportTemplateError=W;exports.TemplateBuilder=De;exports.applyReportCellEdit=Pn;exports.assertRenderPlan=ot;exports.classOf=P;exports.computePageWindow=Oe;exports.createCanvasPager=It;exports.createReportCellEdit=Sn;exports.createReportSource=fn;exports.createTableTemplate=jt;exports.createTemplate=Lt;exports.createTemplateRegistry=on;exports.defineReport=an;exports.defineReportTemplate=tn;exports.evalStyleRule=Te;exports.formatReportCellEdit=re;exports.formatValue=le;exports.getReportCellContext=ne;exports.measurePageSizePx=fe;exports.paginateTemplate=Ne;exports.parseDateLocal=$e;exports.parseReportCellInput=be;exports.parseReportTemplate=nn;exports.planFontSizePx=kt;exports.renderComponent=ce;exports.renderPage=Le;exports.renderPlan=xt;exports.renderPlanToCanvas=Be;exports.renderPlanToImages=Nt;exports.resolvePaper=ue;exports.serializeReportTemplate=rn;exports.toExcelNumberFormat=se;exports.toNumber=Y;exports.validateComponent=Q;exports.validatePage=xe;exports.validateRenderPlan=de;exports.validateReportTemplate=ye;exports.validateReportTemplateDocument=We;