1843 lines
415 KiB
JavaScript
1843 lines
415 KiB
JavaScript
/******************************************************************************
|
||
Copyright (c) Microsoft Corporation.
|
||
|
||
Permission to use, copy, modify, and/or distribute this software for any
|
||
purpose with or without fee is hereby granted.
|
||
|
||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||
PERFORMANCE OF THIS SOFTWARE.
|
||
***************************************************************************** */
|
||
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
||
|
||
|
||
function __awaiter(thisArg, _arguments, P, generator) {
|
||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||
return new (P || (P = Promise))(function (resolve, reject) {
|
||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||
});
|
||
}
|
||
|
||
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
||
var e = new Error(message);
|
||
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
||
};
|
||
|
||
function t(t,e,i,s){return new(i||(i=Promise))(function(n,r){function a(t){try{h(s.next(t));}catch(t){r(t);}}function o(t){try{h(s.throw(t));}catch(t){r(t);}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e);})).then(a,o);}h((s=s.apply(t,[])).next());})}"function"==typeof SuppressedError&&SuppressedError;class e{static formatDate(t,e){let i=t||"yyyy-MM-dd HH:mm:ss.SSS";const s={"y+":(e=e||new Date).getFullYear(),"M+":e.getMonth()+1,"d+":e.getDate(),"h+":e.getHours(),"H+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),"S+":e.getMilliseconds()};let n;for(const t in s)if(n=new RegExp(`(${t})`).exec(i)){const e=`${s[t]}`,r=`00${e}`,a=n[1].length>r.length?0:r.length-n[1].length;i=i.replace(n[1],1===n[1].length?e:r.substring(a));}return i}static randomUUID(t){if("object"==typeof crypto){if("function"==typeof crypto.randomUUID)return t?crypto.randomUUID():crypto.randomUUID().toUpperCase();if("function"==typeof crypto.getRandomValues&&"function"==typeof Uint8Array){const e="10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>{const e=Number(t);return (e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)});return t?e.toUpperCase():e}}let e=(new Date).getTime(),i="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;const s="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let s=16*Math.random();return e>0?(s=(e+s)%16|0,e=Math.floor(e/16)):(s=(i+s)%16|0,i=Math.floor(i/16)),("x"===t?s:3&s|8).toString(16)});return t?s.toUpperCase():s}static getRandomValues(t,e){const i=e&&e>0?e:256,s=[],n=t&&t>0?t:1;let r=(new Date).getTime(),a="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;for(let t=0;t<n;t++){let e=Math.random()*i;r>0?(e=(r+e)%i|0,r=Math.floor(r/i)):(e=(a+e)%i|0,a=Math.floor(a/i)),s[t]=e;}return s}static getRandomStr(t){const e=t&&t>0?t:8;if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof Uint8Array){const t=crypto.getRandomValues(new Uint8Array(e));return Array.from(t).map(t=>(15&t).toString(16)).join("")}return this.getRandomValues(e,16).map(t=>(15&t).toString(16)).join("")}static createRect(t,e,i,s){return {x:t||0,y:e||0,width:i,height:s}}static parseRect(t){if(!t)return;t=t.trim();const e=/^\[?\(?\s*([0-9.+-]+)\s*,\s*([0-9.+-]+)\s*,\s*([0-9.+-]+)\s*,\s*([0-9.+-]+)\s*\)?]?$/.exec(t);return e?{x:parseFloat(e[1]),y:parseFloat(e[2]),width:parseFloat(e[3]),height:parseFloat(e[4])}:void 0}static isInnerRect(t,e){return t.x>=e.x&&t.x+t.width<=e.x+e.width&&t.y>=e.y&&t.y+t.height<=e.y+e.height}static hasIntersection(t,e){return t.x<e.x+e.width&&e.x<t.x+t.width&&t.y<e.y+e.height&&e.y<t.y+t.height}static getUnionRect(t,e){const i=Math.min(t.x,e.x),s=Math.min(t.y,e.y);return {x:i,y:s,width:Math.max(t.x+t.width,e.x+e.width)-i,height:Math.max(t.y+t.height,e.y+e.height)-s}}static rotate90(t){const e=t.x+.5*t.width,i=t.y+.5*t.height,s=t.width,n=t.height;return t.width>0&&t.height>0&&(t.width=n,t.height=s,t.x=e-.5*n,t.y=i-.5*s),t}}var i,s,n,r,a,o,h,c,d,u;!function(t){t[t.NONE=0]="NONE",t[t.ERROR=1]="ERROR",t[t.WARN=2]="WARN",t[t.INFO=3]="INFO",t[t.LOG=4]="LOG";}(i||(i={}));class l{static innerLog(t,...e){this.output?this.output.log(t,...e):console.log(t,...e);}static innerWarn(t,...e){this.output?this.output.warn(t,...e):console.warn(t,...e);}static innerError(t,...e){this.output?this.output.error(t,...e):console.error(t,...e);}static setLevel(t){t!==this.logLevel&&(this.logRecords.push(this.logLevel),this.logLevel=t,this.logRecords.length>this.RecordMaxSize&&this.logRecords.shift(),this.info(`<<================ setLogLevel(${t}) ================>>`));}static setLogOutput(t){this.output=t;}static restorePrev(){const t=this.logLevel;if(this.logRecords.length>0){const e=this.logRecords.shift();return this.logLevel=void 0===e?i.WARN:e,t}return -1}static logWithLevelFunc(t,i,s,...n){const r=e.formatDate("HH:mm:ss.SSS");"string"!=typeof s?1===n.length&&"string"==typeof n[0]?(t.call(l,`${i}[${r}]: ${n[0]||""}`),t.call(l,s)):t.call(l,s,...n):t.call(l,`${i}[${r}]: ${s}`,...n);}static log(t,...e){this.logLevel>=i.LOG&&this.logWithLevelFunc(l.innerLog,"【LOG 】",t,...e);}static info(t,...e){this.logLevel>=i.INFO&&this.logWithLevelFunc(l.innerLog,"【INFO 】",t,...e);}static warn(t,...e){this.logLevel>=i.WARN&&this.logWithLevelFunc(l.innerWarn,"【WARN 】",t,...e);}static error(t,...e){this.logLevel>=i.ERROR&&this.logWithLevelFunc(l.innerError,"【ERROR】",t,...e);}}l.logRecords=[],l.logLevel=i.WARN,l.RecordMaxSize=10,function(t){t[t.Top=0]="Top",t[t.Bottom=1]="Bottom",t[t.Left=2]="Left",t[t.Right=3]="Right";}(s||(s={})),function(t){t[t.None=0]="None",t[t.UnderLine=1]="UnderLine",t[t.ThroughLine=2]="ThroughLine",t[t.OverLine=3]="OverLine";}(n||(n={})),function(t){t[t.REGULAR=0]="REGULAR",t[t.BOLD=1]="BOLD",t[t.ITALIC=2]="ITALIC",t[t.UNDERLINE=4]="UNDERLINE",t[t.STRIKEOUT=8]="STRIKEOUT";}(r||(r={})),function(t){t[t.Unset=255]="Unset",t[t.Start=0]="Start",t[t.Center=1]="Center",t[t.End=2]="End",t[t.Stretch=3]="Stretch";}(a||(a={})),function(t){t[t.Auto=0]="Auto",t[t.RotateCanvas=1]="RotateCanvas",t[t.RotateContent=2]="RotateContent";}(o||(o={})),function(t){t[t.None=0]="None",t[t.AntiColor=1]="AntiColor",t[t.AntiBackground=2]="AntiBackground",t[t.FillFull=4]="FillFull";}(h||(h={})),function(t){t[t.None=0]="None",t[t.Left=1]="Left",t[t.HInner=2]="HInner",t[t.Right=4]="Right",t[t.HOuter=8]="HOuter",t[t.Top=16]="Top",t[t.VInner=32]="VInner",t[t.Bottom=64]="Bottom",t[t.VOuter=128]="VOuter",t[t.Inner=34]="Inner",t[t.Outer=136]="Outer";}(c||(c={})),function(t){t[t.None=0]="None",t[t.Char=1]="Char",t[t.Word=2]="Word";}(d||(d={})),function(t){t[t.Auto=0]="Auto",t[t.MM=1]="MM",t[t.Pix=2]="Pix";}(u||(u={}));class g{static getLineMode(t){const e=/^(\d+)_(\d+)$/.exec(t);if(e){const t=parseInt(e[1])+parseFloat(`0.${e[2]}`);return t>1?t:g.LineSpaceMode_1_0}return (t&&/^\d*\.?\d*$/.test(t)?parseFloat(t):0)>0?g.LineSpaceMode_Custom:g.LineSpaceMode_1_0}static toString(t,e){switch(t){case g.LineSpaceMode_1_0:return g.LineSpace_1_0;case g.LineSpaceMode_1_2:return g.LineSpace_1_2;case g.LineSpaceMode_1_5:return g.LineSpace_1_5;case g.LineSpaceMode_2_0:return g.LineSpace_2_0;default:return "number"==typeof e?String(e):""}}static getModeValue(t,e){return t>1?(t-1)*e:0}static valueOf(t,e){if("string"==typeof t){const i=/^(\d+)_(\d+)$/.exec(t);if(i){const t=parseInt(i[1]),s=parseFloat(`0.${i[2]}`);return this.getModeValue(t+s,e)}{const e=parseFloat(t);return isNaN(e)?0:e}}return this.getModeValue(t,e)}}g.LineSpace_1_0="1_0",g.LineSpace_1_2="1_2",g.LineSpace_1_5="1_5",g.LineSpace_2_0="2_0",g.LineSpaceMode_1_0=1,g.LineSpaceMode_1_2=1.2,g.LineSpaceMode_1_5=1.5,g.LineSpaceMode_2_0=2,g.LineSpaceMode_Custom=0;class p{static isNull(t){return null==t}static isTransparent(t){return "transparent"===(t=(t||"").toLowerCase())||t.match(/^#[0-9a-f]{3}0$/i)||t.match(/^#[0-9a-f]{6}00$/i)}static getLineHeight(t){return 1.172*t}static isHorizontal(t){switch(t){case 0:case 2:case 180:return true;default:return false}}static isPortrait(t){switch(t){case 1:case 3:case 90:case 270:return true;default:return false}}static validateColorStr(t){return t?/^[0-9A-Fa-f]+$/.exec(t)?`#${t}`:/^#([0-9A-Fa-f]+)$/.exec(t)?t:/^0[xX]([0-9A-Fa-f]+)$/.exec(t)?`#${t.substring(2)}`:t:t}get supportLineDash(){return this.supports("setLineDash")}get Canvas(){return this._canvas||this.setCanvas(this.createCanvas()),this._canvas}setCanvas(t){if(!t)return;this._canvas=t,this.initOptions.position&&this._canvas.style&&(this._canvas.style.position=this.initOptions.position);const e=this.initOptions.willReadFrequently||false;this.ctx=this._canvas.getContext("2d",{willReadFrequently:e}),this.setTextBaseline(p.TEXT_BASELINE_DEFAULT),this.setTextAlign("left");}get Context(){return this.ctx}get Width(){return this.width}get Height(){return this.height}get Orientation(){return this.orientation}get BorderAlign(){return this._borderAlign}set BorderAlign(t){this._borderAlign=t;}get ModulePixels(){return this._modulePixels}set ModulePixels(t){t>0&&(this._modulePixels=t);}get DashLen(){return this._dashLen||[]}set DashLen(t){this._dashLen=t;}get PixPerUnit(){return this._pixPerUnit}get HorizontalAlign(){return this._horizontalAlign}set HorizontalAlign(t){this._horizontalAlign="number"==typeof t?t:a.Unset;}get VerticalAlign(){return this._verticalAlign}set VerticalAlign(t){this._verticalAlign="number"==typeof t?t:a.Unset;}get ItemOrientation(){return this._rotation||0}set ItemOrientation(t){this._rotation=t;}get LineWidth(){return this._lineWidth>0?this._lineWidth:p.LINE_WIDTH}set LineWidth(t){t>=0&&(this._lineWidth=t);}get Foreground(){return this._foreground||p.COLOR_FG_DEFAULT}set Foreground(t){this._foreground=t;}get Background(){return this._background||p.COLOR_BG_DEFAULT}set Background(t){this._background=t;}get AutoReturn(){return this._autoReturn}set AutoReturn(t){this._autoReturn=t;}get FontName(){return this.fontName}set FontName(t){t&&"HARMONYOS SANS"===t.toUpperCase()?this.fontName="HarmonyOS Sans SC":this.fontName=t;}get FontHeight(){return this.fontHeight}set FontHeight(t){t>=0&&(this.fontHeight=t);}get FontStyle(){return this.fontStyle}set FontStyle(t){t>=0&&(this.fontStyle=t);}get LineSpace(){return this._lineSpace}set LineSpace(t){this._lineSpace=t;}get CharSpace(){return this._charSpace}set CharSpace(t){this._charSpace=t;}constructor(t){this.fontName=p.FONT_NAME,this.fontStyle=0,this.fontHeight=0,this.width=0,this.height=0,this.orientation=0,this.jobName="",this._modulePixels=2,this._lineWidth=0,this._dashLen=[],this._foreground=p.COLOR_FG_DEFAULT,this._rotation=0,this._horizontalAlign=a.Unset,this._verticalAlign=a.Unset,this._autoReturn=d.Char,this._charSpace=0,this._lineSpace=0,this._borderAlign=c.Inner,this._pixPerUnit=1;const e=t||{};this.initOptions=e,"boolean"==typeof e.adjustFontSize&&(e.adjustFontSize=e.adjustFontSize?.95:0),this._canvasCreator=e.creator,this._canvasClearAction=e.onCanvasClear,e.background&&(this._background=e.background),e.foreground&&(this._foreground=e.foreground),e.canvas&&this.setCanvas(e.canvas);}createCanvas(){return this._canvasCreator?this._canvasCreator():document&&void 0!==document.createElement?document.createElement("canvas"):void 0}getReturnMode(t){return void 0!==t?t:this.AutoReturn}getRotateMode(t){return t&&t>0?t:o.RotateContent}getLineSpace(t,e){return "string"==typeof t&&t?g.valueOf(t,e||this.fontHeight):"number"==typeof t&&t>=0?t:this.LineSpace}setTextBaseline(t){const e=this.ctx;void 0!==this.ctx.textBaseline&&(this.ctx.textBaseline=t),"function"==typeof e.setTextBaseline&&e.setTextBaseline(p.TEXT_BASELINE_DEFAULT);}setTextAlign(t){const e=this.ctx;void 0!==this.ctx.textAlign&&(this.ctx.textAlign=t),"function"==typeof e.setTextAlign&&e.setTextAlign(t);}appendTo(t){return t instanceof Element&&(t.innerHTML="",t.appendChild(this.Canvas),true)}supports(t){switch(t){case "getImageData":return void 0!==this.ctx.getImageData;case "setLineDash":return void 0!==this.ctx.setLineDash;case "toDataURL":return void 0!==this.Canvas.toDataURL;case "toDataURLWithQuality":try{return this.Canvas.toDataURL("image/jpeg",0),!0}catch(t){return false}case "measureText":return void 0!==this.ctx.measureText;default:return false}}clearAll(){this.ctx.clearRect(0,0,this.Canvas.width,this.Canvas.height),this._background&&(this.ctx.fillStyle=p.validateColorStr(this.Background),this.ctx.fillRect(0,0,this.Canvas.width,this.Canvas.height)),"function"==typeof this._canvasClearAction&&this._canvasClearAction(this.Canvas,this.ctx);}getLineWidth(t){return t&&t>0?t:this.LineWidth}getDashLen(t){return t||this.DashLen}setFont(t,e,i){const s=t||this.fontHeight,n=this.initOptions.adjustFontSize||0;i&&"HARMONYOS SANS"===i.toUpperCase()&&(i="HarmonyOS Sans SC");const a=Math.floor(n>.1&&n<1?s*n:s),o=e||this.fontStyle,h=i||this.fontName||p.FONT_NAME,c=0!==(o&r.ITALIC)?"italic":"normal",d=0!==(o&r.BOLD)?"bold":"normal";this.ctx.font=`${c} normal ${d} ${a}px "${h}", system-ui`;}getPaddings(t){let e=[];Array.isArray(t.padding)&&t.padding.length>0?e=t.padding:"number"==typeof t.padding&&(e=[t.padding]);const i=e[0]||0,s=e.length>1?e[1]:i;return [i,s,e.length>2?e[2]:i,e.length>3?e[3]:s]}processPaddings(t,e){return t.x=t.x||0,t.y=t.y||0,t.x+=e[3],"number"==typeof t.width&&(t.width-=e[3]+e[1]),t.y+=e[0],"number"==typeof t.height&&(t.height-=e[0]+e[2]),t}processPadding(t){const e=this.getPaddings(t);return this.processPaddings(t,e)}getAntiColor(t,e){return "number"==typeof t?t:t&&"boolean"==typeof t?e||h.AntiColor|h.AntiBackground:h.None}getHorizontalAlignment(t,e){return "number"!=typeof t&&(t=this._horizontalAlign),t>=a.Start&&t<=a.Stretch?t:"number"==typeof e?e:a.Unset}getVerticalAlignment(t,e){return "number"!=typeof t&&(t=this._verticalAlign),t>=a.Start&&t<=a.Stretch?t:"number"==typeof e?e:a.Unset}getItemRotation(t){const e="object"==typeof t?t:{rotation:t},i="number"==typeof e.rotation?e.rotation:e.orientation;let s="number"==typeof i?i:this.ItemOrientation;return s<0?s+=360:s>=360&&(s%=360),s>0&&s<4&&(s*=90),s}startJob(t){if("number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=0),"number"!=typeof t.printerWidth&&(t.printerWidth=0),t.width<=0&&t.printerWidth>0&&(t.width=t.printerWidth),!(t.width<=0&&t.height<=0))return t.canvas&&this.setCanvas(t.canvas),this.width=Math.round(t.width||t.height||0),this.height=Math.round(t.height||t.width),this.orientation=t.orientation||0,t.jobName&&(this.jobName=t.jobName),this.Canvas.width=this.width,this.Canvas.height=this.height,"boolean"!=typeof t.isPreview||t.isPreview?(t.backgroundColor&&(this._background=t.backgroundColor),t.color&&(this._foreground=t.color)):(this._background=p.COLOR_BG_DEFAULT,this._foreground=p.COLOR_FG_DEFAULT),this._horizontalAlign=a.Unset,this._verticalAlign=a.Unset,this.clearAll(),t.isPreview&&t.backgroundImage&&this.drawImage({image:t.backgroundImage,width:t.width,height:t.height,alignment:a.Stretch}),this.Canvas;l.warn("---- 未指定标签大小!");}commitJob(){return this.Canvas}setRotation(t,e,i){if((t=(t||0)%360)>0){const s=e||{x:0,y:0},n=i||{width:0,height:0};s.x=Math.round(s.x+.5*n.width)+.5,s.y=Math.round(s.y+.5*n.height)+.5,this.ctx.translate(s.x,s.y),this.ctx.rotate(t*Math.PI/180),this.ctx.translate(-s.x,-s.y);}}drawLine(t){let e=t.x1||0,i=t.y1||0,s="number"==typeof t.x2?t.x2:e,n="number"==typeof t.y2?t.y2:i;const r="number"==typeof t.x?t.x:e,a="number"==typeof t.y?t.y:i;if(e===s&&i===n){const o=t.width||0,h=t.height||0;if(o>0||h>0){const c=Math.min(o,h);c>0&&(t.lineWidth=c),o>h?(t.x1=e=r,t.x2=s=r+o,t.y1=i=a+.5*h,t.y2=n=i):(t.x1=e=r+.5*o,t.x2=s=e,t.y1=i=a,t.y2=n=a+h);}else t.x1=e=r,t.x2=s=r+this.width,t.y1=i=a,t.y2=n=a;}else i===n?"number"!=typeof t.y1&&"number"!=typeof t.y2&&"number"==typeof t.y&&(t.y1=i=t.y,t.y2=n=t.y):e===s&&"number"!=typeof t.x1&&"number"!=typeof t.x2&&"number"==typeof t.x&&(t.x1=e=t.x,t.x2=s=t.x);this.ctx.save();const o=this.getItemRotation(t);this.setRotation(o,{x:.5*(e+s),y:.5*(i+n)});const h=this._drawLine(t);return this.ctx.restore(),h}_drawLine(t){const e=Math.floor(t.x1||0)+.5,i=Math.floor(t.y1||0)+.5,s="number"==typeof t.x2?Math.floor(t.x2)+.5:e,n="number"==typeof t.y2?Math.floor(t.y2)+.5:i;this.ctx.strokeStyle=p.validateColorStr(t.color||this.Foreground),this.ctx.lineWidth=Math.ceil(this.getLineWidth(t.lineWidth)),this.ctx.beginPath();let r=t.dashLens;return (!r||r.length<=0)&&(r=(t.dashLen||"").split(",").map(t=>+t)),this.supportLineDash&&this.ctx.setLineDash(r||[]),this.ctx.moveTo(e,i),this.ctx.lineTo(s,n),this.ctx.stroke(),this.supportLineDash&&this.ctx.setLineDash([]),true}drawRect(t){const e=t.x||0,i=t.y||0,s=t.width||0,n=t.height||0;if(t.cornerWidth&&t.cornerWidth>0||t.cornerHeight&&t.cornerHeight>0||t.radius&&t.radius>0)return this.drawRoundRect(t);if(s>0&&n>0){this.ctx.save();const r=this.getItemRotation(t);return this.setRotation(r,{x:e,y:i},{width:s,height:n}),this._drawRect(t),this.ctx.restore(),true}return false}_drawRect(t){const i=p.validateColorStr(t.color||this.Foreground);let s=t.x||0,n=t.y||0,r=t.width||t.height||0,a=t.height||t.width||0;if(r<=0)return false;if(i&&p.isTransparent(i))return true;if(this.ctx.lineJoin=t.lineJoin||"miter",t.fill){const t=this.adjustRect(e.createRect(s,n,r,a),this.BorderAlign);this.ctx.fillStyle=i,this.ctx.fillRect(t.x,t.y,t.width,t.height);}else {let o=this.getLineWidth(t.lineWidth),h=t.dashLens;(!h||h.length<=0)&&(h=(t.dashLen||"").split(",").map(t=>+t)),o=Math.ceil(o),s+=.5*o,n+=.5*o,r-=o,a-=o;const c=this.adjustRect(e.createRect(s,n,r,a),this.BorderAlign);this.ctx.lineWidth=o||this.LineWidth,this.ctx.strokeStyle=i,this.supportLineDash&&h.length>0&&this.ctx.setLineDash(h),this.ctx.strokeRect(c.x,c.y,c.width,c.height),this.supportLineDash&&this.ctx.setLineDash([]);}return true}adjustRect(t,e){let i=t.x,s=t.y,n=t.x+t.width,r=t.y+t.height;const a=240&e;switch(15&e){case c.Left:i=Math.floor(i),n=Math.floor(n);break;case c.HInner:i=Math.ceil(i),n=Math.floor(n);break;case c.Right:i=Math.ceil(i),n=Math.ceil(n);break;case c.HOuter:i=Math.floor(i),n=Math.ceil(n);break;default:i=Math.round(i),n=Math.round(n);}switch(a){case c.Top:s=Math.floor(s),r=Math.floor(r);break;case c.VInner:s=Math.ceil(s),r=Math.floor(r);break;case c.Bottom:s=Math.ceil(s),r=Math.ceil(r);break;case c.VOuter:s=Math.floor(s),r=Math.ceil(r);break;default:s=Math.round(s),r=Math.round(r);}const o=n-i,h=r-s;return {x:i,y:s,width:o>0?o:1,height:h>0?h:1}}drawRoundRect(t){let e=t.x||0,i=t.y||0,s=t.width||0,n=t.height||0;const r=t.cornerWidth||t.cornerHeight||t.radius||0;if(s<=0&&n<=0)return false;if(r<=0)return this.drawRect(t);const a=.5*Math.min(s,n),o=p.validateColorStr(t.color||this.Foreground);let h=this.getLineWidth(t.lineWidth);t.fill||(h>a&&(h=a),e+=.5*h,i+=.5*h,s-=h,n-=h),this.ctx.save();const c=this.getItemRotation(t);return this.setRotation(c,{x:e,y:i},{width:s,height:n}),this.ctx.translate(e,i),this.ctx.fillStyle=o,this.ctx.strokeStyle=o,this.drawRoundRectPath(s,n,r),t.fill?this.ctx.fill():(this.ctx.lineWidth=h,this.ctx.stroke()),this.ctx.restore(),true}drawRoundRectPath(t,e,i){i=Math.min(i,.5*t,.5*e),this.ctx.beginPath(),this.ctx.arc(t-i,e-i,i,0,Math.PI/2),this.ctx.lineTo(i,e),this.ctx.arc(i,e-i,i,Math.PI/2,Math.PI),this.ctx.lineTo(0,i),this.ctx.arc(i,i,i,Math.PI,3*Math.PI/2),this.ctx.lineTo(t-i,0),this.ctx.arc(t-i,i,i,3*Math.PI/2,2*Math.PI),this.ctx.lineTo(t,e-i),this.ctx.closePath();}drawEllipse(t){let e=t.x||0,i=t.y||0,s=t.width||t.height||0,n=t.height||t.width||0;if(s<=0&&n<=0)return false;if(s===n)return this.drawCircle(t);const r=p.validateColorStr(t.color||this.Foreground),a=this.getLineWidth(t.lineWidth);e+=.5*a,i+=.5*a,s-=a,n-=a;const o=.5*s,h=.5*n;e+=o,i+=h;const c=this.getItemRotation(t);if(this.ctx.save(),this.setRotation(c,{x:e,y:i}),this.ctx.lineWidth=a,this.ctx.fillStyle=r,this.ctx.strokeStyle=r,this.ctx.ellipse)this.ctx.beginPath(),this.ctx.ellipse(e,i,o,h,0,0,2*Math.PI);else {const t=.5*o,s=.6*h;this.ctx.translate(e,i),this.ctx.beginPath(),this.ctx.moveTo(0,h),this.ctx.bezierCurveTo(t,h,o,s,o,0),this.ctx.bezierCurveTo(o,-s,t,-h,0,-h),this.ctx.bezierCurveTo(-t,-h,-o,-s,-o,0),this.ctx.bezierCurveTo(-o,s,-t,h,0,h),this.ctx.closePath();}return t.fill?this.ctx.fill():this.ctx.stroke(),this.ctx.restore(),true}drawCircle(t){let e=t.x||0,i=t.y||0,s=t.radius||0;if(s<=0){const n=t.width||0,r=t.height||0;if(n>0&&r>0)s=.5*Math.min(n,r),e+=.5*n,i+=.5*r;else if(n>0)s=.5*n,e+=s;else {if(!(r>0))return false;s=.5*r,i+=s;}}const n=p.validateColorStr(t.color||this.Foreground),r=this.getLineWidth(t.lineWidth);return s-=.5*r,this.ctx.lineWidth=r,this.ctx.fillStyle=n,this.ctx.strokeStyle=n,this.ctx.beginPath(),this.ctx.arc(e,i,s,0,2*Math.PI),this.ctx.closePath(),t.fill?this.ctx.fill():this.ctx.stroke(),true}drawText(t){"number"!=typeof t.x&&(t.x=0),"number"!=typeof t.y&&(t.y=0),"number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=0);const i=this.getItemRotation(t),s=this.getRotateMode(t.rotateMode),n=this.getAntiColor(t.antiColor,h.AntiColor&h.FillFull);if(i>0||n>0){const r=this.getPaddings(t),a=r[1]+r[3],c=r[0]+r[2];if((t.width<=0||t.height<=0)&&void 0!==this.ctx.measureText){const e=this.measureTextExt(t);t.width<=0&&(t.width=e.width+a),t.height<=0&&(t.height=e.height+c);}if(t.width<=0||t.height<=0)return false;(n&h.FillFull)>0&&this.drawRect(Object.assign(Object.assign({},t),{rotation:s===o.RotateContent?0:i,color:t.color||this.Foreground,fill:true})),p.isPortrait(i)&&s===o.RotateContent&&e.rotate90(t);const d=t.x+.5*t.width,u=t.y+.5*t.height;this.ctx.save(),this.setRotation(i,{x:d,y:u});const l=this._drawText(t);return this.ctx.restore(),l}return this._drawText(t)}_drawText(t){if(("number"!=typeof t.x||isNaN(t.x))&&(t.x=0),("number"!=typeof t.y||isNaN(t.y))&&(t.y=0),null==t.text||null==t.text){if(void 0===t.content)return false;t.text=t.content;}const e=this.getAntiColor(t.antiColor,h.AntiColor&h.FillFull),i=t.color||this.Foreground,s=t.bgColor||this.Background,n=t.minFontHeight||6,r=this.getReturnMode(t.autoReturn),o="boolean"!=typeof t.autoShrink||t.autoShrink,c=this.getPaddings(t),u=c[1]+c[3],l=c[0]+c[2];let g=i;e>0&&(g=p.isTransparent(s)?p.COLOR_BG_DEFAULT:s);let f=t.y+c[0];const m=t.width||0;let C=t.height||0;(!t.texts||t.texts.length<=0)&&(t.texts=Array.isArray(t.text)?t.text:[String(t.text)]);const P=t.texts||[],R=t.fontHeight||C||this.fontHeight;let I=this.getHorizontalAlignment(t.horizontalAlignment),b=this.getVerticalAlignment(t.verticalAlignment);if(R<=0)return false;(I>a.Stretch||I<a.Start)&&(I=a.Start),(b>a.Stretch||b<a.Start)&&(b=a.Start),"number"!=typeof t.charSpace&&(t.charSpace=this.CharSpace);const y=t.charSpace>0?t.charSpace:0;this.ctx.fillStyle=p.validateColorStr(g),this.setFont(R,t.fontStyle,t.fontName),this.ctx.textBaseline=p.TEXT_BASELINE_DEFAULT;let v=[];for(let t of P)"string"!=typeof t?v.push(String(t)):(t=t.replace("\t",""),v.push(...t.split("\n")));r!==d.None&&m>0&&(v=this.splitText(Object.assign(Object.assign({},t),{text:v,width:m-u,fontHeight:R,autoReturn:r})));let A=this.getLineSpace(t.lineSpace||"",R);if(v.length>0){const r=p.getLineHeight(R)*v.length,h=r+(v.length-1)*A;C<=0&&(C=h+l),h<=C||!o||R<n?(b===a.Stretch?A=(C-r-c[0]-c[2])/(v.length-1):b===a.End?f+=C-h-l:b===a.Center&&(f+=.5*(C-l-h)),this.drawTextList1({texts:v,x:t.x+c[3],y:f,width:m-u,fontHeight:R,lineSpace:A,charSpace:y,horizontalAlignment:I,fontStyle:t.fontStyle||this.fontStyle,color:e?s:i})):this._drawText(Object.assign(t,{text:P,width:m,fontHeight:.95*R}));}return true}drawTextList1(t){const e=t.lineSpace>0?t.lineSpace:0,i=p.getLineHeight(t.fontHeight);let s=0;for(const n of t.texts)this._drawSingleLineText(n,t.x,t.y+s,t.width,t.fontHeight,t.horizontalAlignment,t.charSpace,t.fontStyle,t.color),s+=i+e;}_drawSingleLineText(t,e,i,s,n,o,h,c,d){t=String(t);const u=.2*n,l=n-u,g=this.measureText({text:t,fontHeight:n},false),f="number"==typeof g.actualBoundingBoxAscent?g.actualBoundingBoxAscent:l,m="number"==typeof g.actualBoundingBoxDescent?g.actualBoundingBoxDescent:u,C=t.length>1&&h>0?(t.length-1)*h:0,P=o||a.Start;let R=(null==g?void 0:g.width)||0,I=.05*n;I<1&&(I=1);const b=i+p.getLineHeight(l),y=f+m;if(g&&P===a.Stretch&&s>g.width)h=(s-g.width)/(t.length-1),1===t.length?this.ctx.fillText(t,e+.5*(s-g.width),b):this.fillCharSpaceText(t,e,b,h),R=s;else {const i=g?g.width+C:0;(s=g?s:0)>i&&(P===a.End?e=e+s-i:P===a.Center&&(e+=.5*(s-i))),s>0&&s<i?(this.fillCharSpaceText(t,e,b,h,s),R=s):(this.fillCharSpaceText(t,e,b,h),R=i);}0!==(c&r.STRIKEOUT)&&this._drawRect({x:e,y:b-f+.5*(y-I),width:R,height:I,color:d,fill:true}),0!==(c&r.UNDERLINE)&&this._drawRect({x:e,y:i+n-.5*I,width:R,height:I,color:d,fill:true});}fillCharSpaceText(t,e,i,s,n){if(t.length<=0)return;const r=void 0!==this.ctx.measureText?this.ctx.measureText(t):void 0,a=t.length>1?(t.length-1)*s:0;if(r&&s>0){const o=r.width+a,h=n&&n<o?n/o:1;let c=e;for(const e of t){const t=this.ctx.measureText(e).width;this.ctx.fillText(e,c,i,t*h),c+=(t+s)*h;}}else n&&n>0?this.ctx.fillText(t,e,i,n):this.ctx.fillText(t,e,i);}drawArcText(t){if(null!=t.text&&null!=t.text||void 0!==t.content&&(t.text=t.content),null==t.text||null==t.text)return false;const e=t.fontHeight||0;if(e<=0)return false;const i={x:t.x||0,y:t.y||0,width:t.width||0,height:t.height||0},s={x:i.x,y:i.y},n=t.lineWidth||0,r=this.getPaddings(t)[0],a=this.getAntiColor(t.antiColor,h.AntiColor&h.AntiBackground),o=h.AntiBackground|h.FillFull,c=t.color||this.Foreground;let d=c;0!=(a&o)&&(d=t.bgColor||this.Background,d&&!p.isTransparent(d)||(d=p.COLOR_BG_DEFAULT));let u=t.radius||0;if(u<=0){if(!(i.width>0||i.height>0))return false;i.width>0&&i.height>0?(u=.5*Math.min(i.width,i.height),s.x+=.5*i.width,s.y+=.5*i.height):i.width>0?(i.height=i.width,u=.5*i.width,s.x+=u):(i.width=i.height,u=.5*i.height,s.y+=u);}else i.x-=u,i.y-=u,i.width=i.height=2*u;0!=(a&h.FillFull)?this.drawRect(Object.assign(Object.assign({},i),{rotation:t.rotation,color:c,fill:true})):0!=(a&h.AntiBackground)&&this.drawCircle({x:s.x,y:s.y,lineWidth:n,radius:u,color:c,fill:true}),n>0&&(this.drawCircle({x:s.x,y:s.y,lineWidth:n,radius:u,color:d}),u-=n);const l=String(t.text);u-=e,r>0&&r<u&&(u-=r);const g=void 0!==this.ctx.measureText,f=2*Math.PI*u,m=(g?this.measureText({text:l,fontHeight:e}).width:0)/f*Math.PI*2;this.setFont(.95*e,t.fontStyle,t.fontName),this.ctx.fillStyle=p.validateColorStr(d),this.ctx.save();const C=this.getItemRotation(t);this.setRotation(C,s),this.ctx.translate(s.x,s.y),this.ctx.rotate(.5*-Math.PI);const P=this.ctx.textBaseline;return this.ctx.textBaseline="bottom",l.split("").forEach((t,i)=>{const s=g?this.ctx.measureText(t).width:e,n=s/f*Math.PI*2;0===i?this.ctx.rotate(.5*-m+.5*n):this.ctx.rotate(n),this.ctx.save(),this.ctx.rotate(Math.PI/2),this.ctx.translate(.5*-s,-u),this.ctx.fillText(t,0,0),this.ctx.restore();}),this.ctx.textBaseline=P,this.ctx.restore(),true}getTextWidths(t){const e=[];if(!t||void 0===this.ctx.measureText)return e;for(const i of t)e.push(this.ctx.measureText(i).width);return e}draw1DBarcode(t){"number"!=typeof t.x&&(t.x=0),"number"!=typeof t.y&&(t.y=0),"number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=0);const i=t.datas;t.padding&&this.processPadding(t);const s=this.getItemRotation(t),n=this.getRotateMode(t.rotateMode);s>0&&p.isPortrait(s)&&n===o.RotateContent&&t.width>0&&t.height>0&&e.rotate90(t),"number"!=typeof t.textHeight&&"number"==typeof t.fontHeight&&(t.textHeight=t.fontHeight);let r="number"==typeof t.textHeight&&t.textHeight>0?t.textHeight:0,h=this.getHorizontalAlignment(t.horizontalAlignment,a.Center);const u="number"==typeof t.autoScaleLevel?t.autoScaleLevel:p.AUTO_SCALE_LEVEL;"number"!=typeof t.textFlag&&"number"==typeof t.flag&&(t.textFlag=t.flag);const l="number"!=typeof t.textFlag||t.topText?2:t.textFlag;r=l>0?r:0;let g=t.topText?r:0;const f=t.datas.map(t=>t.data||"").join(""),m=f.length*this.PixPerUnit;t.width=t.width<m?m:t.width,(h>a.Stretch||h<a.Start)&&(h=a.Center);let C=t.width,P=0,R=C/f.length;if(u>0&&R/this.PixPerUnit<u&&h<=a.End)switch(R=1*this.PixPerUnit,C=f.length*R,h){case a.Start:break;case a.End:P=t.width-C;break;default:P=.5*(t.width-C);}const I=r>0?p.BarTextMargin*R:0;let b=p.MinBarHeight;r>0&&t.topText?b=2*(r+I)+p.MinBarHeight:r&&(b=r+I+p.MinBarHeight),t.height<=0?(r<=0&&(r=25),t.height=3*r):t.height<b&&(t.height=b),this.ctx.save(),this.setRotation(s,{x:t.x,y:t.y},{width:t.width,height:t.height});const y=r+I,v=.5*r+I+1,A="number"==typeof t.textAlign?t.textAlign:t.textAlignment,E=R;let D=t.x+P,w=t.y+g+I,_=w,O=t.y;if(t.topText&&i.length>=7){const e=i.slice(1,6).map(t=>t.data).join("").length*E;g+=I,this._drawText({text:t.topText,x:t.x+i[0].data.length*E,y:t.y,width:e,height:r,fontHeight:r,fontStyle:t.fontStyle,fontName:t.fontName,color:t.color,autoReturn:d.None,horizontalAlignment:"number"==typeof A?A:a.Center,charSpace:t.charSpace});}for(const e of i){if(t.height>y){const i=e.text?y:y-v,s=t.height-i-g;1===l?(_=t.y,w=_+i):(w=t.y+g,_=w+s,O=_+I),this.BorderAlign=c.None;for(let n=0;n<e.data.length;n++,D+=E)"1"===e.data[n]?(t.bgColor&&this._drawRect({x:D,y:_,width:E,height:i,color:t.bgColor,fill:true}),this._drawRect({x:D,y:w,width:E,height:s,color:t.color,fill:true})):t.bgColor&&this._drawRect({x:D,y:t.y,width:E,height:t.height,color:t.bgColor,fill:true});}if(e.text){const s=i.length>2&&e.text.length>1?p.DockCharMargin*E:0,n=e.data.length*E;this._drawText({text:e.text,x:D-n+s,y:O,width:n-2*s,height:r,fontHeight:r,fontStyle:t.fontStyle,fontName:t.fontName,color:t.color,autoReturn:d.None,horizontalAlignment:"number"==typeof A?A:a.Center,charSpace:t.charSpace});}}return this.ctx.restore(),true}draw2DBarcode(t){"number"!=typeof t.x&&(t.x=0),"number"!=typeof t.y&&(t.y=0),"number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=t.width);const i=t.data,s=t.zoneSize||0,n=t.barPixels||this.ModulePixels,r="number"==typeof t.autoScaleLevel?t.autoScaleLevel:p.AUTO_SCALE_LEVEL,d=i.rows||0,u=i.cols||0;if(d<=0||u<=0)return false;const l=this.getItemRotation(t),g=this.getRotateMode(t.rotateMode),f=this.getPaddings(t),m=f[1]+f[3],C=f[0]+f[2],P=d+2*s,R=u+2*s,I=R*this.PixPerUnit,b=P*this.PixPerUnit;let y=this.getHorizontalAlignment(t.horizontalAlignment,a.Center),v=this.getVerticalAlignment(t.verticalAlignment,a.Center),A=0,E=0;(y>a.Stretch||y<a.Start)&&(y=a.Center),(v>a.Stretch||v<a.Start)&&(v=a.Center),t.width<=0?(A=n*this.PixPerUnit,t.width=A*R+m):t.width-m<=I?(A=this.PixPerUnit,t.width=I+m):A=(t.width-m)/R,t.height<=0?(E=n*this.PixPerUnit,t.height=E*P+C):t.height-C<=b?(E=this.PixPerUnit,t.height=b+C):E=(t.height-C)/P,t.color||(t.color=this.Foreground);const D=this.getAntiColor(t.antiColor);let w=D?t.bgColor:t.color;const _=D?t.color:t.bgColor;0!==(D&h.FillFull)&&(this.drawRect({x:t.x,y:t.y,width:t.width,height:t.height,color:t.color||this.Foreground,rotation:g===o.RotateContent?0:l,fill:true}),w&&!p.isTransparent(w)||(w=p.COLOR_BG_DEFAULT)),l>0&&p.isPortrait(l)&&g===o.RotateContent&&t.width>0&&t.height>0&&e.rotate90(t),this.ctx.save(),this.setRotation(l,{x:t.x,y:t.y},{width:t.width,height:t.height}),m>0&&(t.x+=f[3],t.width-=m),C>0&&(t.y+=f[0],t.height-=C),y<a.Stretch&&(A=Math.min(A,E),A<r*this.PixPerUnit&&(A=Math.floor(A/this.PixPerUnit)*this.PixPerUnit)),v<a.Stretch&&(E=Math.min(A,E),E<r*this.PixPerUnit&&(E=Math.floor(E/this.PixPerUnit)*this.PixPerUnit));const O=R*A,x=P*E;let T=0,S=0;switch(y){case a.Start:break;case a.End:T=Math.round(t.width-O);break;default:T=Math.round(.5*(t.width-O));}switch(v){case a.Start:break;case a.End:S=Math.round(t.height-x);break;default:S=Math.round(.5*(t.height-x));}const M=Math.floor(t.x+T),B=Math.floor(t.y+S);this.BorderAlign=c.None,_&&s>0&&(this._drawRect({x:M,y:B,width:Math.round(O),height:Math.round(E*s),color:_,fill:true}),this._drawRect({x:M,y:Math.round(B+(d+s)*E),width:Math.round(O),height:Math.round(s*E),color:_,fill:true}),this._drawRect({x:M,y:B,width:Math.round(A*s),height:Math.round(x),color:_,fill:true}),this._drawRect({x:Math.round(M+(u+s)*A),y:B,width:Math.round(s*A),height:Math.round(x),color:_,fill:true}));for(let t=0,e=B+E*s;t<d;t++,e+=E)for(let n=0,r=M+A*s;n<u;n++,r+=A)i.data[t*(i.cols||0)+n]?w&&this._drawRect({x:r,y:e,width:A,height:E,color:w,fill:true}):_&&this._drawRect({x:r,y:e,width:A,height:E,color:_,fill:true});return this.ctx.restore(),true}drawImage(t){const e=t.image||t.img,i=e?e.dzSrc||e:void 0;if(!i)return false;if(i.width&&i.height)if(t.width&&t.height)if(i.width/i.height>t.width/t.height){"number"!=typeof t.verticalAlignment&&"number"==typeof t.alignment&&(t.verticalAlignment=t.alignment);const e=t.y||0,s=t.width*i.height/i.width;0===t.verticalAlignment?t.height=s:2===t.verticalAlignment?(t.y=e+t.height-s,t.height=s):3===t.verticalAlignment||(t.y=e+.5*(t.height-s),t.height=s);}else {"number"!=typeof t.horizontalAlignment&&"number"==typeof t.alignment&&(t.horizontalAlignment=t.alignment);const e=t.x||0,s=i.width*t.height/i.height;0===t.horizontalAlignment?t.width=s:2===t.horizontalAlignment?(t.x=e+t.width-s,t.width=s):3===t.horizontalAlignment||(t.x=e+.5*(t.width-s),t.width=s);}else t.width?t.height=t.width*i.height/i.width:t.height&&(t.width=i.width*t.height/i.height);const s=Math.ceil(t.x||0),n=Math.ceil(t.y||0),r=t.width?Math.floor(t.width):i.width,a=t.height?Math.floor(t.height):i.height;this.ctx.save();const o=this.getItemRotation(t);return this.setRotation(o,{x:s,y:n},{width:r,height:a}),t.swidth&&t.sheight?this.ctx.drawImage(i,t.sx||0,t.sy||0,t.swidth,t.sheight,s,n,r,a):t.width||t.height?this.ctx.drawImage(i,s||0,n||0,r,a):this.ctx.drawImage(i,s,n),this.ctx.restore(),true}putImageData(t){return !!t.data&&(this.ctx.putImageData(t.data,t.x||0,t.y||0),true)}drawImageResizeLabel(t,e){if(!t.img||this.width<=0||this.height<=0)return;const i=t.img,s=i.width||t.imageWidth||0,n=i.height||t.imageHeight||0;let r=0,a=0,o=0;if(s<=0||n<=0)return void l.warn("---- drawImageResizeLabel: 无法获取 img 对象的像素大小,所以无法对目标图片进行分割绘制!");s/n<this.width/this.height?(o=this.height,a=s*this.height/s,r=this.height/n):(a=this.width,o=this.width*n/s,r=this.width/s);let h=r;t.fullOfLabel?h=r:t.relativeScale&&t.relativeScale>0?h=t.relativeScale*r:e&&(h=e);const c=Math.floor(t.left),d=Math.floor(t.top),u=Math.ceil(t.right),g=Math.ceil(t.bottom),p=u-c,f=g-d,m=s-u,C=n-g,P=a/(c+m+1),R=o/(d+C+1),I=Math.min(P,R);h>I&&(h=t.relativeScale&&t.relativeScale>0?I:r);const b=Math.floor(c*h),y=Math.floor(d*h),v=Math.floor(m*h),A=Math.floor(C*h),E=this.width-v,D=this.height-A;if(this.ctx.drawImage(i,0,0,c,d,0,0,b,y),this.ctx.drawImage(i,u,0,m,d,E,0,v,y),this.ctx.drawImage(i,u,g,m,C,E,D,v,A),this.ctx.drawImage(i,0,g,c,C,0,D,b,A),t.tileMode){const t=a-b-v,e=o-y-A;let s=t,n=e,r=p,h=f;if(t>0)for(let e=b;e<E;e+=t)E-e<t?(s=E-e,r=p*s/t):(s=t,r=p),this.ctx.drawImage(i,c,0,r,d,e,0,s,y),this.ctx.drawImage(i,c,g,r,C,e,D,s,A);if(e>0)for(let t=y;t<D;t+=e)D-t<e?(n=D-t,h=f*n/e):(n=e,h=f),this.ctx.drawImage(i,0,d,c,h,0,t,b,n),this.ctx.drawImage(i,u,d,m,h,E,t,v,n);}else {const t=E-b,e=D-y;this.ctx.drawImage(i,c,0,p,d,b,0,t,y),this.ctx.drawImage(i,u,d,m,f,E,y,v,e),this.ctx.drawImage(i,c,g,p,C,b,D,t,A),this.ctx.drawImage(i,0,d,c,f,0,y,b,e);}}measureText(t,e){null!==t.text&&void 0!==t.text||(t.text="");const i="string"==typeof t.text?t.text:String(t.text);if(i.length<=0)return {width:0};if((t.fontHeight||t.fontStyle||t.fontName)&&("boolean"!=typeof e||e)&&this.setFont(t.fontHeight,t.fontStyle,t.fontName),void 0!==this.ctx.measureText)return this.ctx.measureText(i);{let e=0;for(const s of i)e+=this.getCustomCharWidth(t.fontHeight||this.fontHeight,s);return {width:e}}}measureTextExt(t){const e=t.fontHeight||this.fontHeight;let i=t.width||0;const s=this.splitText(Object.assign(t,{text:t.text||""})),n=this.getLineSpace(t.lineSpace||0,e),r=t.charSpace||0,a=s.length>1?(s.length-1)*n:0;if(i<=0&&void 0!==this.ctx.measureText)for(let t=0;t<s.length;t++)if(s[t].length>0){const e=this.ctx.measureText(s[t]).width+(s[t].length-1)*r;e>i&&(i=e);}return {width:i,height:p.getLineHeight(e)*s.length+a}}measureFontSize(t){const e=t.text||"",i=t.width||0,s=t.minFontHeight||6;if(i<=0||e.length<=0||void 0===this.ctx.measureText)return t.fontHeight||0;let n,r=t.fontHeight||this.fontHeight;do{if(n=this.measureText({text:e,fontHeight:r,fontStyle:t.fontStyle,fontName:t.fontName}),n.width<=i)return r;r*=.95;}while(r>s);return s}findSplitPosition(t,e,i,s){var n;if(t.length<=1)return t.length;const r=s||0;let a=1,o=(null===(n=this.ctx.measureText(t.substring(0,a)))||void 0===n?void 0:n.width)||0;if(o<=0)return t.length;if(o>=e)return a;let h=0,c=0;if(r>0)for(;c<e&&h<t.length;)h+r>t.length?h=t.length:(c>o&&(a=h,o=c),h+=r),c=this.ctx.measureText(t.substring(0,h)).width+(h-1)*i;else h=t.length,c=this.ctx.measureText(t).width+(h-1)*i;if(c<=e)return h;for(;a<h&&h!==a+1;){const s=a+Math.floor((h-a)/2),n=this.ctx.measureText(t.substring(0,s)).width+(s-1)*i;if(n>e)h=s,c=n;else if(a=s,o=n,n>=e)break}return a}findWordSplitPos(t,e){let i=0;if(e>=t.length||/\W/.exec(t.charAt(e)))return e;for(i=e-1;i>=0&&!/\W/.exec(t.charAt(i));i--);return i+1}getCustomCharWidth(t,e){return !e||t<=0?0:/[\u4e00-\u9fa5]/.test(e)?t:/[a-zA-Z]/.test(e)?.55*t:/[0-9]/.test(e)?.5*t:/\s/.test(e)?.25*t:.5*t}splitText(t){if(p.isNull(t.text)&&!p.isNull(t.content)&&(t.text=t.content),p.isNull(t.text))return [];"number"!=typeof t.charSpace&&(t.charSpace=this.CharSpace);const e=t.charSpace>0?t.charSpace:0,i=Array.isArray(t.text)?t.text:[String(t.text)],s=[],n=void 0!==this.ctx.measureText;for(const t of i)s.push(...t.split("\n"));let r=0,a=0;const o=[],h=t.fontHeight||this.fontHeight,c=t.width||0;this.setFont(t.fontHeight,t.fontStyle,t.fontName);const u=this.getReturnMode(t.autoReturn);for(const i of s)if(i.length>0&&u&&c>0&&n){let s=i;for(;s.length>0;)r=this.findSplitPosition(s,c,e,t.measureOptimizeStep),u===d.Word&&(a=this.findWordSplitPos(s,r),a>0&&a<r&&(r=a)),o.push(s.substring(0,r)),s=r<s.length?s.substring(r):"";}else if(!n&&c>0){let t=0,e=0;for(let s=0;s<i.length;s++){const n=this.getCustomCharWidth(h,i[s]);t+=n,t>c&&s>e&&(o.push(i.substring(e,s)),e=s,t=n);}e<i.length&&o.push(i.substring(e));}else o.push(i);return o}inverseColors(){const t=this.ctx,e=this.getImageData();if(e){const i=e.data;for(let t=0;t<i.length;t+=4)i[t]=255-i[t],i[t+1]=255-i[t+1],i[t+2]=255-i[t+2];return t.putImageData(e,0,0),true}return false}horizontalFlip(){const t=this.ctx,e=this.getImageData(),i=t.createImageData(this.Canvas.width,this.Canvas.height);if(e&&i){const s=e.width,n=e.height;for(let t=0;t<n;t++)for(let n=0;n<s;n++)i.data[t*s*4+4*n+0]=e.data[t*s*4+4*(s-n)+0],i.data[t*s*4+4*n+1]=e.data[t*s*4+4*(s-n)+1],i.data[t*s*4+4*n+2]=e.data[t*s*4+4*(s-n)+2],i.data[t*s*4+4*n+3]=e.data[t*s*4+4*(s-n)+3];return t.putImageData(i,0,0),true}return false}getImageData(){return "function"==typeof this.ctx.getImageData?this.ctx.getImageData(0,0,this.Canvas.width,this.Canvas.height):void l.info("---- 当前绘制环境不支持函数:getImageData")}}p.NO_START_STOP=4,p.MinBarHeight=2,p.BarTextMargin=1,p.DockHorizMargin=7,p.DockCharMargin=1,p.BarIsbnMargin=0,p.AUTO_SCALE_LEVEL=2,p.COLOR_FG_DEFAULT="#000",p.COLOR_BG_DEFAULT="#fff",p.LINE_WIDTH=28,p.FONT_NAME="黑体",p.TEXT_BASELINE_DEFAULT="alphabetic";class f{constructor(t){this._dpi=203,this._dpm=203/25.4,this._offsetX=0,this._offsetY=0,this.cvs=new p(t);}get Base(){return this.cvs}get ScaleUnit(){return this._scaleUnit||u.Auto}get Dpi(){return this._dpi}set Dpi(t){t&&t>0&&(this._dpi=t,this._dpm=t/25.4);}get DPM(){return this._dpm}set DPM(t){t>0&&(this._dpm=t,this._dpi=25.4*t);}get OffsetX(){return this._offsetX}set OffsetX(t){this._offsetX=t;}get OffsetY(){return this._offsetY}set OffsetY(t){this._offsetY=t;}get Width(){return this.cvs.Width/this.DPM}get Height(){return this.cvs.Height/this.DPM}get CanvasWidth(){return this.cvs.Canvas.width}get CanvasHeight(){return this.cvs.Canvas.height}get Foreground(){return this.cvs.Foreground}set Foreground(t){this.cvs.Foreground=t;}setFontName(t){this.cvs.FontName=t;}getFontHeight(){return this.invertCvt(this.cvs.FontHeight)}setFontHeight(t){this.cvs.FontHeight=this.cvt(t);}setLineSpace(t){this.cvs.LineSpace=this.cvt(t);}parseLineSpace(t,e){return "number"==typeof t?t:"string"==typeof t?this.cvs.getLineSpace(t,e):0}setCharSpace(t){this.cvs.CharSpace=this.cvt(t);}getLineWidth(){return this.invertCvt(this.cvs.LineWidth)}setLineWidth(t){this.cvs.LineWidth=this.cvt(t);}setRotation(t,e,i){return e&&(e.x=this.cvt(e.x),e.y=this.cvt(e.y)),i&&(i.width=this.cvt(i.width),i.height=this.cvt(i.height)),this.cvs.setRotation(t,e,i)}supports(t){return this.cvs.supports(t)}startJob(t){return this._scaleUnit=t.scaleUnit,t.dpi&&(this.Dpi=t.dpi),this.cvs.startJob(this.cvtDrawOptions(t))?this.cvs:void 0}commitJob(){return this.cvs.commitJob()?this.cvs:void 0}drawLine(t){return this.cvs.drawLine(this.cvtDrawOptions(t))}drawRect(t){return this.cvs.drawRect(this.cvtDrawOptions(t))}drawRoundRect(t){return this.cvs.drawRoundRect(this.cvtDrawOptions(t))}drawEllipse(t){return this.cvs.drawEllipse(this.cvtDrawOptions(t))}drawCircle(t){return this.cvs.drawCircle(this.cvtDrawOptions(t))}drawText(t){return this.cvs.drawText(this.cvtDrawOptions(t))}drawArcText(t){return this.cvs.drawArcText(this.cvtDrawOptions(t))}draw1DBarcode(t){return (t=this.cvtDrawOptions(t)).textHeight=this.cvt(t.textHeight),this.cvs.draw1DBarcode(t)}draw2DBarcode(t){return this.cvs.draw2DBarcode(this.cvtDrawOptions(t))}drawImage(t){return this.cvs.drawImage(this.cvtDrawOptions(t))}drawImageResizeLabel(t){return this.cvs.drawImageResizeLabel(t,this.DPM/20)}putImageData(t){return this.cvs.putImageData(this.cvtDrawOptions(t))}splitText(t){return this.cvs.splitText(this.cvtDrawOptions(t))}measureText(t){return t.fontHeight=this.cvt(t.fontHeight),this.cvs.measureText(t)}measureFontSize(t){t=this.cvtDrawOptions(t);const e=this.cvs.measureFontSize(t);return this.invertCvt(e)}cvt(t){return "number"==typeof t?t*this._dpm:t}invertCvt(t){return "number"==typeof t?t/this._dpm:t}cvtArray(t){if(Array.isArray(t))for(let e=0;e<t.length;e++)t[e]=this.cvt(t[e]);return t}cvtDrawOptions(t){if(this.ScaleUnit===u.Pix)return t;"number"==typeof(t=Object.assign({},t)).x&&(t.x=this.cvt(t.x+this.OffsetX)),"number"==typeof t.y&&(t.y=this.cvt(t.y+this.OffsetY)),t.width&&(t.width=this.cvt(t.width)),t.height&&(t.height=this.cvt(t.height)),"number"==typeof t.margin?t.margin=this.cvt(t.margin):this.cvtArray(t.margin);const e=t;e.lineWidth&&(e.lineWidth=this.cvt(e.lineWidth)),e.radius&&(e.radius=this.cvt(e.radius));const i=t;i.cornerWidth&&(i.cornerWidth=this.cvt(i.cornerWidth)),i.cornerHeight&&(i.cornerHeight=this.cvt(i.cornerHeight));const s=t;s.x1&&(s.x1=this.cvt(s.x1+this.OffsetX)),s.y1&&(s.y1=this.cvt(s.y1+this.OffsetY)),s.x2&&(s.x2=this.cvt(s.x2+this.OffsetX)),s.y2&&(s.y2=this.cvt(s.y2+this.OffsetY)),s.dashLens&&(s.dashLens=s.dashLens.map(t=>this.cvt(t))),s.dashLen&&(s.dashLen=s.dashLen.split(",").map(t=>this.cvt(+t)).join(","));const n=t;"number"==typeof n.padding?n.padding=this.cvt(n.padding):this.cvtArray(n.padding);const r=t;return r.fontHeight&&(r.fontHeight=this.cvt(r.fontHeight)),r.minFontHeight&&(r.minFontHeight=this.cvt(r.minFontHeight)),r.lineSpace&&"number"==typeof r.lineSpace&&(r.lineSpace=this.cvt(r.lineSpace)),r.charSpace&&(r.charSpace=this.cvt(r.charSpace)),t}inverseColors(){return this.cvs.inverseColors()}horizontalFlip(){return this.cvs.horizontalFlip()}getImageData(){return this.cvs.getImageData()}}function m(t,e,i,s){return new(i||(i=Promise))(function(e,n){function r(t){try{o(s.next(t));}catch(t){n(t);}}function a(t){try{o(s.throw(t));}catch(t){n(t);}}function o(t){var s;t.done?e(t.value):(s=t.value,s instanceof i?s:new i(function(t){t(s);})).then(r,a);}o((s=s.apply(t,[])).next());})}f.BORDER_DPM_DEFAULT=8,"function"==typeof SuppressedError&&SuppressedError;class C{constructor(t,e){this.cols=t||0,this.rows=e||0,this.data=new Uint8Array(this.rows*this.cols);}get reservedBit(){return this._reservedBit||(this._reservedBit=new Uint8Array(this.data.length)),this._reservedBit}set(t,e,i,s){const n=t*this.cols+e;this.data[n]="number"==typeof i?i:i?1:0,s&&(this.reservedBit[n]=1);}get(t,e){return this.data[t*this.cols+e]}getRowData(t){const e=(t||0)*this.cols;return this.data.slice(e,e+this.cols)}getColData(t){return this.data.filter((e,i)=>i%this.cols===t)}xor(t,e,i){this.data[t*this.cols+e]^=i?1:0;}fill(t,e,i,s){const n=(e||0)*this.cols+(i||0);let r=0;r="number"==typeof s?s>0?n+s:this.data.length+s:this.data.length,this.data.fill(t,n,r);}setArray(t,e,i){const s=(e||0)*this.cols+(i||0);this.data.set(t,s);}addRow(t,e,i){e>=this.data.length?console.error(`offset: ${e} 越界`):(i&&i<t.length&&(t=t.slice(0,i)),this.data.set(t,e));}isReserved(t,e){return this._reservedBit?this._reservedBit[t*this.cols+e]:0}}const P=Object.freeze({nullCharacter:0,maxAsciiCharacter:127,lineFeed:10,LF:10,carriageReturn:13,CR:13,lineSeparator:8232,paragraphSeparator:8233,nextLine:133,space:32,nonBreakingSpace:160,enQuad:8192,emQuad:8193,enSpace:8194,emSpace:8195,threePerEmSpace:8196,fourPerEmSpace:8197,sixPerEmSpace:8198,figureSpace:8199,punctuationSpace:8200,thinSpace:8201,hairSpace:8202,zeroWidthSpace:8203,narrowNoBreakSpace:8239,ideographicSpace:12288,mathematicalSpace:8287,ogham:5760,_:95,$:36,num_0:48,num_9:57,a:97,z:122,A:65,Z:90,ampersand:38,asterisk:42,at:64,backslash:92,backtick:96,bar:124,caret:94,closeBrace:125,closeBracket:93,closeParen:41,colon:58,comma:44,dot:46,doubleQuote:34,equals:61,exclamation:33,greaterThan:62,hash:35,lessThan:60,minus:45,openBrace:123,openBracket:91,openParen:40,percent:37,plus:43,question:63,semicolon:59,singleQuote:39,slash:47,tilde:126,backspace:8,formFeed:12,byteOrderMark:65279,tab:9,verticalTab:11});class R{static isDigit(t){return "number"==typeof t?t>=P.num_0&&t<=P.num_9:t>="0"&&t<="9"}static isDigits(t,e,i){const s=e||0,n=i?s+i:t.length;return !(n>t.length)&&t.substring(s,n).match(/^[0-9]+$/)}static isUpper(t){return "number"==typeof t?t>=P.A&&t<=P.Z:t>="A"&&t<="Z"}static isLower(t){return "number"==typeof t?t>=P.a&&t<=P.z:t>="a"&&t<="z"}static ctoi(t){const e="string"==typeof t?t.charCodeAt(0):t;return e>=P.num_0&&e<=P.num_9?e-P.num_0:e>=P.A&&e<=P.Z?e-P.A+10:e>=P.a&&e<=P.z?e-P.a+10:-1}static itoc(t){return t>=0&&t<=9?`${t}`:String.fromCharCode(t-10+P.A)}static repeatChar(t,e){const i=[];for(let s=0;s<e;s++)i.push(t);return i.join("")}static preFillChar(t,e,i){return t.length<e?Array(e-t.length+1).join(i)+t:t}}class I{static isISO_8859_1(t){if(!t)return false;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255)return false;return true}static getCharCodes(t){t=t||"";const e=[];for(let i=0;i<t.length;i++)e.push(t.charCodeAt(i));return e}static getCharCodeArrayString(t){return t.map(t=>String.fromCharCode(t)).join("")}static encodeUtf8(t){const e=[];for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);if(s>=55296&&s<=56319&&t.length>i+1){const e=t.charCodeAt(i+1);e>=56320&&e<=57343&&(s=1024*(s-55296)+e-56320+65536,i+=1);}s<128?e.push(s):s<2048?(e.push(s>>6|192),e.push(63&s|128)):s<55296||s>=57344&&s<65536?(e.push(224|s>>12),e.push(128|s>>6&63),e.push(128|63&s)):s>=65536&&s<=1114111?(e.push(240|s>>18),e.push(128|s>>12&63),e.push(128|s>>6&63),e.push(128|63&s)):e.push(239,191,189);}return new Uint8Array(e)}static getBytes_Utf8(t){try{return (new TextEncoder).encode(t)}catch(e){return console.log("DzTextEncoder.encode: TextEncoder is not defined"),this.encodeUtf8(t)}}static getBytes_ISO8859_1(t){return t=unescape(encodeURIComponent(t)),Uint8Array.from(this.getCharCodes(t))}static getBytes_Unicode(t){return Uint8Array.from(this.getCharCodes(t))}static getBytes(t,e){return t=t||"",e?I.getBytes_Utf8(t):I.getBytes_Unicode(t)}static hasBase256Chars(t){const e="string"==typeof t?t.split("").map(t=>t.charCodeAt(0)):t;if((null==e?void 0:e.length)>0)for(const t of e)if(t>=128)return true;return false}static encodeUnicodeFromUtf8(t){let e=0,i=0,s=0;const n=[];do{if(t[i]<=127)n[s]=t[i],e=i+1,s++;else {if(t[i]>=128&&t[i]<=191)return;if(t[i]>=192&&t[i]<=193)return;if(t[i]>=194&&t[i]<=223)n[s]=((31&t[i])<<6)+(63&t[i+1]),e=i+2,s++;else if(t[i]>=224&&t[i]<=239)n[s]=((15&t[i])<<12)+((63&t[i+1])<<6)+(63&t[i+2]),e=i+3,s++;else if(t[i]>=240)return}i=e;}while(i<t.length);return n}}var b;!function(t){t[t.UPC_A=20]="UPC_A",t[t.UPC_E=21]="UPC_E",t[t.EAN13=22]="EAN13",t[t.EAN8=23]="EAN8",t[t.CODE39=24]="CODE39",t[t.ITF25=25]="ITF25",t[t.CODABAR=26]="CODABAR",t[t.CODE93=27]="CODE93",t[t.CODE128=28]="CODE128",t[t.ISBN=29]="ISBN",t[t.ECODE39=30]="ECODE39",t[t.ITF14=31]="ITF14",t[t.ChinaPost=32]="ChinaPost",t[t.Matrix25=33]="Matrix25",t[t.Industrial25=34]="Industrial25",t[t.GS1_128=35]="GS1_128",t[t.EAN128=35]="EAN128",t[t.AUTO=60]="AUTO";}(b||(b={}));class y{constructor(t,e){this.data=t||"",this.text=e.text||t||"",this.options=e;}encode(t,e){return {}}}const v=103,A=104,E=105,D={[v]:0,[A]:1,[E]:2},w={101:0,100:1,99:2},_=String.fromCharCode(208),O=String.fromCharCode(209),x=String.fromCharCode(210),T="[\0-_È-Ï]",S="[ -È-Ï]",M=[11011001100,11001101100,11001100110,10010011e3,10010001100,10001001100,10011001e3,10011000100,10001100100,11001001e3,11001000100,11000100100,10110011100,10011011100,10011001110,10111001100,10011101100,10011100110,11001110010,11001011100,11001001110,11011100100,11001110100,11101101110,11101001100,11100101100,11100100110,11101100100,11100110100,11100110010,11011011e3,11011000110,11000110110,10100011e3,10001011e3,10001000110,10110001e3,10001101e3,10001100010,11010001e3,11000101e3,11000100010,10110111e3,10110001110,10001101110,10111011e3,10111000110,10001110110,11101110110,11010001110,11000101110,11011101e3,11011100010,11011101110,11101011e3,11101000110,11100010110,11101101e3,11101100010,11100011010,11101111010,11001000010,11110001010,1010011e4,10100001100,1001011e4,10010000110,10000101100,10000100110,1011001e4,10110000100,1001101e4,10011000010,10000110100,10000110010,11000010010,1100101e4,11110111010,11000010100,10001111010,10100111100,10010111100,10010011110,10111100100,10011110100,10011110010,11110100100,11110010100,11110010010,11011011110,11011110110,11110110110,10101111e3,10100011110,10001011110,10111101e3,10111100010,11110101e3,11110100010,10111011110,10111101110,11101011110,11110101110,11010000100,1101001e4,11010011100,1100011101011];class B extends y{constructor(t,e){super(t.substring(1),e),this.bytes=t.split("").map(t=>t.charCodeAt(0));}valid(){return /^[\x00-\x7F\xC8-\xD3]+$/.test(this.data)}encode(){const t=this.bytes,e=(t.shift()||0)-105,i=D[e];if(void 0===i)throw new RangeError("The encoding does not start with a start character.");this.shouldEncodeAsEan128()&&t.unshift(207);const s=B.next(t,1,i);return {items:[{text:this.text===this.data?this.text.replace(/[^\x20-\x7E]/g,""):this.text,data:B.getBar(e)+s.result+B.getBar((s.checksum+e)%103)+B.getBar(106)}],text:this.text,options:this.options}}shouldEncodeAsEan128(){return this.options.ean128}static getBar(t){return M[t]?M[t].toString():""}static correctIndex(t,e){if(0===e){const e=t.shift()||0;return e<32?e+64:e-32}return 1===e?(t.shift()||0)-32:10*((t.shift()||0)-48)+(t.shift()||0)-48}static next(t,e,i){if(!t.length)return {result:"",checksum:0};let s,n;if(t[0]>=200){n=(t.shift()||0)-105;const r=w[n]||0;void 0!==r?s=B.next(t,e+1,r):(0!==i&&1!==i||98!==n||(t[0]=0===i?t[0]>95?t[0]-96:t[0]:t[0]<32?t[0]+96:t[0]),s=B.next(t,e+1,i));}else n=B.correctIndex(t,i),s=B.next(t,e+1,i);const r=n*e;return {result:B.getBar(n)+s.result,checksum:r+s.checksum}}}const L=t=>{const e=t.match(new RegExp(`^${T}*`));return e?e[0].length:0},N=t=>{const e=t.match(new RegExp(`^${S}*`));return e?e[0].length:0},U=t=>{const e=t.match(new RegExp("^(Ï*[0-9]{2}Ï*)*"));return e?e[0]:""};function F(t,e){const i=e?T:S,s=t.match(new RegExp(`^(${i}+?)(([0-9]{2}){2,})([^0-9]|$)`));if(s)return s[1]+String.fromCharCode(204)+$(t.substring(s[1].length));const n=t.match(new RegExp(`^${i}+`)),r=n?n[0]:"";return r.length===t.length?t:r+String.fromCharCode(e?205:206)+F(t.substring(r.length),!e)}function $(t){const e=U(t),i=e.length;if(i===t.length)return t;t=t.substring(i);const s=L(t)>=N(t);return e+String.fromCharCode(s?206:205)+F(t,s)}class j extends B{constructor(t,e){if(/^[\x00-\x7F\xC8-\xD3]+$/.test(t)){let i;if(U(t).length>=2)i=x+$(t);else {const e=L(t)>N(t);i=(e?_:O)+F(t,e);}super(i.replace(/[\xCD\xCE]([^])[\xCD\xCE]/,(t,e)=>String.fromCharCode(203)+e),e);}else super(t,e);}}const H={L:["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],G:["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],R:["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],O:["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],E:["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"]},W=(t,e,i)=>{let s=t.split("").map((t,i)=>H[e[i]]).map((e,i)=>e?e[t[i]]:"");if(i){const e=t.length-1;s=s.map((t,s)=>s<e?t+i:t);}return s.join("")};let k=class t extends y{constructor(t,e){super(t,e),this.quietZones=0,this.guardWhitespace=false,this.quietZones=e.quietZones||0,this.guardWhitespace=e.guardWhitespace||false;}encode(){const t=this.options.flat?this.encodeFlat():this.encodeGuarded();return {options:this.options,items:t,text:this.text}}leftText(t,e){return this.text.substr(t,e)}leftEncode(t,e){return W(t||"",e||"")}rightText(t,e){return this.text.substr(t,e)}rightEncode(t,e){return W(t||"",e||"")}encodeGuarded(){const e=[{data:t.SIDE_BIN,text:""},{data:this.leftEncode(),text:this.leftText(0)},{data:t.MIDDLE_BIN,text:""},{data:this.rightEncode(),text:this.rightText()},{data:t.SIDE_BIN,text:""}];if(this.quietZones>0){const t=Array(this.quietZones).fill("0").join("");e.unshift({data:t,text:this.guardWhitespace?"< ":""}),e.push({data:t,text:this.guardWhitespace?" >":""});}return e}encodeFlat(){return [{data:[t.SIDE_BIN,this.leftEncode(),t.MIDDLE_BIN,this.rightEncode(),t.SIDE_BIN].join(""),text:this.text}]}};k.SIDE_BIN="101",k.MIDDLE_BIN="01010";class J extends y{constructor(t,e){super(t,e);}valid(){return -1!==this.data.search(/^[0-9]{2}$/)}encode(){const t=J.EAN2_STRUCTURE[parseInt(this.data)%4],e={data:"1011"+W(this.data,t,"01"),text:this.text};return {options:this.options,items:[e],text:this.text}}}J.EAN2_STRUCTURE=["LL","LG","GL","GG"];class V extends y{static checksum(t){return t.split("").map(t=>+t).reduce((t,e,i)=>i%2?t+9*e:t+3*e,0)%10}constructor(t,e){super(t,e);}valid(){return -1!==this.data.search(/^[0-9]{5}$/)}encode(){const t=V.EAN5_STRUCTURE[V.checksum(this.data)];return {items:[{data:"1011"+W(this.data,t,"01"),text:this.text}],text:this.text,options:this.options}}}V.EAN5_STRUCTURE=["GGLLL","GLGLL","GLLGL","GLLLG","LGGLL","LLGGL","LLLGG","LGLGL","LGLLG","LLGLG"];class G extends k{static checksum(t){return (10-t.substring(0,7).split("").map(t=>+t).reduce((t,e,i)=>i%2?t+e:t+3*e,0)%10)%10}constructor(t,e){ -1!==t.search(/^[0-9]{7}$/)&&(t+=G.checksum(t)),super(t,e);}valid(){return -1!==this.data.search(/^[0-9]{8}$/)&&+this.data[7]===G.checksum(this.data)}leftText(){return super.leftText(0,4)}leftEncode(){const t=this.data.substring(0,4);return super.leftEncode(t,"LLLL")}rightText(){return super.rightText(4,4)}rightEncode(){const t=this.data.substring(4,8);return super.rightEncode(t,"RRRR")}}let K=class t extends k{static checksum(t){return (10-t.substring(0,12).split("").map(t=>+t).reduce((t,e,i)=>i%2?t+3*e:t+e,0)%10)%10}constructor(e,i){ -1!==e.search(/^[0-9]{12}$/)&&(e+=t.checksum(e)),super(e,i);}valid(){return -1!==this.data.search(/^[0-9]{13}$/)&&+this.data[12]===t.checksum(this.data)}leftText(){return super.leftText(1,6)}leftEncode(){const e=this.data.substring(1,7),i=t.EAN13_STRUCTURE[Number(this.data[0])];return super.leftEncode(e,i)}rightText(){return super.rightText(7,6)}rightEncode(){const t=this.data.substring(7,13);return super.rightEncode(t,"RRRRRR")}encodeGuarded(){const t=super.encodeGuarded();return this.quietZones>0?t[0].text=this.text[0]:t.unshift({data:"00000",text:this.text[0]}),t}};K.EAN13_STRUCTURE=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"];class z extends y{static checksum(t){let e,i=0;for(e=1;e<11;e+=2)i+=parseInt(t[e]);for(e=0;e<11;e+=2)i+=3*parseInt(t[e]);return (10-i%10)%10}constructor(t,e){ -1!==t.search(/^[0-9]{11}$/)&&(t+=z.checksum(t)),super(t,e),this.displayValue=e.displayValue;}valid(){return -1!==this.data.search(/^[0-9]{12}$/)&&parseInt(this.data[11])===z.checksum(this.data)}encode(){return {items:this.options.flat?this.flatEncoding():this.guardedEncoding(),text:this.text,options:this.options}}flatEncoding(){let t="";return t+="101",t+=W(this.data.substring(0,6),"LLLLLL"),t+="01010",t+=W(this.data.substring(6,6),"RRRRRR"),t+="101",[{data:t,text:this.text}]}guardedEncoding(){const t=[],e="number"==typeof this.options.quietZones&&this.options.quietZones>2?this.options.quietZones:2,i=Array(e).fill("0").join("");return t.push({data:i,text:this.text.substring(0,1)}),t.push({data:"101"+W(this.data[0],"L")}),t.push({data:W(this.data.substring(1,6),"LLLLL"),text:this.text.substring(1,6)}),t.push({data:"01010"}),t.push({data:W(this.data.substring(6,11),"RRRRR"),text:this.text.substring(6,11)}),t.push({data:W(this.data[11],"R")+"101"}),t.push({data:i,text:this.text.substring(11,12)}),t}}const Z=["XX00000XXX","XX10000XXX","XX20000XXX","XXX00000XX","XXXX00000X","XXXXX00005","XXXXX00006","XXXXX00007","XXXXX00008","XXXXX00009"],q=[["EEEOOO","OOOEEE"],["EEOEOO","OOEOEE"],["EEOOEO","OOEEOE"],["EEOOOE","OOEEEO"],["EOEEOO","OEOOEE"],["EOOEEO","OEEOOE"],["EOOOEE","OEEEOO"],["EOEOEO","OEOEOE"],["EOEOOE","OEOEEO"],["EOOEOE","OEEOEO"]];class X extends y{static expandToUPCA(t,e){const i=parseInt(t[t.length-1]),s=Z[i];let n="",r=0;for(let e=0;e<s.length;e++){const i=s[e];n+="X"===i?t[r++]:i;}return n=`${e}${n}`,`${n}${z.checksum(n)}`}constructor(t,e){if(super(t,e),this.middleDigits="",this.upcA="",this.isValid=false,-1!==t.search(/^[0-9]{6}$/))this.middleDigits=t,this.upcA=X.expandToUPCA(t,"0"),this.text=e.text||`${this.upcA[0]}${t}${this.upcA[this.upcA.length-1]}`,this.isValid=true;else {if(-1===t.search(/^[01][0-9]{7}$/))return;if(this.middleDigits=t.substring(1,t.length-1),this.upcA=X.expandToUPCA(this.middleDigits,t[0]),this.upcA[this.upcA.length-1]!==t[t.length-1])return;this.isValid=true;}this.displayValue=e.displayValue;}valid(){return this.isValid}encode(){return {items:this.options.flat?this.flatEncoding():this.guardedEncoding(),text:this.text,options:this.options}}flatEncoding(){let t="";return t+="101",t+=this.encodeMiddleDigits(),t+="010101",[{data:t,text:this.text}]}guardedEncoding(){const t=[],e="number"==typeof this.options.quietZones&&this.options.quietZones>2?this.options.quietZones:2,i=Array(e).fill("0").join("");return t.push({data:i,text:this.text[0]}),t.push({data:"101",text:""}),t.push({data:this.encodeMiddleDigits(),text:this.text.substring(1,7)}),t.push({data:"010101",text:""}),t.push({data:i,text:this.text[7]}),t}encodeMiddleDigits(){const t=this.upcA[0],e=this.upcA[this.upcA.length-1],i=q[parseInt(e)][parseInt(t)];return W(this.middleDigits,i)}}class Y{constructor(){this.latch=true,this.allEncodes="";}static getDigitText(t){return (t||"").replace(/\D/g,"")}static getInstance(){return this.instance||(this.instance=new Y)}static encode(t){return this.getInstance().init().expand(t)}static checkDigit(t,e){const i=e||t.length;let s=0,n=1&i?3:1;for(let e=0;e<i;e++)s+=n*parseInt(t[e]),n^=2;return String((10-s%10)%10)}init(){return this.latch=true,this.allEncodes="",this}expand(t){let e="";for(let i=0,s=0;i<t.length;i++)s=parseInt(t[i]),e+=Array(s).fill(this.latch?"1":"0").join(""),this.latch=!this.latch;return this.allEncodes+=e,e}}const Q=["BBBAAA","BBABAA","BBAABA","BBAAAB","BABBAA","BAABBA","BAAABB","BABABA","BABAAB","BAABAB"],tt=["AAABBB","AABABB","AABBAB","AABBBA","ABAABB","ABBAAB","ABBBAA","ABABAB","ABABBA","ABBABA"],et=["AA","AB","BA","BB"],it=["BBAAA","BABAA","BAABA","BAAAB","ABBAA","AABBA","AAABB","ABABA","ABAAB","AABAB"],st=["AAAAA","ABABB","ABBAB","ABBBA","BAABB","BBAAB","BBBAA","BABAB","BABBA","BBABA"],nt=["3211","2221","2122","1411","1132","1231","1114","1312","1213","3112"],rt=["1123","1222","2212","1141","2311","1321","4111","2131","3121","2113"],at=["112211","211121","121121","221111","112121","212111","122111","111221","211211","121211"],ot=["1111212111","2111111121","1121111121","2121111111","1111211121","2111211111","1121211111","1111112121","2111112111","1121112111"],ht=["11221","21112","12112","22111","11212","21211","12211","11122","21121","12121"],ct=["1111","211"],dt=["411111","41111"],ut=["212111","21112"],lt=["1111","211"];class gt extends y{constructor(t,e){super(t=Y.getDigitText(t),e);}static gs1_check_digit(t,e){"number"==typeof e&&(e>t.length?t=t.padStart(e,"0"):e<t.length&&(t=t.substring(0,e)));let i=1&t.length?3:1,s=0;for(let e=0;e<t.length;e++)s+=i*parseInt(t[e]),i^=2;return ""+(10*Math.ceil(s/10)-s)}static c25_common(t,e,i,s,n){t=Y.getDigitText(t),s&&s>0&&t.length>s&&(t=t.substring(0,s)),n.checkDigit&&(t+=gt.gs1_check_digit(t));const r=[];if(i)for(let e=0;e<t.length;e++)r.push(at[t.charCodeAt(e)-P.num_0]);else for(let e=0;e<t.length;e++)r.push(ot[t.charCodeAt(e)-P.num_0]);return {options:n,items:[{text:t,data:Y.encode([e[0],...r,e[1]].join(""))}],text:t}}static c25_inter_common(t,e){(t=Y.getDigitText(t)).length>125&&(t=t.substring(0,125)),(t.length%2==1&&!e.checkDigit||t.length%2==1&&e.checkDigit)&&(t="0"+t),e.checkDigit&&(t+=gt.gs1_check_digit(t));const i=[];for(let e=0;e<t.length;e+=2){const s=ht[parseInt(t[e])],n=ht[parseInt(t[e+1])];for(let t=0;t<5;t++)i.push(`${s[t]}${n[t]}`);}return {options:e,items:[{text:t,data:Y.encode([ct[0],...i,ct[1]].join(""))}],text:t}}encode(){return gt.c25_inter_common(this.data,this.options)}}class pt extends gt{encode(){return gt.c25_common(this.data,dt,true,80,this.options)}}class ft extends gt{encode(){return gt.c25_common(this.data,ut,false,45,this.options)}}class mt extends gt{encode(){return gt.c25_common(this.data,lt,true,80,this.options)}}class Ct extends gt{encode(){let t=this.data;return t.length>13?t=t.substring(0,13):t.length<13&&(t=t.padStart(13,"0")),t+=gt.gs1_check_digit(t),this.data=this.text=t,gt.c25_inter_common(t,this.options)}}class Pt extends y{constructor(t,e){0===t.search(/^[0-9\-\$\:\.\+\/]+$/)&&(t="A"+t+"A"),super(t.toUpperCase(),e),this.text=this.options.text||this.text.replace(/[A-D]/g,"");}valid(){return -1!==this.data.search(/^[A-D][0-9\-\$\:\.\+\/]+[A-D]$/)}encode(){const t=[],e=this.getEncodings();for(let i=0;i<this.data.length;i++)t.push(e[this.data.charAt(i)]),i!==this.data.length-1&&t.push("0");return {items:[{text:this.text,data:t.join("")}],text:this.text,options:this.options}}getEncodings(){return {0:"101010011",1:"101011001",2:"101001011",3:"110010101",4:"101101001",5:"110101001",6:"100101011",7:"100101101",8:"100110101",9:"110100101","-":"101001101",$:"101100101",":":"1101011011","/":"1101101011",".":"1101101101","+":"1011011011",A:"1011001001",B:"1001001011",C:"1010010011",D:"1010011001"}}}const Rt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd",It=["1112212111","2112111121","1122111121","2122111111","1112211121","2112211111","1122211111","1112112121","2112112111","1122112111","2111121121","1121121121","2121121111","1111221121","2111221111","1121221111","1111122121","2111122111","1121122111","1111222111","2111111221","1121111221","2121111211","1111211221","2111211211","1121211211","1111112221","2111112211","1121112211","1111212211","2211111121","1221111121","2221111111","1211211121","2211211111","1221211111","1211112121","2211112111","1221112111","1212121111","1212111211","1211121211","1112121211"],bt=["%U","$A","$B","$C","$D","$E","$F","$G","$H","$I","$J","$K","$L","$M","$N","$O","$P","$Q","$R","$S","$T","$U","$V","$W","$X","$Y","$Z","%A","%B","%C","%D","%E"," ","/A","/B","/C","/D","/E","/F","/G","/H","/I","/J","/K","/L","-",".","/O","0","1","2","3","4","5","6","7","8","9","/Z","%F","%G","%H","%I","%J","%V","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","%K","%L","%M","%N","%O","%W","+A","+B","+C","+D","+E","+F","+G","+H","+I","+J","+K","+L","+M","+N","+O","+P","+Q","+R","+S","+T","+U","+V","+W","+X","+Y","+Z","%P","%Q","%R","%S","%T"],yt=["bU","aA","aB","aC","aD","aE","aF","aG","aH","aI","aJ","aK","aL","aM","aN","aO","aP","aQ","aR","aS","aT","aU","aV","aW","aX","aY","aZ","bA","bB","bC","bD","bE"," ","cA","cB","cC","$","%","cF","cG","cH","cI","cJ","+","cL","-",".","/","0","1","2","3","4","5","6","7","8","9","cZ","bF","bG","bH","bI","bJ","bV","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bK","bL","bM","bN","bO","bW","dA","dB","dC","dD","dE","dF","dG","dH","dI","dJ","dK","dL","dM","dN","dO","dP","dQ","dR","dS","dT","dU","dV","dW","dX","dY","dZ","bP","bQ","bR","bS","bT"],vt=["131112","111213","111312","111411","121113","121212","121311","111114","131211","141111","211113","211212","211311","221112","221211","231111","112113","112212","112311","122112","132111","111123","111222","111321","121122","131121","212112","212211","211122","211221","221121","222111","112122","112221","122121","123111","121131","311112","311211","321111","112131","113121","211131","121221","312111","311121","122211"];class At extends y{constructor(t,e){const i=function(t){const e=[],i=[];let s=0,n=0;for(let r=0,a="",o="";r<t.length;r++)if(a=t[r],n=t.charCodeAt(r),o=yt[n],n>127)l.warn(`---- [encode with code93] invalid char: '${a}'[${n}]`);else {if(s+o.length>107){l.warn(`---- content too long, discarded content[${r} --\x3e ${t.length}]: "${t.substring(r)}"`);break}e.push(o),i.push(a>" "&&127!==n?a:" "),s+=o.length;}return {data:e.join(""),text:i.join("")}}(t);e.text=i.text,super(i.data,e);}encode(){const t=[],e=[];for(let e=0;e<this.data.length;e++)t.push(Rt.indexOf(this.data[e]));let i=0,s=1;for(let e=this.data.length-1;e>=0;e--)i+=t[e]*s,s++,21==s&&(s=1);i%=47,t.push(i);let n=0;s=1;for(let e=this.data.length;e>=0;e--)n+=t[e]*s,s++,16==s&&(s=1);n%=47,t.push(n),e.push("111141");for(let i=0;i<t.length;i++)e.push(vt[t[i]]);return e.push("1111411"),{items:[{data:Y.encode(e.join("")),text:this.options.mod43?`${this.text}${Rt[i]}${Rt[n]}`:this.text}],text:this.text,options:this.options}}valid(){return -1!==this.data.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/)}}function Et(t){const e=t.charCodeAt(0);return bt[e]}class Dt extends y{constructor(t,e){if(t=t.toUpperCase(),e.mod43){const i=e.text||t,s=function(t){const e=t.length%43;return Rt[e]}(t);t+=s,e.text=i+s;}super(t,e);}encode(){const t=[],e=[],i=this.data;for(let e=0;e<i.length;e++){const s=Rt.indexOf(i[e]);s>=0?t.push(s):l.warn(`---- 检测到无效字符[encode with code39]: '${i[e]}'`);}e.push("1211212111");for(let s=0;s<i.length;s++)e.push(It[t[s]]);e.push("121121211");const s={data:Y.encode(e.join("")),text:this.options.showStartEndChar?`*${this.text}*`:this.text};return {options:this.options,items:[s],text:this.text}}}class wt extends Dt{constructor(t,e){const i=function(t){const e=[],i=[];let s=0,n=0;for(let r=0,a="",o="";r<t.length;r++)if(a=t[r],n=t.charCodeAt(r),o=Et(a),n>127)l.warn(`---- [ECode39] invalidate char: '${a}'[${n}]`);else {if(s+o.length>85){l.warn(`---- discarded content[${r} --\x3e ${t.length}]: "${t.slice(r)}"`);break}i.push(a),e.push(o),s+=o.length;}return {data:e.join(""),text:i.join("")}}(t);e.text=i.text,super(i.data,e);}valid(){return -1!==this.data.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/)}}class _t extends y{static convertUPCE2UPCA(t){(t=Y.getDigitText(t)).length>7?t=t.substring(0,7):t.length<7&&(t=t.padStart(7,"0"));const e=t.substring(1),i=e[5],s=Array(11).fill("0");switch("1"==t[0]&&(s[0]="1"),s[1]=e[0],s[2]=e[1],i){case "0":case "1":case "2":s[3]=i,s[8]=e[2],s[9]=e[3],s[10]=e[4];break;case "3":s[3]=e[2],s[9]=e[3],s[10]=e[4],"0"!=e[2]&&"1"!=e[2]&&"2"!=e[2]||l.warn("271: Invalid UPC-E data, X3 shall not be equal to 0, 1 or ");break;case "4":s[3]=e[2],s[4]=e[3],s[10]=e[4],"0"==e[3]&&l.warn("272: Invalid UPC-E data, X4 shall not be equal to 0");break;case "5":case "6":case "7":case "8":case "9":s[3]=e[2],s[4]=e[3],s[5]=e[4],s[10]=i,"0"==e[4]&&l.warn("273: Invalid UPC-E data X5 shall not be equal to 0");}return s.join("")}static getUPCECheckCode(t){const e=_t.convertUPCE2UPCA(t);return Y.checkDigit(e,11)}constructor(t,e){(t=Y.getDigitText(t)).length>7?t=t.substring(0,7):t.length<7&&(t=t.padStart(7,"0")),super(t,e);}encode(){let t=this.text;const e=_t.convertUPCE2UPCA(this.text),i=Y.checkDigit(e,11);t+=i;let s="";s="1"==e[0]?tt[R.ctoi(i)]:Q[R.ctoi(i)];const n=[];for(let e=0;e<length;e++)switch(s[e]){case "A":n.push(nt[t.charCodeAt(e)-P.num_0]);break;case "B":n.push(rt[t.charCodeAt(e)-P.num_0]);}const r=[],a=new Y;return r.push({text:"",data:a.expand("111")}),r.push({text:"",data:a.expand(n.join(""))}),r.push({text:"",data:a.expand("111111")}),{options:this.options,items:r,text:t}}}class Ot extends y{constructor(t,e){super(t=Y.getDigitText(t),e);}encode(){let t=this.text,e="";if(t.length<2&&(t=t.padStart(2,"0")),t.length<=2){const i=10*R.ctoi(t[0])+R.ctoi(t[1]);e=et[i%4];}else {t.length<5&&(t=t.padStart(5,"0"));const i=[];for(let e=0;e<5;e++)i[e]=R.ctoi(t[e]);let s=3*(i[0]+i[2]+i[4]);s+=9*(i[1]+i[3]),e=it[s%10];}const i=[];i.push("112");for(let s=0;s<t.length;s++){switch(e[s]){case "A":i.push(nt[t.charCodeAt(s)-P.num_0]);break;case "B":i.push(rt[t.charCodeAt(s)-P.num_0]);}s!=length-1&&i.push("11");}const s=[{text:t,data:Y.encode(i.join(""))}];return {options:this.options,items:s,text:t}}}class xt extends Ot{constructor(t,e){super(t=Y.getDigitText(t),e);}encode(){let t=this.text;t.length>13?t=t.substring(0,13):t.length<12&&(t=t.padStart(12,"0"));const e=Y.checkDigit(t,12);12==t.length?t+=e:e!==t[12]&&(t=t.substring(0,12)+e);const i=st[t.charCodeAt(0)-P.num_0],s=[],n=[];for(let e=1;e<t.length;e++)e>1&&e<7&&"B"==i[e-2]?e<7?s.push(rt[t.charCodeAt(e)-P.num_0]):n.push(rt[t.charCodeAt(e)-P.num_0]):e<7?s.push(nt[t.charCodeAt(e)-P.num_0]):n.push(nt[t.charCodeAt(e)-P.num_0]);const r=this.options.quietZones||0,a=[],o=new Y,h=Array(r>2?r:2).fill("0").join("");return a.push({text:t[0],data:h}),a.push({text:"",data:o.expand("111")}),a.push({text:t.substring(1,7),data:o.expand(s.join(""))}),a.push({text:"",data:o.expand("11111")}),a.push({text:t.substring(7),data:o.expand(n.join(""))}),a.push({text:"",data:o.expand("111")}),a.push({text:this.options.guardWhitespace?" >":"",data:h}),{items:a,text:t,options:this.options}}}class Tt extends xt{static getCheckCode(t,e){let i=0,s=1;const n=e||t.length;for(let e=0;e<n;e++)i+=R.ctoi(t[e])*s,s++;const r=i%11;let a=R.itoc(r);return 10==r&&(a="X"),a}static filterText(t){const e=[];t=t.toUpperCase();for(let i=0;i<t.length&&!(e.length>13);i++)if(R.isDigit(t.charCodeAt(i)))e.push(t[i]);else if("X"===t[i]&&9===e.length&&i===t.length-1){e.push(t[i]);break}return e.join("")}constructor(t,e){if(super(t,e),(t=Tt.filterText(t)).length>13&&(t=t.substring(0,13)),13==t.length){const e=t.substring(0,3);"978"!==e&&"979"!==e&&(t="978"+t.substring(3));const i=Y.checkDigit(t,12);t[12]!=i&&(t=t.substring(0,12)+i);}else t.length>10&&(t=t.substring(0,10)),t.length<9&&(t=t.padStart(9,"0")),t=`978${t.substring(0,9)}`;this.data=this.text=t;}}class St{static registerEncoder(t,e){this.registedEncoderMap.set(t,e);}static getEncoder(t){const e=t.type||b.AUTO,i=t.text||"",s=this.registedEncoderMap.get(e);if(s&&"function"==typeof s.encode)return s;switch(e){case b.UPC_A:return new z(i,t);case b.UPC_E:return new X(i,t);case b.EAN13:return new K(i,t);case b.EAN8:return new G(i,t);case b.CODE39:return new Dt(i,t);case b.ITF25:return new gt(i,t);case b.CODABAR:return new Pt(i,t);case b.CODE93:return new At(i,t);case b.ISBN:return new Tt(i,t);case b.ECODE39:return new wt(i,t);case b.ITF14:return new Ct(i,t);case b.ChinaPost:return new mt(i,t);case b.Matrix25:return new pt(i,t);case b.Industrial25:return new ft(i,t);case b.CODE128:default:return new j(i,t)}}static encode(t){"boolean"!=typeof t.displayValue&&(t.displayValue=true);const e=this.getEncoder(t),i=e.encode(t.text||"",t);return i.data||(i.data=i.items.map(t=>t.data).join("")),i.options||(i.options=e.options),i}}St.registedEncoderMap=new Map;class Mt{static registerBarcodeCreator(t,e){St.registerEncoder(t,e);}static IsProductType(t){switch(t){case b.EAN13:case b.EAN8:case b.UPC_A:case b.UPC_E:case b.ISBN:return true;default:return false}}static create1DBarcode(t){const e=t;let i=b.AUTO;"number"==typeof t.barcodeType?i=t.barcodeType:"number"==typeof e.type&&(i=e.type);let s="number"==typeof t.text?`${t.text}`:(t.text||"").trim();if(s||(s=void 0===t.content||null===t.content?"":String(t.content)),s){s=this.normalize(s,i);try{let e=0;switch(i){case b.EAN13:case b.UPC_A:case b.UPC_E:case b.ISBN:e=Mt.DockHorMargin;}return St.encode({text:s,type:i,quietZones:e,showStartEndChar:t.showStartEnd})}catch(t){return void l.warn(t)}}}static normalize(t,e){if(e===b.CODE39||e===b.CODE93)t=this.normalizeLength(t,107,t=>t>=0&&t<128,"?");else {if(e===b.CODABAR){const e="0123456789-$:/.+ABCD";let i,s;if(t.length>=2){const e="ABCD",n="TN*E";i=t.charAt(0).toUpperCase(),s=t.charAt(t.length-1).toUpperCase();const r=e.indexOf(i)>=0&&e.indexOf(s)>=0,a=n.indexOf(i)>=0&&n.indexOf(s)>=0;r||a?t=t.substring(1,t.length-1):i=s="A";}else i=s="A";return i+(t=this.normalizeLength(t,0,t=>e.indexOf(String.fromCharCode(t))>=0,"0"))+s}if(e===b.EAN13)t=this.normalizeDigitLength(t,12),t+=this.getEAN13CheckCode(t);else if(e===b.EAN8)t=this.normalizeDigitLength(t,7),t+=this.getEAN8CheckCode(t);else if(e===b.UPC_A)t=this.normalizeDigitLength(t,11),t+=Y.checkDigit(t);else if(e===b.UPC_E){const e=(t=this.normalizeDigitLength(t,7)).charAt(0);"0"!==e&&"1"!==e&&(t="0"+t.substring(1)),t+=_t.getUPCECheckCode(t);}else if(e===b.ITF14)t=this.normalizeDigitLength(t,13),t+=this.getITD14CheckCode(t);else {if(e===b.ITF25)return (t=this.normalizeLength(t,80,t=>R.isDigit(t),"0")).length%2!=0?"0"+t:t;if(e===b.GS1_128)if("("===t[0]){if(t.indexOf(")")<0){const e=t.indexOf("]");e>0&&(t=t.substring(0,e)+")"+t.substring(e+1));}}else if("["===t[0]){if(t.indexOf("]")<0){const e=t.indexOf(")");e>0&&(t=t.substring(0,e)+"]"+t.substring(e+1));}}else t.length<2&&(t="0"+t),t=t.length<=20?"(10)"+t:t.length<=30?"(90)"+t:"(91)"+t;else t=this.normalizeLength(t,80,t=>t>=32&&t<=126,"?");}}return t}static normalizeDigitLength(t,e){return (t=this.normalizeLength(t,e,t=>R.isDigit(t),"0")).length<e&&(t=R.preFillChar(t,e,"0")),t}static normalizeLength(t,e,i,s){if(e>0&&t.length>e&&(t=t.substring(0,e)),i&&s){const e=[];for(let n=0;n<t.length;n++)i(t.charCodeAt(n))?e.push(t.charAt(n)):e.push(s);t=e.join("");}return t}static getEAN13CheckCode(t){let e=0,i=0;for(i=0;i<t.length;++i){const s=t.charCodeAt(i)-P.num_0;if(s<0||s>9)throw "检测到非发字符";e+=(1&i?3:1)*s;}return e=10-e%10,10==e&&(e=0),String(e)}static getEAN8CheckCode(t){return Y.checkDigit(t)}static getITD14CheckCode(t){return Y.checkDigit(t)}}var Bt;Mt.DockHorMargin=7,function(t){t[t.Low=0]="Low",t[t.Middle=1]="Middle",t[t.Quality=2]="Quality",t[t.High=3]="High";}(Bt||(Bt={}));const Lt=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];class Nt{static getSymbolSize(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return 4*t+17}static getSymbolTotalCodewords(t){return Lt[t]}static getBCHDigit(t){let e=0;for(;0!==t;)e++,t>>>=1;return e}static calcWaterMarkSeed(t){if("number"==typeof t)return t;if("string"==typeof t){if(!t)return 1024;let e=4660;const i=I.getBytes_Utf8(t);for(let t=0;t<i.length;++t)e+=e>>>5,e+=(255&i[t])*(2&t?5:3),e+=1&t?13:11;return 1025+(1048575&e)}return 0}static hasWaterMarkSeed(t,e,i){if(!e||e.length<3)return false;let s,n;if((255&e[0])>>>4==5)if(9==(15&e[0])){if(e.length<4)return false;if((255&e[1])>>>4!=3)return false;if(13!=(15&e[1]))return false;s=(255&e[2])>>>6&3,n=(63&e[2])<<4|(255&e[3])>>>4;}else {if(3!=(15&e[0]))return false;if((255&e[1])>>>4!=13)return false;s=(255&e[1])>>>2&3,n=(3&e[1])<<8|255&e[2];}else {if((255&e[0])>>>4!=3)return false;if(13!=(15&e[0]))return false;s=(255&e[1])>>>6&3,n=(63&e[1])<<4|(255&e[2])>>>4;}return 1022==n||n==this.calcDtCheckSum(s,i,t)}static calcDtCheckSum(t,e,i){"string"==typeof e&&(e=this.calcWaterMarkSeed(e));let s=this.sDtWaterMarkCheckSums[3&t];if(s=s+e&1048575,i&&i.length>0){const t=I.getBytes_Utf8(i);for(let e=0;e<t.length;++e)s+=s>>>5,s+=(255&t[e])*(2&e?5:3),s+=1&e?13:11;}return s%1019+3}}Nt.sDtWaterMarkCheckSums=[197,257,571,991];class Ut{static getRowColCoords(t){if(1===t)return [];const e=Math.floor(t/7)+2,i=Nt.getSymbolSize(t),s=145===i?26:2*Math.ceil((i-13)/(2*e-2)),n=[i-7];for(let t=1;t<e-1;t++)n[t]=n[t-1]-s;return n.push(6),n.reverse()}static getPositions(t){const e=[],i=Ut.getRowColCoords(t),s=i.length;for(let t=0;t<s;t++)for(let n=0;n<s;n++)0===t&&0===n||0===t&&n===s-1||t===s-1&&0===n||e.push([i[t],i[n]]);return e}}class Ft{constructor(){this.mBuffer=[],this.mLength=0;}get buffer(){return this.mBuffer}get length(){return this.mLength}get(t){const e=Math.floor(t/8);return 1==(this.buffer[e]>>>7-t%8&1)}put(t,e){for(let i=0;i<e;i++)this.putBit(1==(t>>>e-i-1&1));}getLengthInBits(){return this.length}putBit(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.mLength++;}}const $t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],jt=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];class Ht{static getBlocksCount(t,e){switch(e){case Bt.Low:return $t[4*(t-1)+0];case Bt.Middle:return $t[4*(t-1)+1];case Bt.Quality:return $t[4*(t-1)+2];case Bt.High:return $t[4*(t-1)+3];default:return}}static getTotalCodewordsCount(t,e){switch(e){case Bt.Low:return jt[4*(t-1)+0];case Bt.Middle:return jt[4*(t-1)+1];case Bt.Quality:return jt[4*(t-1)+2];case Bt.High:return jt[4*(t-1)+3];default:return}}}const Wt=Nt.getBCHDigit(1335);class kt{static getEccBit(t){switch(t){case Bt.Low:return 1;default:case Bt.Middle:return 0;case Bt.Quality:return 3;case Bt.High:return 2}}static getEncodedBits(t,e){const i=kt.getEccBit(t)<<3|e;let s=i<<10;for(;Nt.getBCHDigit(s)-Wt>=0;)s^=1335<<Nt.getBCHDigit(s)-Wt;return 21522^(i<<10|s)}}class Jt{static isValid(t){return t&&!isNaN(t)&&t>=0&&t<=7}static getPenaltyN1(t){const e=t.cols;let i=0,s=0,n=0,r=null,a=null;for(let o=0;o<e;o++){s=n=0,r=a=null;for(let h=0;h<e;h++){let e=t.get(o,h);e===r?s++:(s>=5&&(i+=s-5+3),r=e,s=1),e=t.get(h,o),e===a?n++:(n>=5&&(i+=n-5+3),a=e,n=1);}s>=5&&(i+=s-5+3),n>=5&&(i+=n-5+3);}return i}static getPenaltyN2(t){const e=t.cols;let i=0;for(let s=0;s<e-1;s++)for(let n=0;n<e-1;n++){const e=t.get(s,n)+t.get(s,n+1)+t.get(s+1,n)+t.get(s+1,n+1);4!==e&&0!==e||i++;}return 3*i}static getPenaltyN3(t){const e=t.cols;let i=0,s=0,n=0;for(let r=0;r<e;r++){s=n=0;for(let a=0;a<e;a++)s=s<<1&2047|t.get(r,a),a>=10&&(1488===s||93===s)&&i++,n=n<<1&2047|t.get(a,r),a>=10&&(1488===n||93===n)&&i++;}return 40*i}static getPenaltyN4(t){let e=0;const i=t.data.length;for(let s=0;s<i;s++)e+=t.data[s];return 10*Math.abs(Math.ceil(100*e/i/5)-10)}static getMaskAt(t,e,i){switch(t){case this.Patterns.PATTERN000:return (e+i)%2==0;case this.Patterns.PATTERN001:return e%2==0;case this.Patterns.PATTERN010:return i%3==0;case this.Patterns.PATTERN011:return (e+i)%3==0;case this.Patterns.PATTERN100:return (Math.floor(e/2)+Math.floor(i/3))%2==0;case this.Patterns.PATTERN101:return e*i%2+e*i%3==0;case this.Patterns.PATTERN110:return (e*i%2+e*i%3)%2==0;case this.Patterns.PATTERN111:return (e*i%3+(e+i)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}}static applyMask(t,e){const i=e.cols;for(let s=0;s<i;s++)for(let n=0;n<i;n++)e.isReserved(n,s)||e.xor(n,s,this.getMaskAt(t,n,s));}static getBestMask(t,e){const i=Object.keys(this.Patterns).length;let s=0,n=1/0;for(let r=0;r<i;r++){e(r),this.applyMask(r,t);const i=this.getPenaltyN1(t)+this.getPenaltyN2(t)+this.getPenaltyN3(t)+this.getPenaltyN4(t);this.applyMask(r,t),i<n&&(n=i,s=r);}return s}}Jt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const Vt="[0-9]+";let Gt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Gt=Gt.replace(/u/g,"\\u");const Kt="(?:(?![A-Z0-9 $%*+\\-./:]|"+Gt+")(?:.|[\r\n]))+",zt=new RegExp("^"+Gt+"$"),Zt=new RegExp("^"+Vt+"$"),qt=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");class Xt{static testKanji(t){return zt.test(t)}static testNumeric(t){return Zt.test(t)}static testAlphanumeric(t){return qt.test(t)}}Xt.KANJI=new RegExp(Gt,"g"),Xt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Xt.BYTE=new RegExp(Kt,"g"),Xt.NUMERIC=new RegExp(Vt,"g"),Xt.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");class Yt{static isValid(t){return !isNaN(t)&&t>=1&&t<=40}}class Qt{static getCharCountIndicator(t,e){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!Yt.isValid(e))throw new Error("Invalid version: "+e);return e>=1&&e<10?t.ccBits[0]:e<27?t.ccBits[1]:t.ccBits[2]}static getBestModeForData(t){return Xt.testNumeric(t)?this.NUMERIC:Xt.testAlphanumeric(t)?this.ALPHANUMERIC:Xt.testKanji(t)?this.KANJI:this.BYTE}static toString(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")}static isValid(t){return "string"!=typeof t&&t&&t.bit&&t.ccBits}static fromString(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case "numeric":return this.NUMERIC;case "alphanumeric":return this.ALPHANUMERIC;case "kanji":return this.KANJI;case "byte":return this.BYTE;default:throw new Error("Unknown mode: "+t)}}static from(t,e){if(this.isValid(t))return t;try{return this.fromString(t)}catch(t){return e}}}Qt.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},Qt.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},Qt.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},Qt.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},Qt.MIXED={id:"",bit:-1,ccBits:[]},Qt.STRUCTURED={id:"Structured",bit:3,ccBits:[0,0,0]};const te=new Uint8Array(512),ee=new Uint8Array(256);!function(){let t=1;for(let e=0;e<255;e++)te[e]=t,ee[t]=e,t<<=1,256&t&&(t^=285);for(let t=255;t<512;t++)te[t]=te[t-255];}();class ie{static log(t){if(t<1)throw new Error("log("+t+")");return ee[t]}static exp(t){return te[t]}static mul(t,e){return 0===t||0===e?0:te[ee[t]+ee[e]]}}class se{static mul(t,e){const i=new Uint8Array(t.length+e.length-1);for(let s=0;s<t.length;s++)for(let n=0;n<e.length;n++)i[s+n]^=ie.mul(t[s],e[n]);return i}static mod(t,e){let i=new Uint8Array(t);for(;i.length-e.length>=0;){const t=i[0];for(let s=0;s<e.length;s++)i[s]^=ie.mul(e[s],t);let s=0;for(;s<i.length&&0===i[s];)s++;i=i.slice(s);}return i}static generateECPolynomial(t){let e=new Uint8Array([1]);for(let i=0;i<t;i++)e=this.mul(e,new Uint8Array([1,ie.exp(i)]));return e}}class ne{constructor(t){this.degree=t,this.degree&&this.initialize(this.degree);}initialize(t){this.degree=t,this.genPoly=se.generateECPolynomial(this.degree);}encode(t){if(!this.genPoly)throw new Error("Encoder not initialized");const e=new Uint8Array(t.length+this.degree);e.set(t);const i=se.mod(e,this.genPoly),s=this.degree-i.length;if(s>0){const t=new Uint8Array(this.degree);return t.set(i,s),t}return i}}const re="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".split("");class ae{get mode(){return this.mMode}get data(){return this.mData}constructor(t,e){this.mMode=t,this.mData=e||"";}getLength(){return this.mData.length}getBitsLength(){return 0}write(t){}}class oe extends ae{constructor(t){super(Qt.ALPHANUMERIC,t);}static getBitsLength(t){return 11*Math.floor(t/2)+t%2*6}getBitsLength(){return oe.getBitsLength(this.mData.length)}write(t){let e;for(e=0;e+2<=this.mData.length;e+=2){let i=45*re.indexOf(this.mData[e]);i+=re.indexOf(this.mData[e+1]),t.put(i,11);}this.mData.length%2&&t.put(re.indexOf(this.mData[e]),6);}}class he extends ae{constructor(t){super(Qt.NUMERIC,t);}static getBitsLength(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)}getBitsLength(){return he.getBitsLength(this.getLength())}write(t){let e,i,s;for(e=0;e+3<=this.mData.length;e+=3)i=this.mData.substr(e,3),s=parseInt(i,10),t.put(s,10);const n=this.mData.length-e;n>0&&(i=this.mData.substr(e),s=parseInt(i,10),t.put(s,3*n+1));}}class ce extends ae{constructor(t){super(Qt.BYTE,t),this.bytes=I.getBytes_Utf8(t);}static getBitsLength(t){return 8*t}getLength(){return this.bytes.length}getBitsLength(){return 8*this.bytes.length}write(t){for(let e=0,i=this.bytes.length;e<i;e++)t.put(this.bytes[e],8);}}class de extends ae{constructor(t){super(Qt.KANJI,t);}static getBitsLength(t){return 13*t}getBitsLength(){return de.getBitsLength(this.getLength())}write(t){let e;for(e=0;e<this.mData.length;e++){let i=Nt.toSJISFunction?Nt.toSJISFunction(this.mData[e]):this.mData.charCodeAt(e);if(i>=33088&&i<=40956)i-=33088;else {if(!(i>=57408&&i<=60351))throw new Error("Invalid SJIS character: "+this.mData[e]+"\nMake sure your charset is UTF-8");i-=49472;}i=192*(i>>>8&255)+(255&i),t.put(i,13);}}}const ue={queue:[],sorter:null,make:function(t){const e=ue,i={};t=t||{};for(const t in e)e.hasOwnProperty(t)&&(i[t]=e[t]);return i.queue=[],i.sorter=t.sorter||e.default_sorter,i},default_sorter:(t,e)=>t.cost-e.cost,push(t,e){this.queue.push({value:t,cost:e}),this.queue.sort(this.sorter);},pop(){return this.queue.shift()},empty(){return 0===this.queue.length}},le={single_source_shortest_paths:function(t,e,i){const s={},n={};n[e]=0;const r=le.PriorityQueue.make();let a,o,h,c,d,u,l,g,p;for(r.push(e,0);!r.empty();)for(h in a=r.pop(),o=null==a?void 0:a.value,c=null==a?void 0:a.cost,d=t[o]||{},d)d.hasOwnProperty(h)&&(u=d[h],l=c+u,g=n[h],p=void 0===n[h],(p||g>l)&&(n[h]=l,r.push(h,l),s[h]=o));if(void 0!==i&&void 0===n[i]){const t=["Could not find a path from ",e," to ",i,"."].join("");throw new Error(t)}return s},extract_shortest_path_from_predecessor_list:function(t,e){const i=[];let s=e;for(;s;)i.push(s),t[s],s=t[s];return i.reverse(),i},find_path:function(t,e,i){const s=le.single_source_shortest_paths(t,e,i);return le.extract_shortest_path_from_predecessor_list(s,i)},PriorityQueue:ue};class ge{static getStringByteLength(t){return unescape(encodeURIComponent(t)).length}static getSegments(t,e,i){const s=[];let n;for(;n=t.exec(i);)s.push({data:n[0],index:n.index,mode:e,length:n[0].length});return s}static getSegmentsFromString(t){const e=this.getSegments(Xt.NUMERIC,Qt.NUMERIC,t),i=this.getSegments(Xt.ALPHANUMERIC,Qt.ALPHANUMERIC,t);let s,n;return "function"==typeof Nt.toSJISFunction?(s=this.getSegments(Xt.BYTE,Qt.BYTE,t),n=this.getSegments(Xt.KANJI,Qt.KANJI,t)):(s=this.getSegments(Xt.BYTE_KANJI,Qt.BYTE,t),n=[]),e.concat(i,s,n).sort(function(t,e){return t.index-e.index}).map(function(t){return {data:t.data,mode:t.mode,length:t.length,index:0}})}static getSegmentBitsLength(t,e){switch(e){case Qt.NUMERIC:return he.getBitsLength(t);case Qt.ALPHANUMERIC:return oe.getBitsLength(t);case Qt.KANJI:return de.getBitsLength(t);case Qt.BYTE:default:return ce.getBitsLength(t)}}static mergeSegments(t){return t.reduce(function(t,e){const i=t.length-1>=0?t[t.length-1]:null;return i&&i.mode===e.mode?(t[t.length-1].data+=e.data,t):(t.push(e),t)},[])}static buildNodes(t){const e=[];for(let i=0;i<t.length;i++){const s=t[i];switch(s.mode){case Qt.NUMERIC:e.push([s,{data:s.data,mode:Qt.ALPHANUMERIC,length:s.length},{data:s.data,mode:Qt.BYTE,length:s.length}]);break;case Qt.ALPHANUMERIC:e.push([s,{data:s.data,mode:Qt.BYTE,length:s.length}]);break;case Qt.KANJI:e.push([s,{data:s.data,mode:Qt.BYTE,length:this.getStringByteLength(s.data)}]);break;case Qt.BYTE:e.push([{data:s.data,mode:Qt.BYTE,length:this.getStringByteLength(s.data)}]);}}return e}static buildGraph(t,e){const i={},s={start:{}};let n=["start"];for(let r=0;r<t.length;r++){const a=t[r],o=[];for(let t=0;t<a.length;t++){const h=a[t],c=""+r+t;o.push(c),i[c]={node:h,lastCount:0},s[c]={};for(let t=0;t<n.length;t++){const r=n[t];i[r]&&i[r].node.mode===h.mode?(s[r][c]=this.getSegmentBitsLength(i[r].lastCount+h.length,h.mode)-this.getSegmentBitsLength(i[r].lastCount,h.mode),i[r].lastCount+=h.length):(i[r]&&(i[r].lastCount=h.length),s[r][c]=this.getSegmentBitsLength(h.length,h.mode)+4+Qt.getCharCountIndicator(h.mode,e));}}n=o;}for(let t=0;t<n.length;t++)s[n[t]].end=0;return {map:s,table:i}}static buildSingleSegment(t,e){let i;const s=Qt.getBestModeForData(t);if(i=Qt.from(e||"",s),!i||i!==Qt.BYTE&&(null==i?void 0:i.bit)<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+Qt.toString(i)+".\n Suggested mode is: "+Qt.toString(s));switch(i===Qt.KANJI&&"function"!=typeof Nt.toSJISFunction&&(i=Qt.BYTE),i){case Qt.NUMERIC:return new he(t);case Qt.ALPHANUMERIC:return new oe(t);case Qt.KANJI:return new de(t);case Qt.BYTE:return new ce(t)}}static fromArray(t){return t.reduce((t,e)=>{if("string"==typeof e){const i=ge.buildSingleSegment(e);i&&t.push(i);}else if(e.data){const i=ge.buildSingleSegment(e.data,e.mode);i&&t.push(i);}return t},[])}static fromString(t,e){const i=this.getSegmentsFromString(t),s=this.buildNodes(i),n=this.buildGraph(s,e),r=le.find_path(n.map,"start","end"),a=[];for(let t=1;t<r.length-1;t++)a.push(n.table[r[t]].node);return this.fromArray(this.mergeSegments(a))}static rawSplit(t){return this.fromArray(this.getSegmentsFromString(t))}}const pe=Nt.getBCHDigit(7973);class fe{static getBestVersionForDataLength(t,e,i){for(let s=1;s<=40;s++)if(e<=this.getCapacity(s,i,t))return s}static getReservedBitsCount(t,e){return Qt.getCharCountIndicator(t,e)+4}static getTotalBitsFromDataArray(t,e){let i=0;return t.forEach(function(t){const s=fe.getReservedBitsCount(t.mode,e);i+=s+t.getBitsLength();}),i}static getBestVersionForMixedData(t,e,i){const s=t&&t.length>0?t.length:0;for(let t=1;t<=40;t++)if(this.getTotalBitsFromDataArray(e,t)+s<=this.getCapacity(t,i,Qt.MIXED))return t}static isValid(t){return !isNaN(t)&&t>=1&&t<=40}static getCapacity(t,e,i){if(!fe.isValid(t))throw new Error("Invalid QR Code version");void 0===i&&(i=Qt.BYTE);const s=8*(Nt.getSymbolTotalCodewords(t)-(Ht.getTotalCodewordsCount(t,e)||0));if(i===Qt.MIXED)return s;const n=s-this.getReservedBitsCount(i,t);switch(i){case Qt.NUMERIC:return Math.floor(n/10*3);case Qt.ALPHANUMERIC:return Math.floor(n/11*2);case Qt.KANJI:return Math.floor(n/13);case Qt.BYTE:default:return Math.floor(n/8)}}static getBestVersionForData(t,e,i){let s;if(Array.isArray(e)){if(e.length>1)return this.getBestVersionForMixedData(t,e,i);if(0===e.length)return 1;s=e[0];}else s=e;const n=t?Math.ceil(t.length/8):0;return this.getBestVersionForDataLength(s.mode,s.getLength()+n,i)}static getEncodedBits(t){if(!fe.isValid(t)||t<7)throw new Error("Invalid QR Code version");let e=t<<12;for(;Nt.getBCHDigit(e)-pe>=0;)e^=7973<<Nt.getBCHDigit(e)-pe;return t<<12|e}}class me{static getPositions(t){const e=Nt.getSymbolSize(t);return [[0,0],[e-7,0],[0,e-7]]}}class Ce{static setupFinderPattern(t,e){const i=t.cols,s=me.getPositions(e);for(let e=0;e<s.length;e++){const n=s[e][0],r=s[e][1];for(let e=-1;e<=7;e++)if(!(n+e<=-1||i<=n+e))for(let s=-1;s<=7;s++)r+s<=-1||i<=r+s||(e>=0&&e<=6&&(0===s||6===s)||s>=0&&s<=6&&(0===e||6===e)||e>=2&&e<=4&&s>=2&&s<=4?t.set(n+e,r+s,true,true):t.set(n+e,r+s,false,true));}}static setupTimingPattern(t){const e=t.cols;for(let i=8;i<e-8;i++){const e=i%2==0;t.set(i,6,e,true),t.set(6,i,e,true);}}static setupAlignmentPattern(t,e){const i=Ut.getPositions(e);for(let e=0;e<i.length;e++){const s=i[e][0],n=i[e][1];for(let e=-2;e<=2;e++)for(let i=-2;i<=2;i++) -2===e||2===e||-2===i||2===i||0===e&&0===i?t.set(s+e,n+i,true,true):t.set(s+e,n+i,false,true);}}static setupVersionInfo(t,e){const i=t.cols,s=fe.getEncodedBits(e);let n,r,a;for(let e=0;e<18;e++)n=Math.floor(e/3),r=e%3+i-8-3,a=1==(s>>e&1),t.set(n,r,a,true),t.set(r,n,a,true);}static setupFormatInfo(t,e,i){const s=t.cols,n=kt.getEncodedBits(e,i);let r=false;for(let e=0;e<15;e++)r=1==(n>>e&1),e<6?t.set(e,8,r,true):e<8?t.set(e+1,8,r,true):t.set(s-15+e,8,r,true),e<8?t.set(8,s-e-1,r,true):e<9?t.set(8,15-e-1+1,r,true):t.set(8,15-e-1,r,true);t.set(s-8,8,1,true);}static setupData(t,e){const i=t.cols;let s=-1,n=i-1,r=7,a=0;for(let o=i-1;o>0;o-=2)for(6===o&&o--;;){for(let i=0;i<2;i++)if(!t.isReserved(n,o-i)){let s=false;a<e.length&&(s=1==(e[a]>>>r&1)),t.set(n,o-i,s),r--,-1===r&&(a++,r=7);}if(n+=s,n<0||i<=n){n-=s,s=-s;break}}}static createData(t,e,i,s){i||(i=new Ft),s.forEach(function(e){i.put(e.mode.bit,4),i.put(e.getLength(),Qt.getCharCountIndicator(e.mode,t)),e.write(i);});const n=8*(Nt.getSymbolTotalCodewords(t)-(Ht.getTotalCodewordsCount(t,e)||0));for(i.getLengthInBits()+4<=n&&i.put(0,4);i.getLengthInBits()%8!=0;)i.putBit(0);const r=(n-i.getLengthInBits())/8;for(let t=0;t<r;t++)i.put(t%2?17:236,8);return this.createCodewords(i,t,e)}static createCodewords(t,e,i){const s=Nt.getSymbolTotalCodewords(e),n=Ht.getTotalCodewordsCount(e,i);if(!n)return;const r=s-n,a=Ht.getBlocksCount(e,i);if(!a)return;const o=a-s%a,h=Math.floor(s/a),c=Math.floor(r/a),d=c+1,u=h-c,l=new ne(u);let g=0;const p=new Array(a),f=new Array(a);let m=0;const C=new Uint8Array(t.buffer);for(let t=0;t<a;t++){const e=t<o?c:d;p[t]=C.slice(g,g+e),f[t]=l.encode(p[t]),g+=e,m=Math.max(m,e);}const P=new Uint8Array(s);let R,I,b=0;for(R=0;R<m;R++)for(I=0;I<a;I++)R<p[I].length&&(P[b++]=p[I][R]);for(R=0;R<u;R++)for(I=0;I<a;I++)P[b++]=f[I][R];return P}static create(t){let e=null===t.text||void 0===t.text?t.content:t.text;if(null==e||""===e)return;e=String(e);const i="number"==typeof t.eccLevel?t.eccLevel:Bt.Middle;let s="number"==typeof t.version?t.version:0,n="number"==typeof t.qrMask?t.qrMask:0;"function"==typeof t.toSJISFunc&&(Nt.toSJISFunction=t.toSJISFunc);const r=new Ft;let a="number"==typeof t.waterMarkMode?t.waterMarkMode:4;if(t.waterMarkSeed&&a>=0){a=a>3?3&Date.now():a;const i=this.getWaterSeedCheckSum(e,a,t.waterMarkSeed);this.appendDtWaterMark(a,i,r);}let o=s;if(s<=0){const t=ge.rawSplit(e);o=fe.getBestVersionForData(r,t,i)||0;}const h=ge.fromString(e,o||40),c=fe.getBestVersionForData(r,h,i);if(!c)throw new Error("The amount of data is too big to be stored in a QR Code");if(s<=0)s=c;else if(s<c)throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: "+c+".\n");const d=this.createData(s,i,r,h);if(!d)return;const u=Nt.getSymbolSize(s),l=new C(u,u);return this.setupFinderPattern(l,s),this.setupTimingPattern(l),this.setupAlignmentPattern(l,s),this.setupFormatInfo(l,i,0),s>=7&&this.setupVersionInfo(l,s),this.setupData(l,d),n<=0&&(n=Jt.getBestMask(l,this.setupFormatInfo.bind(null,l,i))),Jt.applyMask(n,l),this.setupFormatInfo(l,i,n),l}static getWaterSeedCheckSum(t,e,i){const s=3&e;let n=this.sDtWaterMarkCheckSums[s];n=n+(i=Nt.calcWaterMarkSeed(i))&1048575;const r=I.getBytes_Utf8(t);for(let t=0;t<r.length;++t)n+=n>>>5,n+=(255&r[t])*(2&t?5:3),n+=1&t?13:11;return n=n%1019+3,n}static appendDtWaterMark(t,e,i){e=53248|(3&t)<<10|1023&e,this.appendStructuredAppend(e>>>8,255&e,i);}static appendStructuredAppend(t,e,i){this.appendModeInfo(Qt.STRUCTURED,i),i.put(t,8),i.put(e,8);}static appendModeInfo(t,e){e.put(t.bit,4);}}Ce.sDtWaterMarkCheckSums=[197,257,571,991];const Pe=Object.freeze({Auto:"auto",QRCode:"qrcode",PDF417:"pdf417",DMCode:"dataMatrix",GMCode:"gridMatrix"});class Re{static getEncoder(t){if(!t)return;t=t.toUpperCase();const e=this.barcodeCreatorMap[t];return l.log(`---- getBarcode2DEncoder[${t}]: ${!!e}`),e}static setEncoder(t,e){return !(!t||!e||"function"!=typeof e.encode||(t=t.toUpperCase(),l.log(`---- setBarcode2DEncoder[${t}]:`),this.barcodeCreatorMap[t]=e,0))}static checkAndRegisterEncodeModule(t){if(!t||!window)return;const e=window;let i;if((t=t.toUpperCase())===Pe.PDF417.toUpperCase()?i=e.DzPdf417:t===Pe.DMCode.toUpperCase()?i=e.DzDataMatrix:t===Pe.GMCode.toUpperCase()&&(i=e.DzGridMatrix),i){if("function"==typeof i.getInstance){const e=i.getInstance();return this.setEncoder(t,e),e}return "function"==typeof i.register?(i.register(this.getInstance()),this.getEncoder(t)):void 0}}static getInstance(){return this._instance||(this._instance=new Re)}static createQRCode(t){return Ce.create(t)}static create2DBarcode(t){const e=t.barcodeType||t.type;let i;return e&&(i=this.getEncoder(e),i||(i=this.checkAndRegisterEncodeModule(e))),null!==t.text&&void 0!==t.text||(t.text=t.content),i?i.encode(t):Ce.create(t)}static createPDF417(t){return t.barcodeType||(t.barcodeType=Pe.PDF417),this.create2DBarcode(t)}static createDataMatrix(t){return t.barcodeType||(t.barcodeType=Pe.DMCode),this.create2DBarcode(t)}static createGridMatrix(t){return t.barcodeType||(t.barcodeType=Pe.GMCode),this.create2DBarcode(t)}static drawQrcode(t,e){const i=Ce.create(Object.assign(Object.assign({},e),{eccLevel:Bt.Middle})),s=e.width||t.width;if(i){const e=new p({canvas:t});e.startJob({width:s}),e.draw2DBarcode({data:i,width:s});}}register(t){return !!t&&Re.setEncoder(t.barcodeType,t)}}Re.barcodeCreatorMap={};class Ie{constructor(t,e,i){if(this.contentLeft="",this._currValue=0,this.currLength=0,this.contentRight="",this.degreeOffset=0,this.maxDegreeValue=0,!t)return;e=e||1,i=i||0;let s=-1,n=-1;for(n=t.length-1;n>=0&&!R.isDigit(t.charCodeAt(n));n--);if(!(n<0)){for(s=n-1;s>=0&&R.isDigit(t.charCodeAt(s))&&!(n-s>=Ie.MaxDegreeLength);s--);s++,this._currValue=parseInt(t.substring(s,n+1)),this.maxDegreeValue=Number.MAX_VALUE,this.contentLeft=t.substring(0,s),this.contentRight=t.substring(n+1),this.currLength=i>0?i:n-s+1,this.degreeOffset=e||0;}}get IsValid(){return 0!=this.degreeOffset}get CurrValue(){return this._currValue}set CurrValue(t){t>Ie.MaxDegreeValue?this._currValue=Ie.MaxDegreeValue:this._currValue=t<0?0:t;}step(t){return this.CurrValue+=this.degreeOffset*t,this.toString()}get ShownDegree(){if(this.IsValid){let t=this.CurrValue||0;const e=t<0?"-":"";t=Math.abs(t);const i=t.toFixed();return `${e}${i.length<this.currLength?R.repeatChar("0",this.currLength-i.length):""}${i}`}return ""}toString(){return this.IsValid?this.contentLeft+this.ShownDegree+this.contentRight:""}}Ie.MaxDegreeLength=15,Ie.MaxDegreeValue=Math.pow(10,Ie.MaxDegreeLength)-1,Ie.MaxDegreeOffset=Math.pow(10,Ie.MaxDegreeLength-1);class be{static imageToCanvas(t){const e=t.image;if(e)try{let i=t.width||0,s=t.height||0;i>0&&s>0||(i>0?s=i*e.height/e.width:s>0?i=e.width*s/e.height:(i=e.width,s=e.height));const n=document.createElement("canvas");n.width=i,n.height=s;const r=n.getContext("2d");if(r)return r.drawImage(e,0,0,i,s),n}catch(t){l.warn("【DzImageData】createCanvasWithImage.error: ",t);}}static getImageDataFromImage(t){const e=this.imageToCanvas(t),i=null==e?void 0:e.getContext("2d");if(e&&i)return i.getImageData(0,0,e.width,e.height)}static loopImagePixels(t,e){if(t){const i=t.data;for(let t=0,s=[];t<i.length;t+=4)s=e(i[t],i[t+1],i[t+2],i[0]),s&&s.length>0&&(s.length<=1&&(s=[s[0],s[0],s[0]]),i[t]=s[0],i[t+1]=s[1],i[t+2]=s[2],s.length>3&&(i[t+3]=s[3]));}return t}static setRGB(t,e,i){e<t.length&&(i.length>=3?(t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],i.length>3&&(t[e+3]=i[3])):i.length>0&&(t[e]=t[e+1]=t[e+2]=i[0]));}static toGray(t,e,i){return 19661*t+38666*e+7209*i>>16&255}static resetPixelAtIndex(t,e,i){if(!t||t.length<=e)return false;if(t[e]<5||t[e]>250)return false;const s=Math.round(i),n=t[e]+s&255;return t[e]=t[e+1]=t[e+2]=n,true}static toHalfTone_Floyd(t,e,i){const s=t.width,n=t.height,r=t.data,a=4*s,o=.0625,h=this.parseRgba(i||"");for(let t=0;t<n;++t)for(let i=0;i<s;++i){const c=t*a+4*i,d=r[c],u=d>=e?255:0,l=d-u;i<s-1&&this.resetPixelAtIndex(r,4*(i+1)+t*a,7*l*o),i>=1&&t<n-1&&this.resetPixelAtIndex(r,4*(i-1)+(t+1)*a,3*l*o),t<n-1&&this.resetPixelAtIndex(r,4*i+(t+1)*a,5*l*o),i<s-1&&t<n-1&&this.resetPixelAtIndex(r,4*(i+1)+(t+1)*a,1*l*o),this.setRGB(r,c,u>0||h.length<=0?[u]:h);}}static toHalfTone_Burkers(t,e,i){const s=t.width,n=t.height,r=t.data,a=4*s,o=.03125,h=this.parseRgba(i||"");for(let t=0;t<n;++t)for(let i=0;i<s;++i){const c=t*a+4*i,d=r[c],u=d>=e?255:0,l=d-u;i<s-1&&this.resetPixelAtIndex(r,4*(i+1)+t*a,8*l*o),i<s-2&&this.resetPixelAtIndex(r,4*(i+2)+t*a,4*l*o),i>=2&&t<n-1&&this.resetPixelAtIndex(r,4*(i-2)+(t+1)*a,2*l*o),i>=1&&t<n-1&&this.resetPixelAtIndex(r,4*(i-1)+(t+1)*a,4*l*o),t<n-1&&this.resetPixelAtIndex(r,4*i+(t+1)*a,8*l*o),i<s-1&&t<n-1&&this.resetPixelAtIndex(r,4*(i+1)+(t+1)*a,4*l*o),i<s-2&&t<n-1&&this.resetPixelAtIndex(r,4*(i+2)+(t+1)*a,2*l*o),this.setRGB(r,c,u>0||h.length<=0?[u]:h);}}static toHalfTone_Sierra(t,e,i){const s=t.width,n=t.height,r=t.data,a=4*s,o=1/32,h=this.parseRgba(i||"");for(let t=0;t<n;++t)for(let i=0;i<s;++i){const c=t*a+4*i,d=r[c],u=d>=e?255:0,l=d-u;i<s-1&&this.resetPixelAtIndex(r,c+4,5*l*o),i<s-2&&this.resetPixelAtIndex(r,c+8,3*l*o),i>=2&&t<n-1&&this.resetPixelAtIndex(r,c+a-8,2*l*o),i>=1&&t<n-1&&this.resetPixelAtIndex(r,c+a-4,4*l*o),t<n-1&&this.resetPixelAtIndex(r,c+a,5*l*o),i<s-1&&t<n-1&&this.resetPixelAtIndex(r,c+a+4,4*l*o),i<s-2&&t<n-1&&this.resetPixelAtIndex(r,c+a+8,2*l*o),i>=1&&t<n-2&&this.resetPixelAtIndex(r,c+2*a-4,2*l*o),t<n-2&&this.resetPixelAtIndex(r,c+2*a,3*l*o),i<s-1&&t<n-2&&this.resetPixelAtIndex(r,c+2*a+4,2*l*o),this.setRGB(r,c,u>0||h.length<=0?[u]:h);}}static toHalfTone_Stucki(t,e,i){const s=t.width,n=t.height,r=t.data,a=4*s,o=.0238095238095238,h=this.parseRgba(i||"");for(let t=0;t<n;++t)for(let i=0;i<s;++i){const c=t*a+4*i,d=r[c],u=d>=e?255:0,l=d-u;i<s-1&&this.resetPixelAtIndex(r,4*(i+1)+t*a,7*l*o),i<s-2&&this.resetPixelAtIndex(r,4*(i+2)+t*a,5*l*o),i>=2&&t<n-1&&this.resetPixelAtIndex(r,4*(i-2)+(t+1)*a,3*l*o),i>=1&&t<n-1&&this.resetPixelAtIndex(r,4*(i-1)+(t+1)*a,5*l*o),t<n-1&&this.resetPixelAtIndex(r,4*i+(t+1)*a,7*l*o),i<s-1&&t<n-1&&this.resetPixelAtIndex(r,4*(i+1)+(t+1)*a,5*l*o),i<s-2&&t<n-1&&this.resetPixelAtIndex(r,4*(i+2)+(t+1)*a,3*l*o),i>=2&&t<n-2&&this.resetPixelAtIndex(r,4*(i-2)+(t+2)*a,1*l*o),i>=1&&t<n-2&&this.resetPixelAtIndex(r,4*(i-1)+(t+2)*a,3*l*o),t<n-2&&this.resetPixelAtIndex(r,4*i+(t+2)*a,5*l*o),i<s-1&&t<n-2&&this.resetPixelAtIndex(r,4*(i+1)+(t+2)*a,3*l*o),i<s-2&&t<n-2&&this.resetPixelAtIndex(r,4*(i+2)+(t+2)*a,1*l*o),this.setRGB(r,c,u>0||h.length<=0?[u]:h);}}static toHalfTone_Jarvis(t,e,i){const s=t.width,n=t.height,r=t.data,a=4*s,o=.0208333333333333,h=this.parseRgba(i||"");for(let t=0;t<n;++t)for(let i=0;i<s;++i){const c=t*a+4*i,d=r[c],u=d>=e?255:0,l=d-u;i<s-1&&this.resetPixelAtIndex(r,4*(i+1)+t*a,7*l*o),i<s-2&&this.resetPixelAtIndex(r,4*(i+2)+t*a,5*l*o),i>=2&&t<n-1&&this.resetPixelAtIndex(r,4*(i-2)+(t+1)*a,3*l*o),i>=1&&t<n-1&&this.resetPixelAtIndex(r,4*(i-1)+(t+1)*a,5*l*o),t<n-1&&this.resetPixelAtIndex(r,4*i+(t+1)*a,7*l*o),i<s-1&&t<n-1&&this.resetPixelAtIndex(r,4*(i+1)+(t+1)*a,5*l*o),i<s-2&&t<n-1&&this.resetPixelAtIndex(r,4*(i+2)+(t+1)*a,3*l*o),i>=2&&t<n-2&&this.resetPixelAtIndex(r,4*(i-2)+(t+2)*a,1*l*o),i>=1&&t<n-2&&this.resetPixelAtIndex(r,4*(i-1)+(t+2)*a,3*l*o),t<n-2&&this.resetPixelAtIndex(r,4*i+(t+2)*a,5*l*o),i<s-1&&t<n-2&&this.resetPixelAtIndex(r,4*(i+1)+(t+2)*a,3*l*o),i<s-2&&t<n-2&&this.resetPixelAtIndex(r,4*i+2+(t+2)*a,1*l*o),this.setRGB(r,c,u>0||h.length<=0?[u]:h);}}static processHalftoneImage(t,e,i,s){const n=e||150;if(t)switch(this.processGrayImage(t),i){case 1:be.toHalfTone_Floyd(t,n,s);break;case 2:be.toHalfTone_Burkers(t,n,s);break;case 4:be.toHalfTone_Stucki(t,n,s);break;case 5:be.toHalfTone_Jarvis(t,n,s);break;default:be.toHalfTone_Sierra(t,n,s);}return t}static parseRgba(t,e){if(!t)return "number"==typeof e?[e,e,e]:[];const i=[];if("#"===t[0]&&(t=t.substring(1)),/^\[0-9a-fA-F]{3,4}$/.test(t))i.push(parseInt(t[0],16)),i.push(parseInt(t[1],16)),i.push(parseInt(t[2],16)),t.length>3&&i.push(parseInt(t[3],16));else {if(!/^([0-9A-Fa-f]{2}){3,4}$/.test(t))return "number"==typeof e?[e,e,e]:[];i.push(parseInt(t.substring(0,2),16)),i.push(parseInt(t.substring(2,4),16)),i.push(parseInt(t.substring(4,6),16)),t.length>6&&i.push(parseInt(t.substring(6,8),16));}return i}static processBlackWhiteImage(t,e,i){if(!(t&&t.data&&t.width&&t.height))return t;const s=e||150,n=this.parseRgba(i||"",0);return this.loopImagePixels(t,(t,e,i)=>Math.round(.3*t+.59*e+.11*i)<=s?n:[255,255,255])}static processGrayImage(t){return t&&t.data&&t.width&&t.height?this.loopImagePixels(t,(t,e,i)=>{const s=Math.round(.3*t+.59*e+.11*i);return [s,s,s]}):t}static imageProcess(t){const e=t.data;return e?t.colorMode===be.COLOR_MODE_GRAY?be.processGrayImage(e):t.colorMode===be.COLOR_MODE_BLACK_WHITE?be.processBlackWhiteImage(e,t.threshold,t.color):t.colorMode===be.COLOR_MODE_HALFTONE?be.processHalftoneImage(e,t.threshold,t.halftoneMode,t.color):void 0:e}}be.COLOR_MODE_GRAY=1,be.COLOR_MODE_BLACK_WHITE=2,be.COLOR_MODE_HALFTONE=3;class ye{get Text(){return this.text}constructor(){this.keyGroup=[],this.text="";}setKeyWordAction(t){this.keyWordAction=t;}setKeys(t){if(!t)return;t=t.replace(/\\n/g,"\n"),this.text=t;const e=[];let i=0;for(let s=0,n=0,r=false;s<t.length;s++){const a=t.charAt(s);"["===a?(r=true,n=s):"]"===a&&r&&(r=false,e.push({text:t.substring(i,n)}),e.push({text:t.substring(n+1,s),isKey:true}),i=s+1);}i<t.length&&e.push({text:t.substr(i),isKey:e.length<1}),this.keyGroup=e;}hasKeyWord(){return !!this.keyGroup.find(t=>t.isKey)}toString(t){const e=[];let i=false;if(!this.keyWordAction)return t||this.text;for(const t of this.keyGroup)if(t.isKey){const s=this.keyWordAction(t.text);void 0!==s&&(e.push(s||""),i=true);}else e.push(t.text);return !i&&t?t:e.join("")}}const ve=Object.freeze({text:"text",barcode:"barcode",qrcode:"qrcode",pdf417:"pdf417",dataMatrix:"dataMatrix",data_matrix:"datamatrix",gridMatrix:"gridMatrix",grid_matrix:"gridmatrix",image:"image",rect:"rect",rectangle:"rectangle",ellipse:"ellipse",circle:"circle",line:"line",table:"table",arcText:"arcText",arc_text:"arctext",html:"html"});var Ae,Ee,De,we,_e,Oe;!function(t){t.JOB_NAME_TRANS="#!#transparent#!#",t.JOB_NAME_PREV="#!#preview#!#",t.JOB_NAME_DATA="#!#rawdata#!#",t.JOB_NAME_DATA_IMAGE="#!#imagedata#!#";}(Ae||(Ae={}));class xe{static Pix2MM(t,e){return 25.4*t/e}static MM2Pix(t,e){return t*e/25.4}static isPreviewJobName(t){return !!t&&((t=t.toLowerCase()).startsWith(Ae.JOB_NAME_PREV.substring(0,7))||t.startsWith(Ae.JOB_NAME_TRANS.substring(0,8)))}static isTransPrevJob(t){return !!t&&t.toLowerCase().startsWith(Ae.JOB_NAME_TRANS.substring(0,8))}static isWhitePrevJob(t){return !!t&&t.toLowerCase().startsWith(Ae.JOB_NAME_PREV.substring(0,7))}static calcPageHeight(t,e){return ("number"!=typeof e||e<=0)&&(e=0),t.reduce((t,e)=>{const i=(e.y||0)+(e.height||e.fontHeight||0);return i>t?i:t},0)+(e>0?e:2)}static getJobStartOptions(t,i){const s=i||{};let n="number"==typeof s.printerDPI?s.printerDPI:t.printerDpi;"number"!=typeof n&&("number"==typeof t.dpi&&t.dpi>0?n=t.dpi:"number"==typeof t.printerDPI&&t.printerDPI>0&&(n=t.printerDPI));const r="number"==typeof s.printerWidth?s.printerWidth:t.printerWidth;return Object.assign(Object.assign({},t),{dpi:n,printerDpi:n,printerWidth:r,svgViewBox:"string"==typeof t.svgViewBox?e.parseRect(t.svgViewBox):t.svgViewBox,color:t.drawColor})}static loadImageSrc(t){l.log("#### 【DrawContext.loadImage】src:");const e="string"==typeof t?t:t.src;return l.log(e.length>100?e.substring(0,100)+"...":e),new Promise(t=>{try{if(e){const i=new Image;i.crossOrigin="anonymous",i.src=e,i.onload=()=>{t(i);},i.onerror=e=>{l.warn(e),t(null);};}else l.warn("【DrawContext.CreateImage: src不能为空!"),t(null);}catch(e){l.warn(e,"####【DrawContext.loadImage.catch】 图片加载异常,error:"),t(null);}})}static html2ImageSrc(t){return t?`data:image/svg+xml,\n<svg xmlns='http://www.w3.org/2000/svg'>\n<foreignObject width='100%' height='100%'>\n<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>${t}</div>\n</foreignObject>\n</svg>`:t}static html2Image(t){const e=xe.html2ImageSrc(t);return xe.loadImageSrc(e)}static loadSvgContent(t){const e=new Blob([t],{type:"image/svg+xml"});return new Promise(i=>{const s=new FileReader;s.onload=t=>{var e;i(null===(e=t.target)||void 0===e?void 0:e.result);},s.onerror=e=>{l.warn(e,`---- failed to load svg: '${t.substring(0,50)}...'`),i(void 0);},s.readAsDataURL(e);})}static getMargins(t){const e="number"==typeof t.margin&&t.margin>=0?t.margin:0,i="number"==typeof t.marginH&&t.marginH>=0?t.marginH:e,s="number"==typeof t.marginV&&t.marginV>=0?t.marginV:e,n=[];return n[0]="number"==typeof t.marginTop?t.marginTop:s,n[1]="number"==typeof t.marginRight?t.marginRight:i,n[2]="number"==typeof t.marginBottom?t.marginBottom:s,n[3]="number"==typeof t.marginLeft?t.marginLeft:i,n}get Context(){return this.cvs.Base.Context}get CanvasElement(){return this.cvs.Base.Canvas}get Canvas(){return this.cvs}get Dpi(){return this.cvs.Dpi}set Dpi(t){this.cvs.Dpi=t;}get JobInfo(){return this.jobOptions}get isPrintJob(){return !!this.jobOptions&&!this.jobOptions.isPreview}get isPreviewJob(){return !!this.jobOptions&&!!this.jobOptions.isPreview}get Width(){return this.jobWidth}get Height(){return this.jobHeight}get Orientation(){return this.jobOrientation||0}get JobName(){var t;return null===(t=this.jobOptions)||void 0===t?void 0:t.jobName}get ZoomRate(){return this.Canvas.DPM}set ZoomRate(t){t<this.mMinZoomRate&&(t=this.mMinZoomRate),t>this.mMaxZoomRate&&(t=this.mMaxZoomRate);const e=this.Canvas.DPM;t!==e&&(this.Canvas.DPM=t,this.CanvasElement.style&&(this.CanvasElement.style.borderRadius=.5*t+"px"),this.onZoomRateChanged(t,e));}get PixWidth(){return this.Canvas.DPM*this.Width}get PixHeight(){return this.Canvas.DPM*this.Height}get Foreground(){return this.Canvas.Foreground}set Foreground(t){(t||"").match(/^([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/)&&(t=`#${t}`),this.Canvas.Foreground=t;}get Background(){return this.cvs.Base.Background}get IsApiMode(){return this._apiMode||false}set IsApiMode(t){this._apiMode=t;}get instanceId(){return this.mInstanceId}constructor(t){this.jobWidth=0,this.jobHeight=0,this.jobOrientation=0,this.mMinZoomRate=.5,this.mMaxZoomRate=40;const i=t||{};this.mInstanceId=e.getRandomStr(),i.creator||(i.creator=()=>this.createCanvas()),"function"!=typeof i.onCanvasClear&&(i.onCanvasClear=(t,e)=>{this.onCanvasClear(t,e);}),i.apiMode&&(i.willReadFrequently=true,this._apiMode=true),this.cvs=new f(i),this.mKeyWordParser=new ye;}onZoomRateChanged(t,e){}createCanvas(){try{return null===document||void 0===document?void 0:document.createElement("canvas")}catch(t){return void l.warn("---- exception of document.createElement: ",t)}}onCanvasClear(t,e){}loadImage(t){return xe.loadImageSrc(t)}loadHtml(t){const e=xe.html2ImageSrc(t);return this.loadImage(e)}setMaxZoomRate(t){t>0&&(this.mMaxZoomRate=t);}setMinZoomRate(t){t>0&&(this.mMinZoomRate=t);}setOffset(t,e){switch(this.Orientation){case 1:case 90:this.Canvas.OffsetX=e,this.Canvas.OffsetY=-t;break;case 2:case 180:this.Canvas.OffsetX=-t,this.Canvas.OffsetY=-e;break;case 3:case 270:this.Canvas.OffsetX=-e,this.Canvas.OffsetY=t;break;default:this.Canvas.OffsetX=t,this.Canvas.OffsetY=e;}}save(){this.Canvas.Base.Context.save();}restore(){this.Canvas.Base.Context.restore();}setItemOrientation(t){return this.Canvas.Base.ItemOrientation=t,true}setItemHorizontalAlignment(t){return this.Canvas.Base.HorizontalAlign=t,true}setItemVerticalAlignment(t){return this.Canvas.Base.VerticalAlign=t,true}setFontName(t){this.Canvas.setFontName(t);}getFontHeight(){return this.Canvas.getFontHeight()}setFontHeight(t){this.Canvas.setFontHeight(t);}setLineWidth(t){this.Canvas.setLineWidth(t);}setLineSpace(t){return this.Canvas.setLineSpace(t),true}parseLineSpace(t,e){return this.Canvas.parseLineSpace(t,e)}setCharSpace(t){return this.Canvas.setCharSpace(t),true}setAutoTextLine(t){this.Canvas.Base.AutoReturn=t;}setRotation(t,e,i){return this.Canvas.setRotation(t>3?t:90*t,e,i),true}setBorderAlign(t){this.Canvas.Base.BorderAlign=t;}resetCanvas(t={}){const e=t.jobWidth||0,i=t.jobHeight||0;e>0&&this.Canvas.startJob({width:e,height:i>0?i:e});}resetJobInfo(t){"number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=0),"number"!=typeof t.dpi&&(t.dpi=t.printerDpi),"number"!=typeof t.dpi&&(t.dpi=0),"number"!=typeof t.printerWidth&&(t.printerWidth=0),this.jobOptions=t,this.jobWidth=t.width>0?t.width:0,this.jobWidth<=0&&t.dpi>0&&t.printerWidth>0&&(this.jobWidth=t.printerWidth/t.dpi*25.4),this.jobHeight=t.height>0?t.height:t.width,this.jobOrientation=t.orientation||0,this.Canvas.Base.ItemOrientation=0,this.Canvas.Base.HorizontalAlign=0,this.Canvas.Base.VerticalAlign=0;}pound2mm(t){return 25.4*t/72}mm2pound(t){return 72*t/25.4}mm2pix(t,e){return t/25.4*(e||this.Dpi)}pix2mm(t,e){return t/(e||this.Dpi)*25.4}isPreviewMode(t,e){return "boolean"==typeof t.printMode?!t.printMode:"boolean"==typeof t.isPreview?t.isPreview:"boolean"==typeof t.preview?t.preview:"boolean"==typeof t.previewMode?t.previewMode:this.IsApiMode&&t.jobName?xe.isPreviewJobName(t.jobName):"boolean"==typeof e?e:!this.IsApiMode}startJob(t){if((t=t||{}).width||(t.width=t.jobWidth||t.labelWidth),t.height||(t.height=t.jobHeight||t.labelHeight),"number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=0),"number"!=typeof t.printerWidth&&(t.printerWidth=0),"0"===t.drawColor&&delete t.drawColor,!(t.width<=0&&t.printerWidth<=0))return !t.backgroundImage&&t.background&&(t.backgroundImage=t.background,delete t.background),!t.borderImage&&t.border&&(t.borderImage=t.border,delete t.border),"boolean"!=typeof t.isPreview&&(t.isPreview=this.isPreviewMode(t)),t.printMode=!t.isPreview,t.isPreview&&(t.backgroundColor||(xe.isTransPrevJob(t.jobName)?t.backgroundColor=xe.JOB_COLOR_TRANS:t.backgroundColor=xe.JOB_COLOR_WHITE),t.color||(t.color=t.drawColor||p.COLOR_FG_DEFAULT)),this.resetJobInfo(Object.assign({},t)),this.Canvas.startJob(t)?(t.borderImage&&("string"==typeof t.borderImage?this.drawImage({image:t.borderImage,width:t.width,height:t.height}):this.drawBorderImage({image:t.borderImage,svgElement:t.svgElement,borderScale:t.borderScale,tileMode:!t.svgElement,svgWidth:t.svgWidth,svgHeight:t.svgHeight,svgViewBox:t.svgViewBox})),t.watermark&&t.isPreview&&"string"==typeof t.watermark&&this.drawWatermark({text:t.watermark}),t):void 0}endJob(){const t=this.jobOptions;if(!t)return;const e=this.Canvas.commitJob();if(!e)return;const i=Object.assign(Object.assign({},t),{apiMode:this.IsApiMode});return this.IsApiMode&&(t.isPreview?(i.dataUrl=e.Canvas.toDataURL(),i.imageData=t.withImageData?e.getImageData():void 0):(t.antiColor&&this.Canvas.inverseColors(),t.horizontalFlip&&this.Canvas.horizontalFlip(),"boolean"!=typeof t.withDataUrl&&"boolean"==typeof t.withPreview&&(t.withDataUrl=t.withPreview),i.imageData=e.getImageData(),i.dataUrl=t.withDataUrl?e.Canvas.toDataURL():"")),i}commitJob(){return Promise.resolve(this.endJob())}drawWatermark(t){const e=this.jobOptions;if(e){const i=t.width||e.width||0,s=t.height||e.height||0;this.drawText(Object.assign(Object.assign({},t),{width:i,height:s,fontHeight:e.watermarkFontHeight||.25*Math.min(i,s),rotation:"number"==typeof e.watermarkRotation?e.watermarkRotate:-45,color:e.watermarkColor||"#d0d0d0",horizontalAlignment:"number"==typeof t.horizontalAlignment?t.horizontalAlignment:1,verticalAlignment:"number"==typeof t.verticalAlignment?t.verticalAlignment:1}));}}drawLine(t){return "number"!=typeof t.lineWidth&&(t.lineWidth=xe.LINE_WIDTH_MM),this.Canvas.drawLine(t)}drawLines(t,e,i,s,n,r,a){r=r||[],a=a||[];let o=0;this.drawLine({x1:t,y1:e,x2:i,y2:s,lineWidth:n});for(let a=0;a<r.length;a++)o+=r[a],this.drawLine({x1:t,y1:e+o,x2:i,y2:s+o,lineWidth:n});o=0;for(let r=0;r<a.length;r++)o+=a[r],this.drawLine({x1:t+o,y1:e,x2:i+o,y2:s,lineWidth:n});}drawRect(t){return t.fill||"number"==typeof t.lineWidth||(t.lineWidth=xe.LINE_WIDTH_MM),this.Canvas.drawRect(t)}drawRectangle(t){return this.drawRect(t)}fillRect(t){return this.Canvas.drawRect(Object.assign(Object.assign({},t),{fill:true}))}drawRoundRect(t){t.fill||"number"==typeof t.lineWidth||(t.lineWidth=xe.LINE_WIDTH_MM),this.Canvas.drawRoundRect(t);}drawEllipse(t){return t.fill||"number"==typeof t.lineWidth||(t.lineWidth=xe.LINE_WIDTH_MM),this.Canvas.drawEllipse(t)}drawCircle(t){return t.fill||"number"==typeof t.lineWidth||(t.lineWidth=xe.LINE_WIDTH_MM),this.Canvas.drawCircle(t)}getMineFontHeight(t){let e=xe.FONT_SIZE_MIN_DEFAULT;return t.minFontHeight&&t.minFontHeight>0?e=t.minFontHeight:t.minFontSize&&t.minFontSize>0&&(e=t.minFontSize),e}drawText(t){!t.fontHeight&&t.fontSize&&(t.fontHeight=this.pound2mm(t.fontSize));const e=this.getMineFontHeight(t);return t.fontHeight||(t.fontHeight=this.Canvas.getFontHeight()),t.fontHeight<e&&(t.fontHeight=e),"string"==typeof t.lineSpace&&t.lineSpace&&/^\d*\.?\d*$/.test(t.lineSpace)&&(t.lineSpace=parseFloat(t.lineSpace)),this.Canvas.drawText(t)}drawArcText(t){return !t.fontHeight&&t.fontSize&&(t.fontHeight=this.pound2mm(t.fontSize)),this.Canvas.drawArcText(t)}splitText(t){return this.Canvas.splitText(t)}measureText(t){const e=this.Canvas.splitText(t);if(e.length<=0)return {textArray:[],width:0,height:0};const i=t.fontHeight||this.Canvas.getFontHeight(),s=p.getLineHeight(i),n=t.lineSpace?this.Canvas.parseLineSpace(t.lineSpace,t.fontHeight||t.height):0;let r=0;for(const i of e){const e=this.Canvas.measureText(Object.assign(Object.assign({},t),{text:i}));e.width&&e.width>r&&(r=e.width);}return {textArray:e,lineHeight:s,lineSpace:n,width:this.Canvas.invertCvt(r),height:e.length*(s+n)-n}}measureFontSize(t){const e=this.getMineFontHeight(t);return t.fontHeight||(t.fontHeight=this.Canvas.getFontHeight()),t.fontHeight<e&&(t.fontHeight=e),this.Canvas.measureFontSize(t)}draw1DMatrix(t){return !!t.datas&&this.Canvas.draw1DBarcode(t)}drawBarcode(t){return "string"==typeof t.barcodeType&&t.barcodeType?this.draw2DBarcode(t):this.draw1DBarcode(t)}draw1DBarcode(t){const e=Mt.create1DBarcode(t);return t.barcodeType===b.ISBN&&(t.textFlag=2),!!e&&this.draw1DMatrix(Object.assign(t,{datas:e.items}))}draw2DBarcode(t){const e=Re.create2DBarcode(t);return !!e&&this.draw2DMatrix(Object.assign(Object.assign({},t),{data:e}))}draw2DMatrix(t){return !!t.data&&this.Canvas.draw2DBarcode(t)}drawQRCode(t){if("number"==typeof t.barcodeType&&(1===t.barcodeType?t.barcodeType=Pe.PDF417:2===t.barcodeType?t.barcodeType=Pe.DMCode:3===t.barcodeType&&(t.barcodeType=Pe.GMCode)),t.barcodeType===Pe.PDF417)return this.drawPDF417(t);if(t.barcodeType===Pe.DMCode)return this.drawDataMatrix(t);if(t.barcodeType===Pe.GMCode)return this.drawGridMatrix(t);"number"==typeof t.mask&&(t.qrMask=t.mask),"number"==typeof t.mode&&(t.qrMode=t.mode);const e=Re.create2DBarcode(t);return !!e&&this.draw2DMatrix(Object.assign(Object.assign({},t),{data:e,margin:"number"==typeof t.margin?t.margin:void 0}))}draw2DQRCode(t){return this.drawQRCode(t)}drawPDF417(t){"number"==typeof t.pdf417EccLevel&&(t.eccLevel=t.pdf417EccLevel),"number"==typeof t.pdf417Cols&&(t.cols=t.pdf417Cols),"number"!=typeof t.aspectRatio&&t.width&&t.height&&(t.aspectRatio=t.width/t.height);const e=Re.createPDF417(t);return !!e&&this.draw2DMatrix(Object.assign(Object.assign({},t),{data:e,margin:"number"==typeof t.margin?t.margin:void 0}))}draw2DPdf417(t){return this.drawPDF417(t)}drawDataMatrix(t){"number"==typeof t.dmCodeShape&&(t.codeShape=t.dmCodeShape),"number"!=typeof t.aspectRatio&&t.width&&t.height&&(t.aspectRatio=t.width/t.height);const e=Re.createDataMatrix(t);return !!e&&this.draw2DMatrix(Object.assign(Object.assign({},t),{data:e,margin:"number"==typeof t.margin?t.margin:void 0}))}draw2DDataMatrix(t){return this.drawDataMatrix(t)}drawGridMatrix(t){const e=Re.createGridMatrix(t);return !!e&&this.draw2DMatrix(Object.assign(Object.assign({},t),{data:e,margin:"number"==typeof t.margin?t.margin:void 0}))}draw2DGridMatrix(t){return this.drawGridMatrix(t)}drawImage(t){const e=t;if(e.image||(e.img?(e.image=e.img,delete e.img):e.imageSrc?(e.image=e.imageSrc,delete e.imageSrc):e.imageFile&&(e.image=e.imageFile,delete e.imageFile)),e.image){const t=e.image;return t.dzSrc&&(e.image=t.dzSrc),this.Canvas.drawImage(e)}return false}drawImageResizeLabel(t){return this.Canvas.drawImageResizeLabel(t)}putImageData(t){return this.Canvas.putImageData(t)}drawBorderImage(t){const e=t.image;if(!e||"string"==typeof e)return;const i=t.svgElement,s="boolean"==typeof t.svgMode?t.svgMode:!!i;let n=e.width||t.imageWidth||0,r=e.height||t.imageHeight||0;if(i){l.log("---- SVG 图片适配:");const i=t.svgViewBox,s=t.svgWidth,a=t.svgHeight,o=this.Canvas.CanvasWidth,h=this.Canvas.CanvasHeight;if(s&&s>0||a&&a>0)n||(n=s||a||0),r||(r=a||s||0);else {let t=n,s=r;i&&(t=i.width,s=i.height),t&&s?t/s>o/h?(n=o,r=o*s/t):(r=h,n=t*h/s):n=r=Math.min(o,h),"string"!=typeof e&&(e.width=n,e.height=r);}}if(!n||!r)return void l.warn("---- drawBorderImage.fail: [无法获取图片大小]!");const a=n/3,o=r/3;this.Canvas.drawImageResizeLabel({img:e.dzSrc||e,left:a,top:o,right:e.width-a,bottom:e.height-o,tileMode:!s&&t.tileMode,relativeScale:s?t.borderScale||1:void 0,imageWidth:n,imageHeight:r});}drawItem(t,e,i){const s=t,n=this.JobInfo;if(n){if("boolean"!=typeof t.printable&&"boolean"==typeof t.printing&&(t.printable=t.printing),!n.isPreview&&"boolean"==typeof t.printable&&!t.printable)return;t.color&&!n.isPreview&&(t.color=void 0);}const r="string"==typeof s.layerClass?s.layerClass:"";let a="string"==typeof t.type&&t.type?t.type:r;a=a?a.toLowerCase():ve.text;const o="number"==typeof s.contentType?s.contentType:e?2:0;if(2===o&&e){let t;!s.columnName&&s.dataColumnName&&(s.columnName=s.dataColumnName),s.columnName?(this.mKeyWordParser.setKeys(s.columnName),t=this.mKeyWordParser.hasKeyWord()?this.mKeyWordParser.toString(s.text):e[s.columnName]):s.text&&s.text.indexOf("[")>=0&&(this.mKeyWordParser.setKeys(s.text),this.mKeyWordParser.hasKeyWord()&&(t=this.mKeyWordParser.toString(s.text))),void 0!==t&&(s.text=t);}else if(1===o&&i&&i>0){const e=t;e.rawText||(e.rawText=e.text);const s=e.rawText||"",n=new Ie(s,e.degreeOffset,e.degreeLength);n.IsValid&&(e.text=n.step(i));}switch("number"==typeof s.horAlignment&&"number"!=typeof s.horizontalAlignment&&(t.horizontalAlignment=s.horAlignment),"number"==typeof s.verAlignment&&"number"!=typeof s.verticalAlignment&&(t.verticalAlignment=s.verAlignment),"boolean"==typeof s.filled&&"boolean"!=typeof s.fill&&(s.fill=s.filled),a){case ve.text:return this.drawText(t);case ve.barcode:return this.draw1DBarcode(t);case ve.qrcode:return this.drawQRCode(t);case ve.pdf417:return this.drawPDF417(t);case ve.data_matrix:return this.drawDataMatrix(t);case ve.grid_matrix:return this.drawGridMatrix(t);case ve.image:return this.drawImage(t);case ve.rect:case ve.rectangle:return this.drawRect(t);case ve.ellipse:return this.drawEllipse(t);case ve.circle:return this.drawCircle(t);case ve.arc_text:return this.drawArcText(t);case ve.line:return this.drawLine(t);case ve.table:return this.drawTable(t,e,i);default:return l.warn(`---- 不支持的 DrawType: ${t.type}`),false}}static getUnionRectOfRelateRect(t,i,s){for(const n of i)n!==t?e.hasIntersection(t,n)&&(s&&s.push(n),t=e.getUnionRect(t,n)):s&&s.push(n);return t}static shrinkCellContent(t,e){return {x:t.x+e,y:t.y+e,width:t.width-2*e,height:t.height-2*e}}drawTableWithoutRotation(t,i,s){!t.tableRows&&Array.isArray(t.rows)&&(t.tableRows=t.rows);const n=t,r=t.width||0,a=t.height||0,o=t.tableRows||[];if(r<=0||a<=0||o.length<=0)return false;"number"!=typeof t.lineWidth&&(t.lineWidth=xe.LINE_WIDTH_MM);const h=t.lineWidth>0?t.lineWidth:0,c=t.cellPadding||0,d=.5*h,u="number"==typeof t.horizontalAlignment?t.horizontalAlignment:1,l="number"==typeof t.verticalAlignment?t.verticalAlignment:1,g=t.x||0,p=t.y||0;let f="number"==typeof t.rowCount&&t.rowCount>0?t.rowCount:0,m="number"==typeof t.columnCount&&t.columnCount>0?t.columnCount:0;f<=0&&(f="number"==typeof t.rows&&t.rows>0?t.rows:o.length),m<=0&&(m="number"==typeof t.columns&&t.columns>0?t.columns:o.reduce((t,e)=>e&&e.length>t?e.length:t,0));let C=Array(m).fill(0);t.columnWidths&&t.columnWidths.length>1?C=t.columnWidths:("string"==typeof n.colWidth&&n.colWidth&&(n.colWidth=n.colWidth.split(",")),Array.isArray(n.colWidth)&&n.colWidth.length>1&&(C=n.colWidth.map(t=>t?Number(t):0))),C.length>m?C=C.slice(0,m):C.length<m&&(C=C.concat(Array(m-C.length).fill(0))),C=C.map(t=>t>0?t:0);const P=C.filter(t=>t>1).reduce((t,e)=>t+e,0),R=C.filter(t=>t>0&&t<=1),I=C.filter(t=>t<=0);let b=R.reduce((t,e)=>t+e,0);if(I.length>0)if(b>=1){const t=R[R.length-1];b+=t*I.length,C.forEach((t,e)=>{t<=0&&(C[e]=R[R.length-1]);});}else {const t=(1-b)/I.length;b=1,C.forEach((e,i)=>{e<=0&&(C[i]=t);});}b>0?C=C.map(t=>t>1?t:(r-P)/b*t):P!==r&&(C=C.map(t=>t/P*r));let y=Array(f).fill(.5);t.rowHeights&&t.rowHeights.length>1?y=t.rowHeights:("string"==typeof n.rowHeight&&n.rowHeight&&(n.rowHeight=n.rowHeight.split(",")),Array.isArray(n.rowHeight)&&n.rowHeight.length>1&&(y=n.rowHeight.map(t=>t?Number(t):0))),y.length>f?y=y.slice(0,f):y.length<f&&(y=y.concat(Array(f-y.length).fill(y[y.length-1]))),y=y.map(t=>t>0?t:.5);const v=y.filter(t=>t>1).reduce((t,e)=>t+e,0),A=y.filter(t=>t<=1).reduce((t,e)=>t+e,0);A>0?y=y.map(t=>t>1?t:(a-v)/A*t):v!==a&&(y=y.map(t=>t/v*a));let E=t.groups||[];if("string"==typeof n.group&&(E=n.group.split(";").map(t=>{const e=t.split(",").map(t=>t[0]>="0"&&t[0]<="9"?Number(t):0);return e.length>3?{x:e.length>1?e[1]-1:0,y:e.length>0?e[0]-1:0,width:e.length>3?e[3]-e[1]+1:0,height:e.length>2?e[2]-e[0]+1:0}:void 0}).filter(t=>!!t)),o.forEach((t,e)=>{for(let i=0;i<m;i++){const s=t[i];if("object"==typeof s){const t=s.rowSpan||0,n=s.columnSpan||s.colSpan||0;(t>1||n>1)&&E.push({x:i,y:e,width:n>1?n:1,height:t>1?t:1});}}}),E.length>1){const t=E.slice(0);E.splice(0);const e=[];for(const i of t){if(e.indexOf(i)>=0)continue;const s=xe.getUnionRectOfRelateRect(i,t,e);E.push(s);}}h>0&&this.drawRect({x:t.x,y:t.y,width:t.width,height:t.height,lineWidth:h});for(let n=0,r=0;n<f;r+=y[n],n++){const a=o[n]||[];for(let o=0,P=0;o<m;P+=C[o],o++){const R={x:o,y:n,width:1,height:1},I=E.filter(t=>e.isInnerRect(R,t)).shift();if(I){if(R.x!==I.x||R.y!==I.y)continue;R.width=I.width,R.height=I.height;}const b=(t,e)=>(t||0)+e,v={x:g+P,y:p+r,width:R.width>0?C.slice(R.x,R.x+R.width).reduce(b,0):C[R.x],height:R.height>0?y.slice(R.y,R.y+R.height).reduce(b,0):y[R.y]};R.x>0&&h>0&&this.drawLine({x1:v.x,x2:v.x,y1:v.y+(R.y<=0?d:0),y2:v.y+v.height-(R.y+R.height>=f?d:0),lineWidth:h}),R.y>0&&h>0&&this.drawLine({x1:v.x+(R.x<1?d:0),x2:v.x+v.width-(R.x+R.width>=m?d:0),y1:v.y,y2:v.y,lineWidth:h});const A=a[o];let D=0;if(void 0!==A){let e=A;if("object"!=typeof A&&(e={type:ve.text,text:A}),"string"!=typeof e.type||!e.type){let t="string"==typeof e.layerClass?e.layerClass:"";t?(t=t.toLowerCase(),"barcode"!==t&&"qrcode"!==t||"number"==typeof e.type&&(e.barcodeType=e.type),"barcode"===t&&c<=0&&(D=h),e.type=t):e.type=ve.text;}const n=e;"number"!=typeof n.horizontalAlignment&&(n.horizontalAlignment="number"==typeof n.horAlignment?n.horAlignment:u),"number"!=typeof n.verticalAlignment&&(n.verticalAlignment="number"==typeof n.verAlignment?n.verAlignment:l);let r=d+c+D;if(e.type===ve.text){const i=e;i.fontHeight||(i.fontHeight=t.fontHeight||.3*v.height),!i.fontName&&t.fontName&&(i.fontName=t.fontName),"number"!=typeof i.fontStyle&&"number"==typeof t.fontStyle&&(i.fontStyle=t.fontStyle),c<=0&&(r=d+1);}else e.type===ve.qrcode&&c<=0&&(r=d+1);this.drawItem(Object.assign(e,xe.shrinkCellContent(v,r)),i,s);}}}return true}drawTable(t,e,i){let s=t.x||0,n=t.y||0,r=t.width||0,a=t.height||0;if(!this.jobOptions)return false;let o=Array.isArray(t.margin)?t.margin[0]:t.margin,h=Array.isArray(t.margin)?t.margin[1]:o;if(r<=0){const e=this.jobWidth;o="number"==typeof o&&o>=0?o:.05*e,s=t.x="number"==typeof t.x?t.x:o,r=t.width=e-s-o;}if(a<=0){const e=this.jobHeight;h="number"==typeof h&&h>=0?h:.05*e,n=t.y="number"==typeof t.y?t.y:h,a=t.height=e-n-h;}const c=t,d=t.columnWidths||[],u=t.columnCount||t.columns||c.cols||d.length||0;if(c.Cells&&Array.isArray(c.Cells)&&!t.cells&&(t.cells=c.Cells,delete c.Cells),!t.tableRows)if(Array.isArray(t.rows))t.tableRows=t.rows;else if(t.cells&&u>0){t.tableRows=[];for(let e=0;e<t.cells.length;e+=u)t.tableRows.push(t.cells.slice(e,e+u));}if(!t.tableRows||t.tableRows.length<=0)return false;t.fontSize&&!t.fontHeight&&(t.fontHeight=this.pound2mm(t.fontSize));const l="number"==typeof t.rotation?t.rotation:t.orientation;this.save(),this.setRotation(l||0,{x:s,y:n},{width:r,height:a});const g=this.drawTableWithoutRotation(t,e,i);return this.restore(),g}printPageGroup(t,e){const i=t.jobPages||[],s=t.jobArguments||[],n={printCopies:1,copyIndex:0,printPages:1,pageIndex:0},r=t.jobInfo||{},a=t.printerInfo||{},o=xe.getJobStartOptions(r,a),h=r.jobHeight||0,c=xe.getMargins(r);let d=0;const u=r.startPage&&r.startPage>0?r.startPage:0,l=r.printPages||0;if(s.length>0||l>1&&i.length<=1){const t=s.length>0?s.length:u+l;let r=t;l>0&&(r=u+l>t?t:u+l),h<=0&&(o.height=xe.calcPageHeight(i[0],c[2]));for(let t=u;t<r;t++){const a=s[t];if(n.printPages=r,n.pageIndex=t,!this.startJob(Object.assign({},o)))break;this.mKeyWordParser.setKeyWordAction(t=>a[t]);for(const e of i[0])this.drawItem(e,a,t);const h=this.endJob();if(!h)break;const c=e(Object.assign(h,n));if("number"==typeof c&&(d=c),d>0)break;d<0&&t--;}}else {let t=i.length;l>0&&(t=u+l>i.length?i.length:u+l);for(let s=u;s<t;s++){n.printPages=t,n.pageIndex=s,h<=0&&(o.height=xe.calcPageHeight(i[s],c[2]));const r=i[s];if(!this.startJob(Object.assign({},o)))break;for(const t of r)this.drawItem(t);const a=this.endJob();if(!a)break;const u=e(Object.assign(a,n));if("number"==typeof u&&(d=u),d>0)break;d<0&&s--;}}return d}printAsyncPageGroup(t,e){return m(this,0,void 0,function*(){const i=t.jobPages||[],s=t.jobArguments||[],n={printCopies:1,copyIndex:0,printPages:1,pageIndex:0},r=t.jobInfo||{},a=t.printerInfo||{},o=xe.getJobStartOptions(r,a),h=r.jobHeight||0,c=xe.getMargins(r);let d=0,u=r.startPage&&r.startPage>0?r.startPage:0;const l=r.printPages||0;if(s.length>0||l>1&&i.length<=1){const t=s.length>0?s.length:u+l;let r=t;l>0&&(r=u+l>t?t:u+l),u>=r&&(u=r-1),h<=0&&(o.height=xe.calcPageHeight(i[0],c[2]));for(let t=u;t<r;t++){const a=s[t];if(n.printPages=r,n.pageIndex=t,n.isEndPage=t+1>=r,!this.startJob(Object.assign({},o)))break;this.mKeyWordParser.setKeyWordAction(t=>a[t]);for(const e of i[0])this.drawItem(e,a,t);const h=yield this.commitJob();if(!h)break;const c=yield e(Object.assign(h,n));if("number"==typeof c&&(d=c),d>0)break;d<0&&t--;}}else {let t=i.length;l>0?t=u+l>i.length?i.length:u+l:i.length<=1&&u>0&&(u=0);for(let s=u;s<t;s++){n.printPages=i.length,n.pageIndex=s,n.isEndPage=s+1>=i.length,h<=0&&(o.height=xe.calcPageHeight(i[s],c[2]));const t=i[s];if(!this.startJob(Object.assign({},o)))break;for(const e of t)this.drawItem(e);const r=yield this.commitJob();if(!r)break;const a=yield e(Object.assign(r,n));if("number"==typeof a&&(d=a),d>0)break;d<0&&s--;}}return d})}drawJob(t){l.log("#### drawJob:"),t.jobPages||(t.jobPages=[]);const e=t.jobInfo||{},i=e.startCopy||0,s=e.remainCopies||0;let n=0;if(t.jobPages.length<=0&&t.jobPage&&t.jobPages.push(t.jobPage),t.jobPages.length<=0)return n=1,n;const r=e.printCopies&&e.printCopies>0?e.printCopies:1;if(r>1&&e.autoPage){for(let e=0;e<r&&(n=this.printPageGroup(t,n=>t.onPageComplete?(n.printCopies=r+i+s,n.copyIndex=e+i,n.isEndCopy=e+1>=r,t.onPageComplete(n)||0):0),0===n);e++);return n}return this.printPageGroup(t,e=>(t.onPageComplete&&(n=t.onPageComplete(Object.assign(Object.assign({},e),{printCopies:r+i+s,copyIndex:i,isEndCopy:true}))||0),n))}drawAsyncJob(t){return m(this,0,void 0,function*(){l.info("#### drawAsyncJob:"),t.jobPages||(t.jobPages=[]);const e=t.jobInfo||{},i=e.startCopy||0,s=e.remainCopies||0;let n=0;if(t.jobPages.length<=0&&t.jobPage&&t.jobPages.push(t.jobPage),t.jobPages.length<=0)return n=1,n;const r=e.printCopies&&e.printCopies>0?e.printCopies:1;if(r>1&&e.autoPage){for(let e=0;e<r&&(n=yield this.printAsyncPageGroup(t,n=>{var a;return t.onPageComplete?(n.printCopies=r+i+s,n.copyIndex=e+i,n.isEndCopy=e+1>=r,Promise.resolve(null!==(a=t.onPageComplete(n))&&void 0!==a?a:0)):Promise.resolve(0)}),0===n);e++);return n}return yield this.printAsyncPageGroup(t,e=>t.onPageComplete?Promise.resolve(t.onPageComplete(Object.assign(Object.assign({},e),{printCopies:r+i+s,copyIndex:i,isEndCopy:true}))||0):Promise.resolve(0))})}autoLoadDrawItemImage(t,e){return m(this,0,void 0,function*(){if(t.type===ve.image){const i=!this.isPreviewMode(e),s=t;if(s&&"string"==typeof s.image){s.image=yield this.loadImage(s.image).catch(t=>(l.warn("---- 图片加载异常!",t),s.image));try{const t=s.image,n=s.color||e.color||e.drawColor,r=s.colorMode||0;if(t instanceof HTMLImageElement&&r>0&&r<=3){const e=s.width||0,a=s.height||0;let o=0,h=0;e>0&&a>0?(e/a>t.width/t.height?"number"==typeof s.horizontalAlignment&&s.alignment!==s.horizontalAlignment&&(s.alignment=s.horizontalAlignment):"number"==typeof s.verticalAlignment&&s.alignment!==s.verticalAlignment&&(s.alignment=s.verticalAlignment),3===s.alignment?(o=e,h=a):e/a>t.width/t.height?(o=t.width*a/t.height,h=a):(o=e,h=e*t.height/t.width)):e>0?(o=e,h=e*t.height/t.width):a>0&&(o=t.width*a/t.height,h=a);const c=be.imageToCanvas({image:t,width:o?this.mm2pix(o):void 0,height:h?this.mm2pix(h):void 0});if(c){const t=c.getContext("2d");let e=null==t?void 0:t.getImageData(0,0,c.width,c.height);if(e&&(e=be.imageProcess({data:e,colorMode:r,threshold:s.threshold,halftoneMode:s.halftoneMode,color:i?"":n})),e&&t){t.putImageData(e,0,0);const i=c.toDataURL();s.image=yield this.loadImage(i);}}}}catch(t){return l.warn("代码异常!",t),false}}}else if(t.type===ve.html){const e=t;"string"!=typeof e.html&&e.html&&(e.html=e.html.innerHTML),e.image=yield this.loadHtml(e.html);}else if(t.type===ve.table){const i=t;if(i.tableRows)for(const t of i.tableRows)for(const i of t||[])i&&"string"!=typeof i&&i.type&&(yield this.autoLoadDrawItemImage(i,e));else if(i.cells)for(const t of i.cells)t&&"string"!=typeof t&&t.type&&(yield this.autoLoadDrawItemImage(t,e));}return true})}autoLoadImage(t){return m(this,0,void 0,function*(){const e=t.jobInfo||{};if(t.jobInfo){const i=this.isPreviewMode(t.jobInfo);!e.backgroundImage&&e.background&&(e.backgroundImage=e.background),e.background&&delete e.background,i?e.backgroundImage&&"string"==typeof e.backgroundImage?e.backgroundImage=yield this.loadImage(e.backgroundImage):e.background&&"string"==typeof e.background&&(e.background=yield this.loadImage(e.background)):(e.backgroundImage=void 0,e.background=void 0),e.borderImage&&"string"==typeof e.borderImage?e.borderImage=yield this.loadImage({src:e.borderImage,withSize:true}):e.border&&"string"==typeof e.border&&(e.border=yield this.loadImage({src:e.border,withSize:true}));}t.jobPage&&(!t.jobPages||t.jobPages.length<=0)&&(t.jobPages=[t.jobPage]);const i=t.jobPages||[];for(const t of i)for(const i of t)yield this.autoLoadDrawItemImage(i,e);return t})}}xe.JOB_COLOR_WHITE="#fff",xe.JOB_COLOR_TRANS="transparent",xe.LINE_WIDTH_MM=.35,xe.FONT_SIZE_MIN_DEFAULT=2;class Te{constructor(t){this._margin=[],this.data=t.data,this.init(t);}get marginTop(){return this._margin.length>0?this._margin[0]:0}get marginRight(){return this._margin.length>1?this._margin[1]:0}get marginLeft(){return this._margin.length>3?this._margin[3]:this.marginRight}get marginBottom(){return this._margin.length>2?this._margin[2]:this.marginTop}get cornerRadius(){return this._radius||0}get jobInfo(){return this.data.jobInfo}get jobPages(){return this.data.jobPages}get jobWidth(){var t;return (null===(t=this.data.jobInfo)||void 0===t?void 0:t.jobWidth)||0}get jobHeight(){var t;return (null===(t=this.data.jobInfo)||void 0===t?void 0:t.jobHeight)||0}get orientation(){var t;return (null===(t=this.data.jobInfo)||void 0===t?void 0:t.orientation)||0}init(t){this._radius=t.radius||0,this._margin=t.margin||[],this._jobStartAction=t.onJobStart,1===this._margin.length&&this._margin.push(this._margin[0]),t.element&&this.attachTo({element:t.element});}createDrawContext(t){return new xe(Object.assign(Object.assign({},t),{apiMode:false,position:t.position||"relative"}))}attachTo(t){return m(this,0,void 0,function*(){if(!t.element&&!t.canvas)return false;if(!this.drawContext){const e=this.createDrawContext(t);if(!e)return false;const i=this.data.jobInfo;i&&e.resetJobInfo({width:i.jobWidth||0,height:i.jobHeight||0}),this.drawContext=e;}const e=t.element,i=t.canvas;if(e)return this.drawContext.Canvas.Base.appendTo(e),this.raiseViewChanged(e.offsetWidth,e.offsetHeight,t.styles);{const e=t.viewWidth||i.width||0,s=t.viewHeight||i.height||0;return this.raiseViewChanged(e,s,t.styles)}})}raiseViewChanged(t,e,i){return m(this,0,void 0,function*(){const s=this.data?this.data.jobInfo:void 0,n=(null==s?void 0:s.jobWidth)||0,r=(null==s?void 0:s.jobHeight)||0,a=this.drawContext;if(!s)return l.warn("---- 未检测到 jobInfo 相关信息!"),false;if(n<=0||r<=0)return l.warn(`---- 纸张大小错误:{jobWidth: ${n}, jobHeight: ${r}}`),false;if(!a)return l.warn("---- 未检测到绘制上下文!"),false;if(t<=0||e<=0)return l.warn(`---- 参数错误:viewWidth = ${t}, viewHeight = ${e}`),false;const o=e-2,h=t-2-this.marginLeft-this.marginRight,c=o-this.marginTop-this.marginBottom,d=h>0?h/n:0,u=c>0?c/r:0;return a.ZoomRate=Math.min(d,u),this.updateCanvasPosition(a,i),this.refreshView()})}updateCanvasPosition(t,e){var i;if("absolute"!==(null===(i=t.CanvasElement.style)||void 0===i?void 0:i.position))return;const s=t.CanvasElement.parentElement;if(s){const i=s.offsetWidth,n=s.offsetHeight,r=.5*(i-t.PixWidth),a=this.marginTop+.5*(n-this.marginTop-this.marginBottom-t.PixHeight);if(t.CanvasElement.style){if(t.CanvasElement.style.left=`${r}px`,t.CanvasElement.style.top=`${a}px`,e){const i=Object.keys(e);for(const s of i) void 0!==e[s]&&void 0!==t.CanvasElement.style[s]&&(t.CanvasElement.style[s]=e[s]);}e&&"string"==typeof e.borderRadius?t.CanvasElement.style.borderRadius=e.borderRadius:this.cornerRadius>=0&&(t.CanvasElement.style.borderRadius=t.ZoomRate*this.cornerRadius+"px");}}}refreshView(t){return m(this,0,void 0,function*(){const e=this.drawContext,i=this.data.jobInfo;if(!e||!i)return false;t&&(Array.isArray(t)?this.data.jobArguments=t:"object"==typeof t&&(this.data.jobArguments=[t])),yield e.autoLoadImage(this.data);const s=xe.getJobStartOptions(i,this.data.printerInfo),n=e.startJob(s);return !!n&&(this._jobStartAction&&(yield Promise.resolve(this._jobStartAction(n))),e.drawAsyncJob(this.data).then(t=>0===t))})}}class Se{static innerDecode(t){const e=new Uint16Array(32),i=t.length,s=i-32;let n="",r="",a=0,o=0,h=0,c=-1;for(let d=0,u=0,l=0,g=0;g<i;){for(a=g<=s?32:i-g|0;d<a;g=g+1|0,d=d+1|0){switch(u=255&t[g],u>>4){case 15:if(l=255&t[g=g+1|0],l>>6!=2||247<u){g=g-1|0;break}o=(7&u)<<6|63&l,h=5,u=256;case 14:l=255&t[g=g+1|0],o<<=6,o|=(15&u)<<6|63&l,h=l>>6==2?h+4|0:24,u=u+256&768;case 13:case 12:l=255&t[g=g+1|0],o<<=6,o|=(31&u)<<6|63&l,h=h+7|0,g<i&&l>>6==2&&o>>h&&o<1114112?(u=o,o=o-65536|0,0<=o?(c=55296+(o>>10)|0,u=56320+(1023&o)|0,d<31?(e[d]=c,d=d+1|0,c=-1):(l=c,c=u,u=l)):a=a+1|0):(u>>=8,g=g-u-1|0,u=65533),h=0,o=0,a=g<=s?32:i-g|0;default:e[d]=u;continue;case 11:case 10:case 9:case 8:}e[d]=65533;}if(r+=String.fromCharCode(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15],e[16],e[17],e[18],e[19],e[20],e[21],e[22],e[23],e[24],e[25],e[26],e[27],e[28],e[29],e[30],e[31]),d<32&&(r=r.slice(0,d-32|0)),g<i){if(e[0]=c,d=~c>>>31,c=-1,r.length<n.length)continue}else -1!==c&&(r+=String.fromCharCode(c));n+=r,r="";}return n}static decode(t,e){try{return new TextDecoder(e).decode(Uint8Array.from(t))}catch(e){return l.log("DzTextDecoder.decode: TextDecoder is not defined"),this.innerDecode(t)}}}class Me{static decode(t){try{let e="";return e="function"==typeof Me.decodeAction?Me.decodeAction(t):new TextDecoder("gbk").decode(t),e}catch(t){return console.warn(t),""}}static initEncodeTable(){if(!this._table){l.log("---- start to initEncodeTable:");const t=[[161,169,161,254],[176,247,161,254],[129,160,64,254],[170,254,64,160],[168,169,64,160],[170,175,161,254],[248,254,161,254],[161,167,64,160]],e=new Uint16Array(23940);let i=0;for(const[s,n,r,a]of t)for(let t=r;t<=a;t++)if(127!==t)for(let r=s;r<=n;r++)e[i++]=t<<8|r;this._table=new Uint16Array(65536),this._table.fill(65535);const s=Me.decode(e);if(!s)return this._table=new Uint16Array(0),this._table;for(let t=0;t<s.length;t++)this._table[s.charCodeAt(t)]=e[t];l.log("---- end to initEncodeTable:");}return this._table}static encode(t,e){t=t||"";const i=this.initEncodeTable();if(i.length<=0)return void console.warn("---- 当前系统不支持该操作。");const s=new Uint16Array(t.length);for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);if(r<128){s[n]=r;continue}const a=i[r];if(65535!==a)s[n]=a;else if(8364===r)s[n]=128;else {const t=e?e(n):63;if(-1===t)return s.subarray(0,n);s[n]=t;}}return s}static encodeToUint8Array(t,e){t=t||"";const i=this.initEncodeTable();if(i.length<=0)return void console.warn("---- 当前系统不支持该操作。");const s=new Uint8Array(2*t.length);let n=0;for(let r=0;r<t.length;r++){const a=t.charCodeAt(r);if(a<128){s[n++]=a;continue}const o=i[a];if(65535!==o)s[n++]=o,s[n++]=o>>8;else if(8364===a)s[n++]=128;else {const t=e?e(r):63;if(-1===t)return s.subarray(0,n);t>255?(s[n++]=t,s[n++]=t>>8):s[n++]=t;}}return s.subarray(0,n)}static uint8ArrayToUint16Array(t,e){const i=[];for(let s=0,n=0,r=0;s<t.length;s++)t[s]<128?i.push(t[s]):(n=255&t[s++],r=s<t.length?255&t[s]:0,e?i.push(n<<8|r):i.push(r<<8|n));return Uint16Array.from(i)}}class Be{}Be.base64EncodeChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Be.base64DecodeChars=Uint8Array.from([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,64,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,255,255,255,255,255]),function(t){t[t.ASYNC_WAIT=-1]="ASYNC_WAIT",t[t.OK=0]="OK",t[t.ERROR_PARAM=1]="ERROR_PARAM",t[t.ERROR_NO_PRINTER=2]="ERROR_NO_PRINTER",t[t.ERROR_DISCONNECTED=3]="ERROR_DISCONNECTED",t[t.ERROR_CONNECT_FAILED=4]="ERROR_CONNECT_FAILED",t[t.ERROR_GET_SERVICE=5]="ERROR_GET_SERVICE",t[t.ERROR_GET_CHARACTERISTIC=6]="ERROR_GET_CHARACTERISTIC",t[t.ERROR_OPEN_ADAPTER=7]="ERROR_OPEN_ADAPTER",t[t.ERROR_DATA_SEND_ERROR=8]="ERROR_DATA_SEND_ERROR",t[t.ERROR_DATA_RECEIVE_ERROR=9]="ERROR_DATA_RECEIVE_ERROR",t[t.ERROR_IS_PRINTING=10]="ERROR_IS_PRINTING",t[t.ERROR_RESPONSE_TIMEOUT=11]="ERROR_RESPONSE_TIMEOUT",t[t.ERROR_PRINTER_CANCELED=12]="ERROR_PRINTER_CANCELED",t[t.ERROR_JOB_CREATE=13]="ERROR_JOB_CREATE",t[t.ERROR_JOB_CANCELED=14]="ERROR_JOB_CANCELED",t[t.ERROR_GET_IMAGE_DATA=15]="ERROR_GET_IMAGE_DATA",t[t.ERROR_PRINTER_NOT_AVAILABLE=16]="ERROR_PRINTER_NOT_AVAILABLE",t[t.ERROR_DATA_PARSE=17]="ERROR_DATA_PARSE",t[t.ERROR_NO_IMPLEMENT=18]="ERROR_NO_IMPLEMENT",t[t.ERROR_UN_SUPPORTED=19]="ERROR_UN_SUPPORTED",t[t.ERROR_NOTIFY_CHARACTERISTIC=21]="ERROR_NOTIFY_CHARACTERISTIC",t[t.ERROR_READ_CHARACTERISTIC=22]="ERROR_READ_CHARACTERISTIC",t[t.ERROR_WRITE_CHARACTERISTIC=23]="ERROR_WRITE_CHARACTERISTIC",t[t.ERROR_AUTH_FAILED=24]="ERROR_AUTH_FAILED",t[t.ERROR_CANCEL=25]="ERROR_CANCEL",t[t.ERROR_OTHER=100]="ERROR_OTHER",t[t.ERROR_EXCEPTION=101]="ERROR_EXCEPTION",t[t.ERROR_NO_BRIDGE=102]="ERROR_NO_BRIDGE";}(Ee||(Ee={})),function(t){t[t.DZIP_PRINTABLE=0]="DZIP_PRINTABLE",t[t.DZIP_ISPRINTING=1]="DZIP_ISPRINTING",t[t.DZIP_ISROTATING=2]="DZIP_ISROTATING",t[t.DZIP_NOJOB=10]="DZIP_NOJOB",t[t.DZIP_PAGENOTREADY=11]="DZIP_PAGENOTREADY",t[t.DZIP_JOBCANCELED=12]="DZIP_JOBCANCELED",t[t.DZIP_ENVNOTREADY=20]="DZIP_ENVNOTREADY",t[t.DZIP_VOLTOOLOW=30]="DZIP_VOLTOOLOW",t[t.DZIP_VOLTOOHIGH=31]="DZIP_VOLTOOHIGH",t[t.DZIP_TPHNOTFOUND=32]="DZIP_TPHNOTFOUND",t[t.DZIP_TPHTOOHOT=33]="DZIP_TPHTOOHOT",t[t.DZIP_COVEROPENED=34]="DZIP_COVEROPENED",t[t.DZIP_NO_PAPER=35]="DZIP_NO_PAPER",t[t.DZIP_RIBBONCANOPENED=36]="DZIP_RIBBONCANOPENED",t[t.DZIP_NO_RIBBON=37]="DZIP_NO_RIBBON",t[t.DZIP_UNMATCHED_RIBBON=38]="DZIP_UNMATCHED_RIBBON",t[t.DZIP_TPHTOOCOLD=39]="DZIP_TPHTOOCOLD",t[t.DZIP_USEDUP_RIBBON=40]="DZIP_USEDUP_RIBBON",t[t.DZIP_USEDUP_RIBBON2=41]="DZIP_USEDUP_RIBBON2",t[t.DZIP_NO_LABEL=42]="DZIP_NO_LABEL",t[t.DZIP_UNMATCHED_LABEL=43]="DZIP_UNMATCHED_LABEL",t[t.DZIP_USEDUP_LABEL=44]="DZIP_USEDUP_LABEL",t[t.DZIP_NO_RIBBON2=45]="DZIP_NO_RIBBON2",t[t.DZIP_UNMATCHED_RIBBON2=46]="DZIP_UNMATCHED_RIBBON2",t[t.DZIP_LABELCANOPENED=50]="DZIP_LABELCANOPENED";}(De||(De={})),function(t){t[t.Unset=255]="Unset",t[t.None=0]="None",t[t.Hole=1]="Hole",t[t.Gap=2]="Gap",t[t.Black=3]="Black",t[t.Trans=4]="Trans";}(we||(we={})),function(t){t[t.Unset=255]="Unset",t[t.Min=1]="Min",t[t.Low=2]="Low",t[t.Normal=3]="Normal",t[t.High=4]="High",t[t.Max=5]="Max";}(_e||(_e={})),function(t){t[t.Unset=255]="Unset",t[t.Min=1]="Min",t[t.Low=4]="Low",t[t.Normal=6]="Normal",t[t.High=10]="High",t[t.Max=15]="Max";}(Oe||(Oe={}));class Le{static decodeBase64(t){if(t){if(Le.decodeBase64)return Le.decodeBase64(t);if("function"==typeof atob){const e=Le.atob(t);let i=e.length;const s=new Uint8Array(i);for(;i--;)s[i]=e.charCodeAt(i);return s.buffer}}}static arrayBufferToBase64(t){if(!t||t.length<=0)return "";try{return btoa((new TextDecoder).decode(t))}catch(e){return btoa(t.reduce((t,e)=>t+String.fromCharCode(e),""))}}static arrayBufferToBase64_2(t){let e=0,i=0,s=0;const n=t.length;let r="";for(let a=0;a<n;){if(e=t[a++],a==n){r+=Be.base64EncodeChars.charAt(e>>2),r+=Be.base64EncodeChars.charAt((3&e)<<4),r+="==";break}if(i=t[a++],a==n){r+=Be.base64EncodeChars.charAt(e>>2),r+=Be.base64EncodeChars.charAt((3&e)<<4|(240&i)>>4),r+=Be.base64EncodeChars.charAt((15&i)<<2),r+="=";break}s=t[a++],r+=Be.base64EncodeChars.charAt(e>>2),r+=Be.base64EncodeChars.charAt((3&e)<<4|(240&i)>>4),r+=Be.base64EncodeChars.charAt((15&i)<<2|(192&s)>>6),r+=Be.base64EncodeChars.charAt(63&s);}return r}static base64ToArrayBuffer(t){const e=(t=t.replace(/\s/g,"")).replace(/-/g,"+").replace(/_/g,"/");let i=0;try{const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);return i}catch(e){const s=t.length,n=[],r=new Uint8Array(4);for(let e=0;e<s;){for(i=0;i<r.length&&e<s;e++)r[i]=Be.base64DecodeChars[255&t.charCodeAt(e)],r[i]>=0&&r[i]<=64?i++:10!==r[i]||l.warn(`---- 检测到无效的字符:data[${e}] = '${t.charAt(e)}', charCode = 0x${t.charCodeAt(e).toString(16)}`);if(i>0&&i<r.length)return l.warn(`---- base64字符串解析失败,pos = ${i}, i = ${e}, data.length = ${s}`),Uint8Array.from([]);if(n.push(r[0]<<2|(48&r[1])>>4),r[2]>=64)break;r[3]>=64?n.push((15&r[1])<<4|(60&r[2])>>2):(n.push((15&r[1])<<4|(60&r[2])>>2),n.push((3&r[2])<<6|r[3]));}return Uint8Array.from(n)}}static atob(t){try{if(window&&"function"==typeof window.atob)return atob(t);{const e=Le.base64ToArrayBuffer(t);return Se.decode(new Uint8Array(e),"utf-8")}}catch(t){return l.warn(t),""}}static concatUint8Array(t){const e=t.reduce((t,e)=>t+(e?e.length:0),0),i=new Uint8Array(e);let s=0;for(const e of t)e&&e.length>0&&(i.set(e,s),s+=e.length);return i}static isSupportedService(t){if(!t)return false;if(0===(t=this.getFullUUID(t)).indexOf("F000FFC0"))return false;const e=/^0000([0-9A-F]{4})-0000-1000-8000-00805F9B34FB$/i.exec(t);if(e){const t=e[1];if(t>="0000"&&t<="2AFF")return false;if("FF10"===t)return false;if("FFC0"===t)return false}else if(this.isMatchedUUID(t,"E7810A71-73AE-499D-8C15-FAA9AEF0C3F2"))return false;return true}static getFullUUID(t){return 4===t.length?`0000${t}-0000-1000-8000-00805F9B34FB`.toUpperCase():8===t.length?`${t}-0000-1000-8000-00805F9B34FB`.toUpperCase():t.toUpperCase()}static getShortUUID(t){const e=t.length;return e>8&&"-"===t[8]||8===e?t.substring(4,8).toUpperCase():4===e?t.toUpperCase():""}static isMatchedUUID(t,e){return !(!t||!e)&&(t.length===e.length?t.toUpperCase()===e.toUpperCase():this.getFullUUID(t)===this.getFullUUID(e))}static isDeviceInfoService(t){return 0===this.getFullUUID(t).indexOf("0000180A")}static isDeviceInfoCharacteristic(t){return 0===this.getFullUUID(t).indexOf("00002A24")}static sleep(t,e){return new Promise(i=>{setTimeout(()=>{i(e);},t);})}static execAsync(t,e,i){return new Promise(s=>{setTimeout(()=>{t(e).then(t=>{s(t);});},i||0);})}static getResultMessage(t){switch(t){case Ee.ASYNC_WAIT:return "异步等待中,请稍后";case Ee.OK:return "OK";case Ee.ERROR_PARAM:return "参数错误!";case Ee.ERROR_NO_PRINTER:return "未检测到打印机或者未指定打印机";case Ee.ERROR_DISCONNECTED:return "打印机未连接";case Ee.ERROR_CONNECT_FAILED:return "打印机链接失败";case Ee.ERROR_OPEN_ADAPTER:return "蓝牙适配器打开失败";case Ee.ERROR_NOTIFY_CHARACTERISTIC:return "特征值notify启动失败";case Ee.ERROR_READ_CHARACTERISTIC:return "特征值读取失败";case Ee.ERROR_WRITE_CHARACTERISTIC:return "特征值写入失败";case Ee.ERROR_DATA_SEND_ERROR:return "数据发送失败";case Ee.ERROR_DATA_RECEIVE_ERROR:return "数据接收异常,打印机无响应";case Ee.ERROR_IS_PRINTING:return "打印机正在打印过程中不能打印其他标签";case Ee.ERROR_RESPONSE_TIMEOUT:return "指令发送响应超时";case Ee.ERROR_JOB_CREATE:return "打印任务创建失败";case Ee.ERROR_JOB_CANCELED:return "打印任务被取消";case Ee.ERROR_GET_IMAGE_DATA:return "打印数据获取失败";case Ee.ERROR_PRINTER_NOT_AVAILABLE:return "打印机状态异常";case Ee.ERROR_OTHER:return "其他异常";case Ee.ERROR_EXCEPTION:return "捕获到代码异常!";default:return "未知异常"}}static successResult(t,e,i){return e&&("function"==typeof e.success&&e.success(t),"function"==typeof e.complete&&e.complete(t),"function"==typeof e.callback&&e.callback(t)),i&&i(t),t}static setSuccessResult(t,e,i){return this.successResult(t,e,i)}static failResult(t,e,i){const s="object"==typeof t?t:void 0;return s&&"number"==typeof s.statusCode&&(s.errMsg||(s.errMsg=Le.getResultMessage(s.statusCode))),e&&("function"==typeof e.fail&&e.fail(t),"function"==typeof e.complete&&e.complete(t),"function"==typeof e.callback&&e.callback(t)),i&&i(t),t}static setFailResult(t,e,i){return this.failResult(t,e,i)}static onResult(t,e,i){return t.errMsg||(t.errMsg=Le.getResultMessage(t.statusCode)),t.codeName||(t.codeName=Ee[t.statusCode]),e&&(0===t.statusCode?e.success&&e.success(t.resultInfo):e.fail&&e.fail(t),"function"==typeof e.complete&&e.complete(t),"function"==typeof e.callback&&e.callback(t)),i&&i(t),t}static success(t,e,i){return this.onResult({statusCode:Ee.OK,resultInfo:t},e,i)}static fail(t,e,i){return this.onResult({statusCode:Ee.ERROR_OTHER,resultInfo:t},e,i)}static complete(t,e,i,s){return this.onResult({statusCode:t,resultInfo:e},i,s)}static processResult(t,e,i,s){return this.complete(t,e,i,s)}static getBytes(t){return this.hex16ToArrayBuffer(t)}static hex16ToArrayBuffer(t){const e=[];let i="";for(let s=0;s<t.length;s+=2)i=t.substring(s,s+2),e.push(parseInt(i,16));return Uint8Array.from(e)}static arrayBufferToHex16(t,e,i){return this.arrayToHexString(Array.from(t),e,i)}static toHexByteString(t,e){return (e||"")+`00${t.toString(16)}`.slice(-2)}static toHexShortString(t,e){return (e||"")+`0000${t.toString(16)}`.slice(-4)}static toHexString(t,e){try{return (e||"")+`00000000${t.toString(16)}`.slice(-8)}catch(e){return l.warn("Capture Exception from LPAUtils.toHexString:",e),`${t}`}}static arrayToHexString(t,e,i){return t.map(t=>Le.toHexByteString(t,i)).join(e||"")}static getString(t,e,i){const s=e||0;return i&&i>0?t=t.slice(s,i):s>0&&(t=t.slice(s)),Se.decode(t,"gbk")}static isAndroid(t){return t?"android"===(t=t.toLowerCase()):!!navigator&&/android/i.test(navigator.userAgent||"")}static isHarmonyOS(t){return t?(t=t.toLowerCase()).indexOf("ohos")>=0||t.indexOf("harmony")>=0:!(!navigator||!navigator.userAgent)&&((t=navigator.userAgent).indexOf("ohos")>=0||t.indexOf("harmony")>=0)}static isIOS(t){return t?"ios"===(t=t.toLowerCase())||"iphone"===t||"ipad"===t||"ipod"===t:!!navigator&&/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent||"")}static isWindows(){if(!navigator)return false;const t=(navigator.platform||"").toLowerCase(),e=(navigator.userAgent||"").toLowerCase();return -1!==t.indexOf("win")||(-1!==e.indexOf("windows")||-1!==e.indexOf("win"))}static isLinux(){if(!navigator)return false;const t=(navigator.platform||"").toLowerCase(),e=(navigator.userAgent||"").toLowerCase();return -1!==t.indexOf("linux")||(-1!==e.indexOf("linux")||-1!==e.indexOf("x11"))}static isMacOS(){const t=(navigator.platform||"").toLowerCase(),e=(navigator.userAgent||"").toLowerCase();return -1!==t.indexOf("mac")||(-1!==e.indexOf("mac")||-1!==e.indexOf("macos"))}static getRequestData(t,e){if(null==e?e=[]:"object"!=typeof e&&(e=[e]),e.length&&"object"==typeof e[0])return e[0];const i={};if("string"==typeof t&&(t=[t]),t.length<1||!t[0])return i;for(let s=0;s<t.length;s++)i[t[s]]=e[s];return i}static filter(t,e){return Object.keys(t).filter(i=>!!e&&e(i,t[i])).reduce((e,i)=>(e[i]=t[i],e),{})}static filter_NoFunc(t){return Le.filter(t,(t,e)=>"function"!=typeof e)}static filter_NoNone(t){return Le.filter(t,(t,e)=>null!=e)}static filter_NoFuncAndNone(t){return Le.filter(t,(t,e)=>null!=e&&"function"!=typeof e)}static filterAndAssign(t,e,i){const s=i||((t,e)=>null!=e&&"function"!=typeof e),n=Le.filter(t,s);return Object.assign(n,e)}static combineUint8Array(t){const e=t.reduce((t,e)=>t+e.length,0),i=new Uint8Array(e);let s=0;return t.forEach(t=>{i.set(t,s),s+=t.length;}),i}static lowByte(t){return 255&t}static highByte(t){return t>>>8&255}static toPromise(t){return new Promise(e=>{t(e);})}static randomUUID(t){return e.randomUUID(t)}static getRandomValues(t,i){return e.getRandomValues(t,i)}static getRandomStr(t){return e.getRandomStr(t)}static nextPageKey(t){return ++t>=65535&&(t=1),t}static isPromise(t){return !!t&&(t instanceof Promise||"object"==typeof t&&"function"==typeof t.then)}}class Ne{static createEmitter(t){return new Ne(t||"")}constructor(t){this.listeners=new Map,this.tagName=t;}on(t,e){const i=e||Ne.EVENT_NAME;let s=this.listeners.get(i);return s?s.push(t):(s=[t],this.listeners.set(i,s)),t}off(t,e){const i=e||Ne.EVENT_NAME,s=this.listeners.get(i);if(s){const e=s.indexOf(t);if(e>=0)return s.splice(e,1),t}}clear(t){const e=this.listeners.get(t||Ne.EVENT_NAME);return e?e.splice(0):[]}emit(t,e,i){var s;const n=e||Ne.EVENT_NAME,r=(null===(s=this.listeners.get(n))||void 0===s?void 0:s.slice(0))||[];i?r.forEach(e=>e(t)):setTimeout(()=>{r.forEach(e=>e(t));});}invoke(t,e){this.emit(t,e,true);}beginInvoke(t,e){this.emit(t,e,false);}}Ne.EVENT_NAME="_";class Ue{static getPackBytes(t){return t+(t>=192?5:4)}static toShort(t,e){return this.toNumber(t,e)}static toEBV(t,e){return e&&e>=192?this.toNumber(t,-193&e):255&t}static fromEBV(t){const e=[];return t>=192?(e.push(t>>>8|192),e.push(255&t)):e.push(t),e}static fromBuffer(t,e){const i=Array.from(e);return i.length>0?new Ue(t,i):new Ue(t)}static fromRawData(t){if(t.length<4||t[0]!=Ue.DEVICE_TO_HOST_DATA_START)return;const e=t[1];if(!(e<=0)){if(t[2]>=192){const i=Ue.toShort(t[3],t[2]);if(t.length<i+5)return;const s=t[i+4],n=Ue.calcCRC(t,1,i+4);if(s!==Ue.FIXED_PACKAGE_CRC_RESULT&&s!==n)return l.warn(`---- CRC检验失败:cmd = 0x${e.toString(16)}, receiveCRC = ${s}, calcCRC = ${n}`),void l.warn(`---- data: 0x[${Le.arrayBufferToHex16(t)}]`);const r=Ue.fromBuffer(e,t.slice(4,i+4));return r.setRawData(t.slice(0,i+5)),r}{const i=t[2];if(t.length<i+4)return;const s=t[i+3],n=Ue.calcCRC(t,1,i+3);if(s!==Ue.FIXED_PACKAGE_CRC_RESULT&&s!==n)return l.warn(`---- CRC校验失败:cmd = 0x${e.toString(16)}, receiveCrc = ${s}, calcCrc = ${n}`),void l.warn(`---- data: 0x[${Le.arrayBufferToHex16(t)}]`);const r=Ue.fromBuffer(e,t.slice(3,i+3));return r.setRawData(t.slice(0,i+4)),r}}}static toNumber(t,e,i,s){let n=0;return t&&(n|=255&t),e&&(n|=(255&e)<<8),i&&(n|=(255&i)<<16),s&&(n|=(255&s)<<24),n}static getBytesFromNumber(t,e){const i=new Uint8Array(e);for(let s=0;s<e;s++)i[s]=t>>>8*(e-1-s)&255;return i}static getBytesFromShort(t,e){let i=[t>>>8&255,255&t];return e&&(i=t>=192?[t>>>8|192,255&t]:[255&t]),new Uint8Array(i)}static getBytesFromInt32(t){return this.getBytesFromNumber(t,4)}static calcCRC(t,e,i){let s=0;for(;e<i;++e)s+=255&t[e];return 255&~s}static parse(t){return t.length>=4&&t[0]===Ue.DEVICE_TO_HOST_DATA_START?Ue.fromRawData(Uint8Array.from(t)):void 0}constructor(t,e){this.mOffset=0,this.mCmd=t,this.mData=e||[];}get cmd(){return this.mCmd}get Data(){return this.mData}get Length(){return this.mData?this.mData.length:0}get Remains(){return this.mData.length-this.mOffset}getRawData(){return this.mRawData}setRawData(t){this.mRawData=t;}pushByte(t){this.mData.push(255&t);}popByte(t){let e=t||0;return this.mOffset<this.mData.length&&(e=this.mData[this.mOffset++]),e}pushShort(t,e){e?t>=192?(this.mData.push(t>>>8|192),this.mData.push(255&t)):this.mData.push(255&t):(this.mData.push(t>>>8&255),this.mData.push(t>>>0&255));}popShort(t){let e=t||0;const i=this.mOffset;return i<=this.mData.length-2?(e=Ue.toShort(this.mData[i+1],this.mData[i]),this.mOffset+=2):e=Ue.toShort(this.mData[this.mOffset++]),e}pushEBV(t){return t>=192?(this.mData.push(t>>>8|192),this.mData.push(255&t),this.mOffset+=2,this.mOffset):(this.mData.push(t),this.mOffset++,this.mOffset)}popEBV(t){const e=this.mOffset;let i=t||0;return e<this.mData.length&&(this.mData[e]>=192&&this.mData.length>=e+2?(i=Ue.toEBV(this.mData[e+1],-193&this.mData[e]),this.mOffset+=2):i=this.mData[this.mOffset++]),i}pushInt(t){this.mData.push(t>>>24&255),this.mData.push(t>>>16&255),this.mData.push(t>>>8&255),this.mData.push(t>>>0&255);}popInt(t){let e=t||0;const i=this.mOffset;return i+4<=this.mData.length&&(e=Ue.toNumber(this.mData[i+3],this.mData[i+2],this.mData[i+1],this.mData[i]),this.mOffset+=4),e}popInteger(t){return this.popInt(t)}popString(){const t=this.mOffset;if(t>=this.mData.length)return "";let e=t;for(;e<this.mData.length&&0!==this.mData[e];e++);this.mOffset=e;const i=this.mData.slice(t,e);return Se.decode(Uint8Array.from(i),"gbk")}popByteArray(){const t=this.mOffset;return t>=this.mData.length?new Uint8Array(0):(this.mOffset=this.mData.length,Uint8Array.from(this.Data.slice(t)))}getBufferLength(){return Ue.getPackBytes(this.mData.length)}getBytes(){const t=this.mData||[],e=t.length,i=new Uint8Array(e+(e>=192?5:4));if(i[0]=Ue.DEVICE_TO_HOST_DATA_START,i[1]=this.mCmd,e>=192){i[2]=e>>>8|192,i[3]=255&e;for(let s=0;s<e;s++)i[s+4]=t[s];i[e+4]=Ue.FIXED_PACKAGE_CRC_RESULT;}else {i[2]=e;for(let s=0;s<e;s++)i[s+3]=t[s];i[e+3]=Ue.FIXED_PACKAGE_CRC_RESULT;}return i}}Ue.HOST_TO_DEVICE_DATA_START=31,Ue.DEVICE_TO_HOST_DATA_START=31,Ue.FIXED_PACKAGE_CRC_RESULT=136;class Fe{get FreeSpace(){return this.mBuffer.length-this.mBufLen}get Length(){return this.mBufLen}constructor(t){this.mBufLen=0;const e=t&&t>Fe.BUFFER_LENGTH_DEFAULT?t:Fe.BUFFER_LENGTH_DEFAULT;this.mBuffer=new Uint8Array(e);}static getBytes(t,e){return new Ue(t,e).getBytes()}pushPackage(t,e){const i=Fe.getBytes(t,e);return this.push(i)}pushByte(t,e){const i=Fe.getBytes(t,[255&e]);return this.push(i)}pushShort(t,e,i){const s=Ue.getBytesFromShort(e,i);return this.push(Fe.getBytes(t,Array.from(s)))}pushInt(t,e){const i=Ue.getBytesFromInt32(e);return this.push(Fe.getBytes(t,Array.from(i)))}push(t,e,i){const s=e||0,n=i||t.length;if(n-s>this.mBuffer.length-this.mBufLen)return l.warn("---- PackageBuffer缓存不够!"),false;for(let e=s;e<n;e++)this.mBuffer[this.mBufLen++]=t[e];return true}getAllBytes(){return this.mBuffer.slice(0,this.mBufLen)}clearBuffer(){this.mBufLen=0,this.mBuffer.fill(0);}toString(){return `{size: ${this.mBuffer.length}, mBufLen: ${this.mBufLen}, buffer: [${Le.arrayBufferToHex16(this.mBuffer)}]}`}}Fe.BUFFER_LENGTH_DEFAULT=1e3;class $e{constructor(){this.mBufferList=[];}get BufferList(){return this.mBufferList}get Length(){return this.mBufferList.length}reset(){this.mBufferList.splice(0);}toList(){return this.mBufferList.slice(0)}push(t,e,i){const s=e||0,n=i||t.length,r=n-s;let a=this.mBufferList[this.mBufferList.length-1];(!a||a.FreeSpace<r)&&(a=new Fe(r),this.mBufferList.push(a)),a.push(t,s,n);}push2(t,e,i,s,n,r){const a=new Fe;a.push(t,e,i),a.push(s,n,r),this.push(a.getAllBytes());}pushPackage(t,e){const i=Fe.getBytes(t,e);return this.push(i)}}const je=[1,2,3,4,5,6,7,8,9,10,11,12,24,36,48,120],He=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,41,62,83,104,125,146,167,188,209,230,461,923];class We{static appendRLEC(t,e,i,s,n){for(;s>=63;s-=63){if(e.value+2>n)return false;t[e.value]=255,++e.value,t[e.value]=i,++e.value;}switch(s){case 1:if(i>192){if(e.value+2>n)return false;t[e.value]=193,++e.value,t[e.value]=i,++e.value;}else {if(e.value+1>n)return false;t[e.value]=i,++e.value;}break;case 2:if(e.value+2>n)return false;i>192?(t[e.value]=194,++e.value,t[e.value]=i,++e.value):(t[e.value]=i,++e.value,t[e.value]=i,++e.value);break;default:if(s>0){if(e.value+2>n)return false;t[e.value]=192|s,++e.value,t[e.value]=i,++e.value;}}return true}static calcRLEC(t,e,i,s){if(e<=0)return 0;const n={value:0};let r=t[0],a=1;for(let o=1;o<e;++o)if(t[o]===r)++a;else {if(!this.appendRLEC(i,n,r,a,s))return 0;r=t[o],a=1;}return this.appendRLEC(i,n,r,a,s)?n.value:0}static appendRLE5(t,e,i,s,n){if(s<=0)return true;let r=Math.floor(5*e.value/8),a=15;for(;s>0;)if(s>=je[a]){s-=je[a];const o=a|(i?16:0);if(e.value=e.value+1,5*e.value>8*n)return false;switch(7&e.value){case 0:t[r]=t[r]|o,++r;break;case 1:t[r]=t[r]|o<<3;break;case 2:t[r]=t[r]|o>>>2,++r,t[r]=t[r]|(3&o)<<6;break;case 3:t[r]=t[r]|o<<1;break;case 4:t[r]=t[r]|o>>>4,++r,t[r]=t[r]|(15&o)<<4;break;case 5:t[r]=t[r]|o>>>1,++r,t[r]=t[r]|(1&o)<<7;break;case 6:t[r]=t[r]|o<<2;break;case 7:t[r]=t[r]|o>>>3,++r,t[r]=t[r]|(7&o)<<5;}}else s<=12?a=s-1:--a;return true}static calcRLE5X(t,e,i,s){if(e<=0)return 0;let n=0,r=0,a=false,o=128;const h={value:0};for(;;){if(0!==(t[r]&o))if(a)++n;else {if(!this.appendRLE5(i,h,false,n,s))return 0;a=true,n=1;}else if(a){if(!this.appendRLE5(i,h,true,n,s))return 0;a=false,n=1;}else ++n;if(1===o){if(++r,r>=e)break;o=128;}else o>>>=1;}return a&&!this.appendRLE5(i,h,true,n,s)?0:h.value}static calcRLE5D(t,e,i,s,n,r){let a=0,o=0,h=false,c=128;const d={value:0},u=Math.min(e,s);if(u>0)for(;;){if((i[o]&c)!==(t[o]&c))if(h)++a;else {if(!this.appendRLE5(n,d,false,a,r))return 0;h=true,a=1;}else if(h){if(!this.appendRLE5(n,d,true,a,r))return 0;h=false,a=1;}else ++a;if(1===c){if(++o,o>=u)break;c=128;}else c>>>=1;}if(e!==s)for(e<s&&(t=i,e=s),c=128;;){if(0!==(t[o]&c))if(h)++a;else {if(!this.appendRLE5(n,d,false,a,r))return 0;h=true,a=1;}else if(h){if(!this.appendRLE5(n,d,true,a,r))return 0;h=false,a=1;}else ++a;if(1===c){if(++o,o>=e)break;c=128;}else c>>>=1;}return h&&!this.appendRLE5(n,d,true,a,r)?0:d.value}static appendRLE6(t,e,i,s,n){if(s<=0)return true;let r=Math.floor(6*e.value/8),a=31;for(;s>0;)if(s>=He[a]){s-=He[a];const o=a|(i?32:0);if(e.value=e.value+1,6*e.value>8*n)return false;switch(3&e.value){case 0:t[r]=t[r]|o,++r;break;case 1:t[r]=t[r]|o<<2;break;case 2:t[r]=t[r]|o>>>4,++r,t[r]=t[r]|(15&o)<<4;break;case 3:t[r]=t[r]|o>>>2,++r,t[r]=t[r]|(3&o)<<6;}}else s<=20?a=s-1:--a;return true}static calcRLE6X(t,e,i,s){if(e<=0)return 0;let n=0,r=0,a=false,o=128;const h={value:0};for(;;){if(0!==(t[r]&o))if(a)++n;else {if(!this.appendRLE6(i,h,false,n,s))return 0;a=true,n=1;}else if(a){if(!this.appendRLE6(i,h,true,n,s))return 0;a=false,n=1;}else ++n;if(1===o){if(++r,r>=e)break;o=128;}else o>>>=1;}return a&&!this.appendRLE6(i,h,true,n,s)?0:h.value}static calcRLE6D(t,e,i,s,n,r){let a=0,o=0,h=false,c=128;const d={value:0},u=Math.min(e,s);if(u>0)for(;;){if((i[o]&c)!==(t[o]&c))if(h)++a;else {if(!this.appendRLE6(n,d,false,a,r))return 0;h=true,a=1;}else if(h){if(!this.appendRLE6(n,d,true,a,r))return 0;h=false,a=1;}else ++a;if(1===c){if(++o,o>=u)break;c=128;}else c>>>=1;}if(e!==s)for(e<s&&(t=i,e=s),c=128;;){if(0!==(t[o]&c))if(h)++a;else {if(!this.appendRLE6(n,d,false,a,r))return 0;h=true,a=1;}else if(h){if(!this.appendRLE6(n,d,true,a,r))return 0;h=false,a=1;}else ++a;if(1===c){if(++o,o>=e)break;c=128;}else c>>>=1;}return h&&!this.appendRLE6(n,d,true,a,r)?0:d.value}}const ke=1024,Je=1536,Ve=[12];class Ge{static getPrintableMessage(t){const e=t;switch(e){case Ge.DZIP_PRINTABLE:return "OK";case Ge.DZIP_ISPRINTING:return "正在打印";case Ge.DZIP_ISROTATING:return "正在转动马达";case Ge.DZIP_NOJOB:return "没有打印任务";case Ge.DZIP_PAGENOTREADY:return "页面数据还没有接收完全";case Ge.DZIP_JOBCANCELED:return "当前打印任务被取消";case Ge.DZIP_VOLTOOLOW:return "打印电压太低了";case Ge.DZIP_VOLTOOHIGH:return "打印电压太高了";case Ge.DZIP_TPHNOTFOUND:return "没有检测到打印头";case Ge.DZIP_TPHTOOHOT:return "打印头温度太高了";case Ge.DZIP_COVEROPENED:return "打印机盖子打开了";case Ge.DZIP_NO_PAPER:return "未检测到纸张";case Ge.DZIP_RIBBONCANOPENED:return "碳带盒未锁紧";case Ge.DZIP_NO_RIBBON:return "未检测到碳带";case Ge.DZIP_UNMATCHED_RIBBON:return "不匹配的碳带";case Ge.DZIP_TPHTOOCOLD:return "环境温度过低";case Ge.DZIP_USEDUP_RIBBON:return "用完的碳带";case Ge.DZIP_USEDUP_RIBBON2:return "用完的色带";case Ge.DZIP_LABELCANOPENED:return "标签盒未锁紧";default:return "未知异常:"+e}}}Ge.CMD_NULL=0,Ge.CMD_IS_PRINTABLE=112,Ge.DZIP_PRINTABLE=0,Ge.DZIP_ISPRINTING=1,Ge.DZIP_ISROTATING=2,Ge.DZIP_NOJOB=10,Ge.DZIP_PAGENOTREADY=11,Ge.DZIP_JOBCANCELED=12,Ge.DZIP_ENVNOTREADY=20,Ge.DZIP_VOLTOOLOW=30,Ge.DZIP_VOLTOOHIGH=31,Ge.DZIP_TPHNOTFOUND=32,Ge.DZIP_TPHTOOHOT=33,Ge.DZIP_COVEROPENED=34,Ge.DZIP_NO_PAPER=35,Ge.DZIP_RIBBONCANOPENED=36,Ge.DZIP_NO_RIBBON=37,Ge.DZIP_UNMATCHED_RIBBON=38,Ge.DZIP_TPHTOOCOLD=39,Ge.DZIP_USEDUP_RIBBON=40,Ge.DZIP_USEDUP_RIBBON2=41,Ge.DZIP_NO_LABEL=42,Ge.DZIP_UNMATCHED_LABEL=43,Ge.DZIP_USEDUP_LABEL=44,Ge.DZIP_NO_RIBBON2=45,Ge.DZIP_UNMATCHED_RIBBON2=46,Ge.DZIP_LABELCANOPENED=50,Ge.DZCT_ANDROID_APP=0,Ge.DZCT_ANDROID_BLE=6,Ge.DZCT_ANDIOS_DJGW=12,Ge.DZCT_ANDROID_USB=16,Ge.CMD_ENABLE_SETTING=128,Ge.CMD_DEVICE_TYPE=120,Ge.CMD_DEVICE_NAME=121,Ge.CMD_DEVICE_VERSION=122,Ge.CMD_BUFFER_SIZE2=123,Ge.CMD_SOFTWARE_VERSION=124,Ge.CMD_PRINTER_DPI=113,Ge.CMD_PRINTER_WIDTH=114,Ge.CMD_MANUFACTURER=117,Ge.CMD_BUFFER_STATE=118,Ge.CMD_BUFFER_SIZE=119,Ge.CMD_PAGE_START=32,Ge.CMD_PAGE_PRINT=33,Ge.CMD_PAGE_LINE=34,Ge.CMD_PAGE_PARAM=37,Ge.CMD_PAGE_HEIGHT=38,Ge.CMD_PAGE_WIDTH=39,Ge.CMD_PAGE_END=40,Ge.CMD_PAGE_CONTROL=35,Ge.CMD_DARKNESS=67,Ge.CMD_SPEED=68,Ge.CMD_GAP_TYPE=66,Ge.CMD_GAP_LEN=69,Ge.CMD_MOTORMODE=71,Ge.CMD_AUTOPOWEROFF=72,Ge.CMD_LANGUAGE=73,Ge.CMD_CAP_GAPTYPE=82,Ge.CMD_CAP_MOTORMODE=87,Ge.CMD_CAP_LANGUAGE=89,Ge.CMD_DEVICE_DMINFO=125,Ge.CMD_SET_GENFLAGS=77,Ge.CMD_COMMIT_PARAM=79,Ge.CMD_DEV_DISCOVERY=90,Ge.CMD_POSITIONING=92,Ge.CMD_ADDRESS_READ=97,Ge.CMD_PERIPHERALFLAGS=131,Ge.CMD_PERIPHERALTYPE_FLAGS=1,Ge.CMD_PERIPHERALTYPE_SPISPEED=2,Ge.CMD_HARDWARE_FLAGS=132,Ge.CMD_REQ_ADCVALUE=136,Ge.CMD_DEV_HANDSHAKE=158,Ge.CMD_MANU_TOOLKIT=159,Ge.CMD_MCU_GETID=10,Ge.CMD_DEBUG_BUFFER=127,Ge.CMD_PRINT_COUNTER=115,Ge.CMD_MANUSHIPTIME=17,Ge.CMD_SUB_ROM_UPGRADE=41,Ge.CMD_BITMAP_P_RLEC=41,Ge.CMD_BITMAP_PRINT=43,Ge.CMD_BITMAP_P_RLEX=44,Ge.CMD_BITMAP_P_RLED=45,Ge.CMD_BITMAP_P_RLE6X=60,Ge.CMD_BITMAP_P_RLE6D=61,Ge.CMD_BITMAP_REPEAT=46,Ge.CMD_0x40=64,Ge.ADCEVT_POWER=1,Ge.ADCEVT_TPHTM=2,Ge.PCPDHF_UHFRFID_WRITOR=2,Ge.PCPDHF_HFRFID_WRITOR=4,Ge.PCPDHF_NFCRFID_WRITOR=6,Ge.PCPDHF_MSKRFID_WRITOR=6,Ge.PCPDHF_HAS_BEEP=16384,Ge.PCPDHF_SUPER_BITMAP=16,Ge.PCPDHF_GRAY_BITMAP=32,Ge.PCPDHF_BLUETOOTH_2=131072,Ge.PCPDSF_NO_AUTO_OUT=268435456,Ge.PCPDSF_MOTOR_ANTIDIR=1,Ge.PCPDSF_RLE5_BITMAP=16,Ge.PCPDSF_RLE6_BITMAP=32,Ge.PCPDSF_RLEC_BITMAP=128,Ge.PCPDSF_MASK_BITMAP=240,Ge.PCPDSF_BT_HARD_FC=256,Ge.PCPDSF_PRTA_RIGHT=0,Ge.PCPDSF_PRTA_CENTER=512,Ge.PCPDSF_PRTA_LEFT=1024,Ge.PCPDSF_PRTA_MASK=1536,Ge.PCPDSF_ROTATE_180=16384,Ge.PCPDAF_BT_HARD_FC=1,Ge.PCPDAF_STRING_GBK=2,Ge.PCPDAF_HAS_WIFI=4096,Ge.PCPDAF_RLEC_BITMAP=128;class Ke{constructor(){this.mThreshold=Ke.THRESHOLD_DEFAULT,this.mOrientation=0,this.mLineAction=0,this.mSoftwareFlags=16,this.mHardwareFlags=0,this.mSupportSuperBitmap=true,this.mPrinterWidth=0,this.mLineCount=0,this.mLineBytes=0,this.mBufferList=new $e,this.mByteWidth=0,this.mPrevBytes=0,this.mSumLines=0,this.mSumPrints=0,this.mSumRLE5Xs=0,this.mSumRLE5Ds=0,this.mSumRLE6Xs=0,this.mSumRLE6Ds=0,this.mSumRLE_Cs=0,this.mSumRepeats=0,this.mRLE5XSaved=0,this.mRLE5DSaved=0,this.mRLE6XSaved=0,this.mRLE6DSaved=0,this.mRLECSaved=0;}static encodeImageData(t,e){this.instance||(this.instance=new Ke);const i=e||{},s=Object.assign(Object.assign(Object.assign({},i),t),{gapType:"number"==typeof t.gapType?t.gapType:255,printDarkness:"number"==typeof t.printDarkness?t.printDarkness:255,printSpeed:"number"==typeof t.printSpeed?t.printSpeed:255,gapLength:t.gapLength||0,printerDPI:i.printerDPI||t.printerDPI,printerWidth:i.printerWidth||t.printerWidth,softwareFlags:i.softwareFlags||t.softwareFlags,hardwareFlags:i.hardwareFlags||t.hardwareFlags}),n=this.instance.print(s);return n?n.map(t=>t.getAllBytes()):[]}static updatePageKey(t,e){const i=t[0];if(i&&!(i.length<=0)&&31===i[0]&&i[1]===Ge.CMD_PAGE_START&&2===i[2]){const t=Ue.toShort(i[4],i[3]);if(t!==e){const s=Ue.getBytesFromShort(e||0,false);i[3]=s[0],i[4]=s[1],l.log(`---- updatePageKey: from -> to [${t}] => [${e}]`);}}}get IsLandscape(){return 0===this.mOrientation||2===this.mOrientation}print(t){return this.start(t)?(l.info("---- start to image encode:"),this.encode(t),l.info("---- stop to image encode:"),this.end(t)):null}reset(t){const e=t||{},i=e;"number"!=typeof e.printSpeed&&"number"==typeof i.speed&&(e.printSpeed=i.speed),"number"==typeof e.printAlignment&&(0===e.printAlignment?e.printAlignment=ke:1===e.printAlignment?e.printAlignment=512:2===e.printAlignment&&(e.printAlignment=0)),e.orientation="number"==typeof e.orientation?e.orientation:0,e.orientation>=360&&(e.orientation=e.orientation%360),e.orientation>3&&(e.orientation=Math.floor(e.orientation/90)),this.mOrientation=e.orientation,this.mPrinterWidth=e.printerWidth&&e.printerWidth>0?e.printerWidth:Ke.PRINTER_WIDTH_DEFAULT,"number"==typeof e.darkness&&(e.printDarkness=e.darkness),"number"==typeof e.speed&&(e.printSpeed=e.speed),e.threshold&&e.threshold>0&&e.threshold<255?this.mThreshold=e.threshold:this.mThreshold=Ke.THRESHOLD_DEFAULT,this.mBufferList.reset(),this.mSoftwareFlags="number"==typeof e.softwareFlags?e.softwareFlags:16,this.mHardwareFlags=e.hardwareFlags||0,this.mSupportSuperBitmap="boolean"!=typeof e.enableSuperBitmap||e.enableSuperBitmap,this.mLineAction=1,this.mByteWidth=Math.floor((this.mPrinterWidth+7)/8),this.mLineCount=e.marginTop&&e.marginTop>0?e.marginTop:0,this.mLineBytes=0,this.mLineData=new Uint8Array(0),this.mPrevBytes=0,this.mPrevData=new Uint8Array(0),this.mSumLines=0,this.mSumPrints=0,this.mSumRLE5Xs=0,this.mSumRLE5Ds=0,this.mSumRLE6Xs=0,this.mSumRLE6Ds=0,this.mSumRLE_Cs=0,this.mSumRepeats=0,this.mRLE5XSaved=0,this.mRLE5DSaved=0,this.mRLE6XSaved=0,this.mRLE6DSaved=0,this.mRLECSaved=0;}start(t){const e=t.pageKey,i=new Fe,s=t.imageData;if(!s)return l.warn("---- PrintPackage.start --\x3e imageData is null."),false;if(!s.width||!s.height||!s.data)return l.warn("---- PrintPackage.start --\x3e imageData is invalid:",s),false;this.reset(t),l.info(`========== startPage pageKey: ${e} ==========`),l.info(`---- width : ${s.width}`),l.info(`---- height : ${s.height}`),l.info(`---- orientation : ${this.mOrientation}`),l.info(`---- printerDPI : ${t.printerDPI}`),l.info(`---- printerWidth : ${t.printerWidth}`),l.info(`---- gapType : ${t.gapType}`),l.info(`---- printDarkness : ${t.printDarkness}`),l.info(`---- printSpeed : ${t.printSpeed}`),l.info(`---- gapLength : ${t.gapLength}`),l.info(`---- printAlignment : ${t.printAlignment}`),l.info("---- printerAlignment[0/2/4] : "+(this.getPrintAlignment()>>8)),l.info(`---- threshold : ${t.threshold}`),l.info(`---- printable : ${t.printable}`),l.info(`---- mSoftwareFlags : ${Le.toHexString(this.mSoftwareFlags,"0x")}`),l.info(`---- mHardwareFlags : ${Le.toHexString(this.mHardwareFlags,"0x")}`),l.info(`---- supportSuperBitmap : ${this.mSupportSuperBitmap}`),l.info(`---- pageNo : ${t.pageNo}`),l.info(`---- pageCount : ${t.PageCount}`),l.info("=================================================");const n=this.IsLandscape?s.width:s.height,r=Ue.getBytesFromShort(e||0,false);i.pushPackage(Ge.CMD_PAGE_START,Array.from(r));const a=Ue.fromEBV(Math.floor((n+7)/8));i.pushPackage(Ge.CMD_PAGE_WIDTH,a);const o="number"==typeof t.gapType?t.gapType:-1;o>=we.None&&o<=we.Trans&&i.pushPackage(Ge.CMD_GAP_TYPE,[o]);const h="number"==typeof t.gapLength?t.gapLength:0;if(h>0&&o>0&&o<=4){let t=Math.floor(100*h);t>Ke.MAX_EBV_VALUE&&(t=Ke.MAX_EBV_VALUE),i.pushPackage(Ge.CMD_GAP_LEN,Ue.fromEBV(t));}const c="number"==typeof t.printDarkness?t.printDarkness:-1;c>=Oe.Min&&c<=Oe.Max&&i.pushPackage(Ge.CMD_DARKNESS,[c-1]);const d="number"==typeof t.printSpeed?t.printSpeed:-1;return d>=_e.Min&&d<=_e.Max&&i.pushPackage(Ge.CMD_SPEED,[d-1]),this.mBufferList.push(i.getAllBytes()),true}static getImageGrayValue(t,e){return e+3<t.length&&t[e+3]>0?19661*t[e]+38666*t[e+1]+7209*t[e+2]>>>16:255}getPrintAlignment(){return this.mSoftwareFlags&Ge.PCPDSF_PRTA_MASK}encode(t){const e=t.imageData,i=e.width,s=e.height,n=this.IsLandscape?Math.min(i,this.mPrinterWidth):Math.min(s,this.mPrinterWidth);this.mByteWidth=Math.floor((n+7)/8);const r=this.mThreshold;let a=0,o=0;const h=t.printAlignment||this.getPrintAlignment();let c=0;1===this.mOrientation||3===this.mOrientation?s>n&&(c=512===(h&Je)?Math.floor(.5*(s-n)):(h&Je)===ke?0:s-n):i>n&&(c=512===(h&Je)?Math.floor(.5*(i-n)):(h&Je)===ke?0:i-n);const d=e.data;if(1===this.mOrientation)for(let t=0;t<i;++t){const e=new Uint8Array(this.mByteWidth);let h=128,u=0;for(let l=0;l<n;++l)a=4*((s-l-c-1)*i+t),o=Ke.getImageGrayValue(d,a),o<=r&&(e[u]=e[u]|h),1===h?(h=128,++u):h>>>=1;this.printRow(e);}else if(2===this.mOrientation)for(let t=0;t<s;++t){const e=new Uint8Array(this.mByteWidth);let h=128,u=0;a=4*((s-t)*i-c-1);for(let t=0;t<n;++t,a-=4)o=Ke.getImageGrayValue(d,a),o<=r&&(e[u]=e[u]|h),1===h?(h=128,++u):h>>>=1;this.printRow(e);}else if(3===this.mOrientation)for(let t=0;t<i;++t){const e=new Uint8Array(this.mByteWidth);let s=128,h=0;for(let u=0;u<n;++u)a=4*((u+c)*i+(i-t-1)),o=Ke.getImageGrayValue(d,a),o<=r&&(e[h]=e[h]|s),1===s?(s=128,++h):s>>>=1;this.printRow(e);}else for(let t=0;t<s;++t){const e=new Uint8Array(this.mByteWidth);a=4*(i*t+c);let s=128,h=0;for(let t=0;t<n;++t,a+=4)o=Ke.getImageGrayValue(d,a),o<=r&&(e[h]=e[h]|s),1===s?(s=128,++h):s>>>=1;this.printRow(e);}}end(t){const e=t.marginBottom||0;switch(this.mLineAction){case 1:this.pushLine(this.mLineCount+e);break;case 2:this.pushPrint(),this.pushLine(e);break;default:return null}return this.mLineAction=0,this.mBufferList.push(Ve),this.mBufferList.toList()}printRow(t){let e=t.length-1;for(;e>=0&&0===t[e];--e);if(e<0)return this.printLine(1);switch(++e,this.mLineAction){case 1:this.pushLine(this.mLineCount);break;case 2:if(this.mLineBytes===e&&this.checkArrayEquals(this.mLineData,t,e))return this.mLineCount+=1,true;this.pushPrint();break;default:return false}return this.mLineData=t,this.mLineBytes=e,this.mLineCount=1,this.mLineAction=2,true}printLine(t){switch(this.mLineAction){case 1:return this.mLineCount+=t,true;case 2:this.pushPrint();break;default:return false}return this.mLineData=new Uint8Array(0),this.mLineBytes=0,this.mLineCount=t,this.mLineAction=1,true}pushLine(t){if(t<=0)return;this.mSumLines+=t,this.mPrevData=Uint8Array.from([]),this.mPrevBytes=0;const e=[27,74,255];for(;t>=255;t-=255)this.mBufferList.push(e);t>0&&this.mBufferList.push([27,74,t]);}pushPrint(){if(this.mLineCount<=0)return;let t=0;for(;t<this.mLineBytes&&0===this.mLineData[t];++t);const e=this.mLineBytes-t;let i=new Uint8Array(0),s=new Uint8Array(0),n=new Uint8Array(0),r=new Uint8Array(0),a=new Uint8Array(0),o=0,h=0,c=0,d=0,u=0;this.mSupportSuperBitmap&&(128&this.mSoftwareFlags&&(i=new Uint8Array(this.mByteWidth+4),o=We.calcRLEC(this.mLineData,this.mLineBytes,i,this.mByteWidth)),16&this.mSoftwareFlags&&(s=new Uint8Array(this.mByteWidth+4),h=We.calcRLE5X(this.mLineData,this.mLineBytes,s,this.mByteWidth)),16&this.mSoftwareFlags&&this.mPrevData.length>0&&(n=new Uint8Array(this.mByteWidth+4),c=We.calcRLE5D(this.mPrevData,this.mPrevBytes,this.mLineData,this.mLineBytes,n,this.mByteWidth)),32&this.mSoftwareFlags&&(r=new Uint8Array(this.mByteWidth+4),d=We.calcRLE6X(this.mLineData,this.mLineBytes,r,this.mByteWidth)),32&this.mSoftwareFlags&&this.mPrevData.length>0&&(a=new Uint8Array(this.mByteWidth+4),u=We.calcRLE6D(this.mPrevData,this.mPrevBytes,this.mLineData,this.mLineBytes,a,this.mByteWidth)));const l=(t>=192?4:3)+(e>=192?2:1)+e,g=o<=0?this.mByteWidth+100:o+(o>=192?4:3),p=h<=0?this.mByteWidth+100:Math.ceil(5*h/8)+(h>=192?4:3),f=c<=0?this.mByteWidth+100:Math.ceil(5*c/8)+(c>=192?4:3),m=d<=0?this.mByteWidth+100:Math.ceil(6*d/8)+(d>=192?4:3),C=u<=0?this.mByteWidth+100:Math.ceil(6*u/8)+(u>=192?4:3);if(f<l&&f<g&&f<p&&f<m&&f<=C)this.mSumRLE5Ds+=1,this.mRLE5DSaved+=l-f,this.pushRLE5(Ge.CMD_BITMAP_P_RLED,n,c);else if(C<l&&C<g&&C<p&&C<m)this.mSumRLE6Ds+=1,this.mRLE6DSaved+=l-C,this.pushRLE6(Ge.CMD_BITMAP_P_RLE6D,a,u);else if(p<l&&p<g&&p<=m)this.mSumRLE5Xs+=1,this.mRLE5XSaved+=l-p,this.pushRLE5(Ge.CMD_BITMAP_P_RLEX,s,h);else if(m<l&&m<g)this.mSumRLE6Xs+=1,this.mRLE6XSaved+=l-m,this.pushRLE6(Ge.CMD_BITMAP_P_RLE6X,r,d);else if(g<l)this.mSumRLE_Cs+=1,this.mRLECSaved+=l-g,this.pushRLEC(Ge.CMD_BITMAP_P_RLEC,i,o);else {this.mSumPrints+=1;const i=[Ue.HOST_TO_DEVICE_DATA_START,Ge.CMD_BITMAP_PRINT,0,0];let s=this.pushEBV(i,2,t);s=this.pushEBV(i,s,e),this.mBufferList.push2(i,0,s,this.mLineData,t,this.mLineBytes);}this.mLineCount>1&&this.pushRepeat(this.mLineCount-1),this.mPrevData=this.mLineData,this.mPrevBytes=this.mLineBytes;}pushRepeat(t){if(t<=0)return;this.mSumRepeats+=t;const e=16383;let i=[Ue.HOST_TO_DEVICE_DATA_START,46,0];for(this.pushEBV(i,2,e);t>e;t-=16384)this.mBufferList.push(i);t>0&&(i=[Ue.HOST_TO_DEVICE_DATA_START,46,0],this.pushEBV(i,2,t-1),this.mBufferList.push(i));}pushEBV(t,e,i){return i>=192?(t[e+0]=i>>>8|192,t[e+1]=255&i,e+2):(t[e+0]=i,e+1)}pushRLEC(t,e,i){if(i<=0)return;const s=[Ue.HOST_TO_DEVICE_DATA_START,t,0],n=this.pushEBV(s,2,i);this.mBufferList.push2(s,0,n,e,0,i);}pushRLE5(t,e,i){if(i<=0)return;const s=[Ue.HOST_TO_DEVICE_DATA_START,t,0],n=this.pushEBV(s,2,i),r=Math.ceil(5*i/8);this.mBufferList.push2(s,0,n,e,0,r);}pushRLE6(t,e,i){if(i<=0)return;const s=[Ue.HOST_TO_DEVICE_DATA_START,t,0],n=this.pushEBV(s,2,i),r=Math.ceil(6*i/8);this.mBufferList.push2(s,0,n,e,0,r);}checkArrayEquals(t,e,i){for(let s=0;s<i;++s)if(t[s]!==e[s])return false;return true}}var ze,Ze,qe,Xe,Ye,Qe,ti,ei,ii;Ke.MAX_EBV_VALUE=16383,Ke.THRESHOLD_DEFAULT=150,Ke.PRINTER_DPI_DEFAULT=203,Ke.PRINTER_WIDTH_DEFAULT=384,function(t){t[t.AUTO=0]="AUTO",t[t.WEB_BLE=100]="WEB_BLE",t[t.WEB_HID=101]="WEB_HID";}(ze||(ze={})),function(t){t[t.None=0]="None",t[t.Connected=2]="Connected",t[t.Checking=3]="Checking",t[t.ReadyPrint=4]="ReadyPrint",t[t.Sending=5]="Sending",t[t.Printing=6]="Printing",t[t.Paused=7]="Paused",t[t.Cancel=8]="Cancel";}(Ze||(Ze={})),function(t){t[t.None=0]="None",t[t.Printable=1]="Printable",t[t.PageKey=2]="PageKey";}(qe||(qe={})),function(t){t[t.None=0]="None",t[t.Connect=1]="Connect",t[t.Disconnect=2]="Disconnect";}(Xe||(Xe={}));class si{get isFinished(){return !this.mTimer}get userData(){return this.mUserData}constructor(t,e,i){this.mContext=t,this.mUserData=e,this.mTimer=0,this.mTimeout=i||2e3;}dispatcher(t){throw new Error("Method not implemented.")}stop(){this.mTimer&&(clearTimeout(this.mTimer),this.mTimer=0);}start(t,e){this.mResponseAction=t,e&&e>0&&(this.mTimeout=e),this.mTimer=setTimeout(()=>{this.mTimer=0,this.invoke(void 0);},this.mTimeout);const i=this.mUserData.cmd||Le.arrayBufferToHex16(this.mUserData.sendData);l.log(`RequestMessage.start ->: [TM: ${this.mTimer}, CMD: ${i}], mTimeout: ${this.mTimeout}`,e);}invoke(t){this.stop(),this.mResponseAction&&this.mResponseAction(t?this.userData:void 0),this.mContext.popMessage(this);}}class ni extends si{get userData(){return this.mUserData}get cmd(){return this.userData.cmd}constructor(t,e,i){super(t,e,i);}start(t,e){super.start(t,e);const i=Le.toHexByteString(this.cmd);l.log(`RequestCmdMessage.start ->: [TM: ${this.mTimer}, cmd: 0x${i}], timeout: ${e}`);}dispatcher(t){return t.cmd===this.cmd&&(this.invoke(t),true)}invoke(t){const e=Le.toHexByteString(this.cmd);l.log(`RequestCmdMessage.invoke ->: [TM: ${this.mTimer}, mTimeout: ${this.mTimeout}, cmd: 0x${e}], value = ${t?t.Data.join(","):"timeout"}`),t&&(this.userData.respPkg=t),super.invoke(t);}}class ri extends si{get userData(){return this.mUserData}constructor(t,e,i){super(t,e,i);}dispatcher(t){let e=false,i=false;const s=this.userData.pkgList,n=[],r=[];for(const a of s)a.sendPkg.cmd!==t.cmd||a.receivedPkg||e||(a.receivedPkg=t,e=true),a.receivedPkg?n.push(Le.toHexByteString(a.sendPkg.cmd,"0x")):(i=true,r.push(Le.toHexByteString(a.sendPkg.cmd,"0x")));l.log(`---- resolvedPkg : [${n.join(",")}]`),l.log(`---- unresolvedPkg: [${r.join(",")}]`);const a=t.getRawData();return a&&l.warn(`---- pkgData: [${Le.arrayBufferToHex16(a,",","0x")}]`),i||this.invoke(t),e}}class ai{get device(){return this.mDevice}get adapter(){return this.mAdapter}get deviceId(){return this.mDevice.deviceId}get deviceName(){return this.mDevice.name}get printerInfo(){return Object.assign(Object.assign({},this.mDevice),this.mPrinterInfo)}get printable(){return this.mPrinterInfo.printable}get bufferSize(){return this.mBufferSize}get isConnected(){return this.mConnected}get printStatus(){return this.mPrintStatus}get PrintStatusChanged(){return this.mPrintStatusEmitter}get clientType(){return this.mClientType}get isPrinterAvailable(){return this.printable>=0&&this.printable<=Ge.DZIP_PAGENOTREADY}get enableMcuId(){return this.mEnableMcuId}get isPageKeyEnable(){return 0!==(this.mDataSendMode&qe.PageKey)}get isPageKeySupported(){return this.isPageKeyEnable&&this.mIsPrPageKey>=0}get isPageKeyValid(){return this.isPageKeySupported&&this.mIsPrPageKey>0}get printByPrintable(){return 0!==(this.mDataSendMode&qe.Printable)}get connectInfo(){return this.mInitOptions}constructor(t,e,i){this.mInitOptions={},this.mConnected=false,this.mRequestQueue=[],this.mPrinterInfo={printerDPI:0,printerWidth:0,hardwareFlags:0,softwareFlags:Ge.PCPDSF_RLE5_BITMAP,softwareVersion:"",deviceName:"",deviceVersion:"",printable:0,isPrPageKey:-1},this.mMinBufferSize=0,this.mReadBuffer=[],this.mPackageStartRecords=[],this.mPrintJobList=[],this.mPausedPageMap=new Map,this.mPrintingMap=new Map,this.mIsPrPageKey=-1,this.mPageKey=Math.ceil(255*Math.random()),this.mBufferSize=0,this.mClientType=0,this.mEnableMcuId=false,this.mDataSendMode=qe.PageKey,this.mDeviceNameStage=0,this.mPrintStatus=Ze.None,this.mPrintStatusEmitter=Ne.createEmitter("PrintStatusChanged"),this.mIsCheckingPrintable=false,this.mCheckPrintingKeys=[],this.mDevice=t,this.mAdapter=e,i&&this.setOptions(i);}setOptions(t){t&&(this.mInitOptions=Object.assign(Object.assign({},this.mInitOptions),t),"number"==typeof t.clientType&&(this.mClientType=t.clientType),"boolean"==typeof t.enableMcuId&&(this.mEnableMcuId=t.enableMcuId),"number"==typeof t.minBufferSize&&(this.mMinBufferSize=t.minBufferSize),"number"==typeof t.dataSendMode?this.mDataSendMode=t.dataSendMode:"boolean"==typeof t.enablePageKey&&(t.enablePageKey?this.mDataSendMode|=qe.PageKey:this.mDataSendMode&=~qe.PageKey));}connect(t){return l.info(t,`DeviceConnection.connect(${this.deviceName}[${this.deviceId}])`),this.mAdapter.connect({deviceId:this.deviceId,name:this.deviceName,connectionStateChange:e=>{e.deviceId!==this.deviceId||e.connected||(this.disconnect(),t.connectionStateChange&&t.connectionStateChange(e));}}).then(t=>(this.mConnected=0===t.statusCode,this.raisePrintStatusChanged(t.statusCode>0?Ze.None:Ze.Connected),t))}disconnect(t){return l.info(t,`DeviceConnection.disconnect(${this.deviceName}[${this.deviceId}])`),this.adapter.disconnect({deviceId:this.deviceId}).then(t=>(this.mConnected=false,this.raisePrintStatusChanged(Ze.None),0===t.statusCode))}notifyData(t){return this.adapter.notify({deviceId:this.deviceId,dataReceived:e=>{"string"==typeof e&&(e=Le.hex16ToArrayBuffer(e)),t(e);}}).then(t=>({statusCode:t.statusCode,resultInfo:"object"==typeof t.resultInfo?t.resultInfo:void 0}))}writeData(t,e){return this.mBufferSize-=t.length,this.adapter.write({deviceId:this.deviceId,value:t})}checkPrinterInfo(){return t(this,void 0,void 0,function*(){const t=this.device;this.mReadBuffer.splice(0);const e=yield this.notifyData(t=>{this.onDataReceived(t);});if(e.statusCode!==Ee.OK)return l.warn("---- 数据检测启动失败!"),yield this.disconnect(t),Le.onResult({statusCode:Ee.ERROR_NOTIFY_CHARACTERISTIC,resultInfo:"notify 特征值启动失败!"});this.raisePrintStatusChanged(Ze.Checking),yield Le.sleep(30);const i=yield this.loadPrinterInfo();return i.statusCode!==Ee.OK?(l.error(`---- 打印机相关参数获取失败(statusCode: ${i.statusCode})!`),this.raisePrintStatusChanged(Ze.None),yield this.disconnect(t),Le.onResult(i)):(this.raisePrintStatusChanged(Ze.ReadyPrint),Le.successResult({statusCode:Ee.OK,resultInfo:Object.assign(Object.assign({},e.resultInfo||{}),this.mPrinterInfo)}))})}dispatcherRequest(t){for(const e of this.mRequestQueue)if(e.dispatcher(t))break}popMessage(t){const e=this.mRequestQueue.indexOf(t);e>=0&&this.mRequestQueue.splice(e);}pushRequestMessage(t,e){return new Promise(i=>{if(!this.isConnected)return Le.complete(Ee.ERROR_DISCONNECTED,"设备连接异常",void 0,i);const s=e||t.userData;if(!s||s.length<=0)return Le.complete(Ee.ERROR_PARAM,"未检测到发送的数据!",void 0,i);this.mRequestQueue.push(t),t.start(t=>{i({statusCode:t?Ee.OK:Ee.ERROR_RESPONSE_TIMEOUT,resultInfo:t});}),this.writeData(e).then(e=>{e.statusCode>Ee.OK&&(this.popMessage(t),Le.complete(e.statusCode,void 0,void 0,i));});})}pushCommandRequest(t,e,i){const s=new ni(this,{cmd:t,sendData:e},i);return this.pushRequestMessage(s,e)}pushPackageRequest(t,e){const i=new ni(this,{cmd:t.cmd,sendData:t.getRawData()||t.getBytes(),sendPkg:t},e);return this.pushRequestMessage(i,t.getBytes())}pushPackageListRequest(t,e){if(!t||t.length<=0)return Promise.resolve({statusCode:Ee.ERROR_PARAM});const i=t.map(t=>t.getRawData()),s=Le.concatUint8Array(i),n=new ri(this,{sendData:s,pkgList:t.map(t=>({sendPkg:t}))},e);return this.pushRequestMessage(n,s)}queryCommand(e,i){return t(this,void 0,void 0,function*(){if(e===Ge.CMD_NULL&&i&&i.length>0){const t=ai.parsePackageList(new Uint8Array(i),[],[]),s=t.length>0?t[0]:null;s&&(e=s.cmd,i=s.Data);}const t=Fe.getBytes(e,i);return this.pushCommandRequest(e,t)})}raisePrintStatusChanged(t){l.info(`◆◆◆ PrintStatusChanged: ${Ze[this.mPrintStatus]} --\x3e ${Ze[t]} ◆◆◆`),this.mPrintStatus=t,this.PrintStatusChanged.emit(t);}parseManuToolkit(t,e){switch(e){case Ge.CMD_SUB_ROM_UPGRADE:break;case Ge.CMD_MANUSHIPTIME:{const e=t.popByteArray(),i=Se.decode(e);l.info(`★★★★★★ CMD_MANU_TOOLKIT.manuShipTime: ${i} ★★★★★★`);break}case Ge.CMD_MCU_GETID:{const e=t.popByteArray(),i=Le.arrayBufferToHex16(e,"").toUpperCase();this.mPrinterInfo.mcuId=i,l.info(`★★★★★★ CMD_MANU_TOOLKIT.McuId: ${i} ★★★★★★`);break}case Ge.CMD_ADDRESS_READ:{const e=t.popByteArray();l.info(`★★★★★★ CMD_MANU_TOOLKIT.addressRead: [${Le.arrayBufferToHex16(e)}] ★★★★★★`);}}}onReadPackage(t){switch(l.info(`========== DataPackage.onReadPackage: cmd = 【0x${Le.toHexByteString(t.cmd)}】`),l.info(`data: [${Le.arrayToHexString(t.Data)}]`),t.cmd){case Ge.CMD_DEVICE_TYPE:break;case Ge.CMD_BUFFER_SIZE:case Ge.CMD_BUFFER_SIZE2:{const e=t.popEBV();this.mBufferSize=500*(1===e?2:e),l.info(`★★★ bufferSize: ${this.mBufferSize}[0x${e.toString(16)}]`);break}case Ge.CMD_PRINTER_DPI:this.mPrinterInfo.printerDPI=t.popShort(),l.info(`★★★ printerDPI: ${this.mPrinterInfo.printerDPI}`);break;case Ge.CMD_PRINTER_WIDTH:if(t.Remains>=5){const e=t.popByteArray(),i=255&e[0],s=255&e[1];this.mPrinterInfo.printerWidth=(i<<8)+s;const n=255&e[2],r=255&e[3];this.mPrinterInfo.paperWidth=Math.round(.1*((n<<8)+r)),this.mPrinterInfo.printerLocateArea=255&e[4],l.info(`---- pagerWidth: ${this.mPrinterInfo.paperWidth}, printerLocateArea: ${this.mPrinterInfo.printerLocateArea}`);}else this.mPrinterInfo.printerWidth=t.popShort();l.info(`★★★ printerWidth: ${this.mPrinterInfo.printerWidth}`);break;case Ge.CMD_MANUFACTURER:this.mPrinterInfo.manufacturer=t.popString(),l.info(`★★★ manufacturer: ${this.mPrinterInfo.manufacturer}`);break;case Ge.CMD_DARKNESS:this.mPrinterInfo.printDarkness=t.popByte(),l.info(`★★★ printDarkness: ${this.mPrinterInfo.printDarkness}`);break;case Ge.CMD_SPEED:this.mPrinterInfo.printSpeed=t.popByte(),l.info(`★★★ printSpeed: ${this.mPrinterInfo.printSpeed}`);break;case Ge.CMD_GAP_TYPE:this.mPrinterInfo.gapType=t.popByte(),l.info(`★★★ gapType: ${this.mPrinterInfo.gapType}`);break;case Ge.CMD_GAP_LEN:this.mPrinterInfo.gapLength=t.popEBV(),l.info(`★★★ gapLength: ${this.mPrinterInfo.gapLength}`);break;case Ge.CMD_HARDWARE_FLAGS:{const e=t.Data;e.length>20?this.mPrinterInfo.batteryCount=255&e[20]:this.mPrinterInfo.batteryCount=2;const i=t.popInteger();this.mPrinterInfo.hardwareFlags=i,l.info(`mHardwareFlags: [${Le.toHexString(this.mPrinterInfo.hardwareFlags,"0x")}]`),t.Remains>=4?this.mPrinterInfo.softwareFlags=t.popInteger():this.mPrinterInfo.softwareFlags=Ge.PCPDSF_MOTOR_ANTIDIR|Ge.PCPDSF_PRTA_RIGHT|i&Ge.PCPDSF_RLE5_BITMAP,l.info(`★★★ mSoftwareFlags: [${Le.toHexString(this.mPrinterInfo.softwareFlags,"0x")}]`);break}case Ge.CMD_IS_PRINTABLE:{const e=t.Data;if(this.mPrinterInfo.printable=e[0],e.length>=6){if(e[1]===e[2]){const t=Ue.toShort(e[4],e[3]),i=Ue.toShort(e[3],e[4]);let s=0;const n=[...this.mPrintingMap.keys()];for(const e of n){if(e===t){s=t;break}if(e===i){s=i;break}}this.mIsPrPageKey=s>0?s:t;}else this.mIsPrPageKey=0;const t=this.mPrinterInfo.softwareVersion;e.length>=28&&t&&t>="3.1.20250908"&&l.log("----------- 当前打印机支持 pageNo, pageCount, 等等更多高级功能!");}else this.mIsPrPageKey=-1;this.mPrinterInfo.isPrPageKey=this.mIsPrPageKey,l.info(`★★★ printable : 0x${this.printable}, isPrPageKey: ${this.mIsPrPageKey}`);break}case Ge.CMD_DEVICE_NAME:{const e=t.popString();1===this.mDeviceNameStage?(this.mPrinterInfo.deviceName=e,l.info(`★★★ nameStage[${this.mDeviceNameStage}]: deviceName: ${e}`)):2===this.mDeviceNameStage?(this.mPrinterInfo.seriesName=e,l.info(`★★★ nameStage[${this.mDeviceNameStage}]: seriesName: ${e}`)):3===this.mDeviceNameStage?(this.mPrinterInfo.devIntName=e,l.info(`★★★ nameStage[${this.mDeviceNameStage}]: devIntName: ${e}`)):l.warn(`---- nameStage[${this.mDeviceNameStage}]: 未处理的设备信息 deviceName: ${e}`),this.mDeviceNameStage++;break}case Ge.CMD_DEVICE_VERSION:{const e=`${Le.toHexByteString(t.popByte())}`;this.mPrinterInfo.deviceVersion=e.substring(0,1)+"."+e.substring(1),l.info(`★★★ deviceVersion: ${this.mPrinterInfo.deviceVersion}`);break}case Ge.CMD_SOFTWARE_VERSION:this.mPrinterInfo.softwareVersion=t.popString(),l.info(`★★★ softwareVersion: ${this.mPrinterInfo.softwareVersion}`);break;case Ge.CMD_MOTORMODE:this.mPrinterInfo.motorMode=t.popByte();break;case Ge.CMD_AUTOPOWEROFF:this.mPrinterInfo.autoPowerOffMins=t.popEBV();break;case Ge.CMD_REQ_ADCVALUE:{const e=t.popByteArray();if(e.length>0){const t=e[0];if(t==Ge.ADCEVT_TPHTM){if(e.length>2){let t=0;t<<=8,t|=255&e[1],t<<=8,t|=255&e[2],this.mPrinterInfo.printerHeadTem=.1*t,l.info(`★★★ printerHeadTem: ${this.mPrinterInfo.printerHeadTem}`);}}else t==Ge.ADCEVT_POWER&&(e.length>8&&(this.mPrinterInfo.batteryVoltage=.01*Ue.toShort(e[8],e[7]),l.info(`★★★ batteryVoltage: ${this.mPrinterInfo.batteryVoltage}`)),e.length>10&&(this.mPrinterInfo.chargeStatus=e[10]>0,l.info(`★★★ chargeStatus: ${this.mPrinterInfo.chargeStatus}`)),e.length>12&&0!=e[12]&&(this.mPrinterInfo.batteryLevel=e[12],this.mPrinterInfo.batteryVoltageCount=(e[12]>>4)-1,l.info(`★★★ batteryVoltageCount: ${this.mPrinterInfo.batteryVoltageCount}, batteryLevel: ${e[12]}`)));}break}case Ge.CMD_LANGUAGE:case Ge.CMD_CAP_GAPTYPE:case Ge.CMD_CAP_MOTORMODE:case Ge.CMD_CAP_LANGUAGE:break;case Ge.CMD_ENABLE_SETTING:129===t.popByte()&&l.info(`---- This printer supported command package start char is ${Le.toHexByteString(Ue.HOST_TO_DEVICE_DATA_START,"0x")}`);break;case Ge.CMD_PERIPHERALFLAGS:if(1==t.Remains)this.mPrinterInfo.peripheralFlags=t.popByte();else if(t.popByte()===Ge.CMD_PERIPHERALTYPE_FLAGS)this.mPrinterInfo.peripheralFlags=t.popShort();break;case Ge.CMD_DEV_HANDSHAKE:break;case Ge.CMD_MANU_TOOLKIT:{const e=t.popByte();l.info(`★★★ CMD_MANU_TOOLKIT.childCmd: 【0x${Le.toHexByteString(e)}】`),this.parseManuToolkit(t,e);break}case Ge.CMD_DEBUG_BUFFER:{const e=t.popByteArray();l.info(`★★★ CMD_MANU_TOOLKIT.debugBuffer: [${Le.arrayBufferToHex16(e)}]`);}break;case Ge.CMD_PRINT_COUNTER:{const e=t.popByteArray();l.info(`★★★ CMD_MANU_TOOLKIT.printCounter: [${Le.arrayBufferToHex16(e)}]`);for(let t=0;t<4;++t){const i=((255&e[4*t])<<24)+((255&e[4*t+1])<<16)+((255&e[4*t+2])<<8)+(255&e[4*t+3]);l.info(`---- printCounter.line${t} = ${i}`);}}break;case Ge.CMD_0x40:{const e=t.popByteArray();1==e[0]&&(this.mPrinterInfo.batteryCount=e[1],this.mPrinterInfo.batteryVoltage=.01*Ue.toShort(e[3],e[2]),this.mPrinterInfo.batteryVoltageCount=e[4],this.mPrinterInfo.chargeStatus=e[5]>0,this.mPrinterInfo.printable=e[6],l.info(`★★★★★ batteryCount: ${e[1]}, batteryVoltage: ${this.mPrinterInfo.batteryVoltage}, batteryVoltageCount: ${e[4]}, isCharging: ${e[5]}, printable: ${e[6]}`));}}this.dispatcherRequest(t);}onDataReceived(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);l.log(`#### 【onDataReceived】 [${Le.arrayBufferToHex16(e)}]`),ai.parsePackageList(e,this.mReadBuffer,this.mPackageStartRecords,t=>{this.onReadPackage(t);});}static parsePackageList(t,e,i,s){const n=[],r=[];for(const a of t)if(e.length<=0)a===Ue.DEVICE_TO_HOST_DATA_START?e.push(a):r.push(a);else if(a===Ue.DEVICE_TO_HOST_DATA_START&&i.push(e.length),e.push(a),e.length>=4){let t=Ue.parse(e);if(!t&&i.length>0)for(let s=0;s<i.length;s++){const n=i[s];if(e.length-n>=4&&(t=Ue.parse(e.slice(n)),t)){r.push(...e.slice(0,n));break}}t&&(n.push(t),s&&s(t),e.splice(0),i.splice(0));}return r.length>0&&l.warn(`#### 【丢弃无效的指令】:${Le.arrayToHexString(r)}`),e.length>0&&l.info(`---- 待处理数据:[${Le.arrayToHexString(e)}]`),n}loadPrinterInfo(){return t(this,void 0,void 0,function*(){let t=yield this.queryCommand(Ge.CMD_PRINTER_DPI);if(t.statusCode!==Ee.OK)return t;const e=new Fe;if(e.pushPackage(Ge.CMD_PRINTER_WIDTH),e.pushPackage(Ge.CMD_IS_PRINTABLE),t=yield this.writeData(e.getAllBytes()),t.statusCode>Ee.OK)return t;if(this.mDeviceNameStage=1,e.clearBuffer(),e.pushPackage(Ge.CMD_SOFTWARE_VERSION),e.pushPackage(Ge.CMD_DEVICE_NAME),e.pushPackage(Ge.CMD_DEVICE_VERSION),e.pushPackage(Ge.CMD_MANUFACTURER),yield this.writeData(e.getAllBytes()),e.clearBuffer(),e.pushPackage(Ge.CMD_ENABLE_SETTING,[~Ge.CMD_ENABLE_SETTING]),e.pushPackage(Ge.CMD_HARDWARE_FLAGS,[1]),this.mEnableMcuId&&(e.pushPackage(Ge.CMD_MANU_TOOLKIT,[Ge.CMD_MCU_GETID]),e.pushPackage(Ge.CMD_PERIPHERALFLAGS,[Ge.CMD_PERIPHERALTYPE_FLAGS,0]),e.pushPackage(Ge.CMD_MANU_TOOLKIT,[Ge.CMD_MANUSHIPTIME]),yield this.writeData(e.getAllBytes()),e.clearBuffer()),e.pushPackage(Ge.CMD_REQ_ADCVALUE,[Ge.ADCEVT_POWER]),e.pushPackage(Ge.CMD_REQ_ADCVALUE,[Ge.ADCEVT_TPHTM]),e.pushPackage(Ge.CMD_ENABLE_SETTING,[128]),t=yield this.writeData(e.getAllBytes()),t.statusCode>Ee.OK)return t;e.clearBuffer(),e.pushPackage(Ge.CMD_DEVICE_NAME,["S".charCodeAt(0)]),e.pushPackage(Ge.CMD_DEVICE_NAME,["D".charCodeAt(0)]),yield this.writeData(e.getAllBytes()),e.clearBuffer(),e.pushPackage(Ge.CMD_GAP_TYPE),e.pushPackage(Ge.CMD_GAP_LEN),yield this.writeData(e.getAllBytes());let i=[13];return this.mClientType>0&&(i=this.mClientType>255?Ue.getBytesFromShort(this.mClientType):[this.mClientType]),this.queryCommand(Ge.CMD_DEVICE_TYPE,Array.from(i))})}waitPrintable(t){const e=t||3e3;return new Promise(t=>{let i=0;const s=setInterval(()=>{i++,(!this.mIsCheckingPrintable||10*i>=e)&&(clearInterval(s),t(true));},10);})}checkPrintable(e){return t(this,void 0,void 0,function*(){if(!this.isConnected)return;this.mIsCheckingPrintable&&(yield this.waitPrintable()),this.mIsCheckingPrintable=true,this.mPrinterInfo.printable=255,l.info("▶▶▶▶▶-▶▶▶▶▶-▶▶▶▶▶ 【Start】 to check printable: ▶▶▶▶▶-▶▶▶▶▶-▶▶▶▶▶--\x3e:"),l.info(`【checkPrintable】: 0xFF, bufferSize: ${this.mBufferSize}`);const t=new Fe;return t.pushPackage(Ge.CMD_ENABLE_SETTING,[~Ge.CMD_ENABLE_SETTING]),t.pushPackage(Ge.CMD_HARDWARE_FLAGS,[1]),t.pushPackage(Ge.CMD_ENABLE_SETTING,[0]),yield this.writeData(t.getAllBytes()),t.clearBuffer(),t.pushPackage(Ge.CMD_IS_PRINTABLE),t.pushPackage(Ge.CMD_BUFFER_SIZE),this.pushCommandRequest(Ge.CMD_BUFFER_SIZE,t.getAllBytes(),e||2e3).then(t=>{0!==t.statusCode&&(this.mPrinterInfo.printable=-1,l.warn("---- checkPrintable timeout!"));const e=t.resultInfo,i=this.mPrinterInfo.printable,s=this.mIsPrPageKey,n=this.mBufferSize;return l.info(`:<-- printable: ${i}, mIsPrPageKey: ${s}, bufferSize: ${n}`),l.info(":<--◀◀◀◀◀-◀◀◀◀◀-◀◀◀◀◀ 【End】to check printable: ◀◀◀◀◀-◀◀◀◀◀-◀◀◀◀◀"),this.updatePrintProgress(this.printable,this.mIsPrPageKey),this.mIsCheckingPrintable=false,null==e?void 0:e.respPkg})})}tryCheckPrintable(e,i){return t(this,void 0,void 0,function*(){if(this.isConnected){if(!(e&&e>0))return this.checkPrintable(i);for(let t=0;t<e;t++){const s=yield this.checkPrintable(i);if(s)return s;if(!this.isConnected)return l.warn(`---- tryCheckPrintable failed of tryTimes: [${t+1} - ${e}]: 设备已断开!`),s;l.warn(`---- tryCheckPrintable failed of tryTimes: [${t+1} - ${e}]`);}}else l.info("---- 设备连接已断开,停止打印机状态的检测!");})}checkAndSendPrintParams(e,i){return t(this,void 0,void 0,function*(){if(!this.isConnected)return;this.printStatus,Ze.Sending,this.mIsCheckingPrintable&&(yield this.waitPrintable()),this.mIsCheckingPrintable=true,this.mPrinterInfo.printable=255,l.info("▶▶▶▶▶ checkAndSendPrintParams: printable = 0xFF ◀◀◀◀◀");const t=new Fe;let s=e.printDarkness;return "number"==typeof s&&s>=Oe.Min&&s<=Oe.High&&t.pushPackage(Ge.CMD_DARKNESS,[s-1]),s=e.printSpeed,"number"==typeof s&&s>=_e.Min&&s<=_e.Max&&t.pushPackage(Ge.CMD_SPEED,[s-1]),s=e.gapType,"number"==typeof s&&s>=we.None&&s<=we.Trans&&t.pushPackage(Ge.CMD_GAP_TYPE,[s]),s=e.gapLength,"number"==typeof s&&s>0&&s<=Ke.MAX_EBV_VALUE&&t.pushPackage(Ge.CMD_GAP_LEN,Ue.fromEBV(s)),s=e.motorMode,"number"==typeof s&&s>=0&&t.pushPackage(Ge.CMD_MOTORMODE,[s]),s=e.autoPowerOffMins,"number"==typeof s&&s>0&&t.pushPackage(Ge.CMD_AUTOPOWEROFF,Ue.fromEBV(s)),t.pushPackage(Ge.CMD_BUFFER_SIZE),yield this.writeData(t.getAllBytes()),t.clearBuffer(),t.pushPackage(Ge.CMD_IS_PRINTABLE),t.pushPackage(Ge.CMD_BUFFER_SIZE),this.pushCommandRequest(Ge.CMD_BUFFER_SIZE,t.getAllBytes(),i||2e3).then(t=>{t||(this.mPrinterInfo.printable=-1,l.warn("---- checkAndSendPrintParams timeout!"));const e=t.resultInfo;return this.mIsCheckingPrintable=false,e.respPkg})})}printJob(t){return !!this.isConnected&&(this.mPrintJobList.push(t),t.jobPushed&&t.jobPushed(),this.mPrintStatus>=Ze.ReadyPrint&&!this.mPrintingJob&&(this.mPausedPageMap.clear(),this.popAndSendPrintJob()),true)}continuePrintJob(){return this.sendPausedPages()}cancelPrintJob(){if(this.printStatus===Ze.Paused){if(this.mPausedPageMap.size>0){const t=Array.from(this.mPausedPageMap.keys());l.log(`---- 清空暂存打印任务:${t.join(",")}`),this.mPausedPageMap.clear();}this.mPrintingMap.clear(),this.raisePrintStatusChanged(Ze.ReadyPrint);}else this.printStatus>Ze.ReadyPrint&&(this.raisePrintStatusChanged(Ze.Cancel),this.mPrintingMap.clear(),this.mPausedPageMap.clear());}backupPrintPages(...t){if(this.isPageKeySupported){if(this.mPrintingMap.size>0){for(const t of this.mPrintingMap.values())this.mPausedPageMap.set(t.pageKey,t);this.mPrintingMap.clear();}if(t.length>0)for(const e of t)this.mPausedPageMap.set(e.pageKey,e);const e=Array.from(this.mPausedPageMap.keys());l.warn(`#### #### 检测到打印机异常: printable = ${this.printable}`),l.info(`---- 打印任务已暂停,并已暂存未完成的打印任务:[${e.join(",")}]`);}}updatePrintProgress(t,e){const i=Array.from(this.mPrintingMap.keys()),s=Ze[this.mPrintStatus];if(l.log(`---- updatePrintProgress: printStatus = ${s}, pageKey = ${e}`),l.log(`---- mPrintingKeys: [${i.join(",")}], mDataSendMode: ${qe[this.mDataSendMode]}`),!(this.mPrintingMap.size<=0||t>=255)&&this.mPrintStatus>=Ze.ReadyPrint)if(t>=Ge.DZIP_PAGENOTREADY&&t<255)this.raisePrintStatusChanged(Ze.Paused),this.backupPrintPages();else if(t>=0){const s=new Map;if(this.isPageKeyEnable&&e>0)if(l.log(`---- <<< update print progress by pageKey>>>: printable = ${t}`),this.mPrintingMap.has(e)){const n=i[0];if(i.length>0){const r=i.join(",");for(const a of i){const i=a>=n?a:a+65534;i<e?(s.set(a,this.mPrintingMap.get(a)),this.mPrintingMap.delete(a),l.info(`---- updatePrintProgress: 检测到已完成任务(${a}),keys:[${r}]`)):i===e&&1!==t&&2!==t&&(s.set(a,this.mPrintingMap.get(a)),this.mPrintingMap.delete(a),l.info(`---- updatePrintProgress: 检测到可能已完成任务(${a}),keys:${r}`));}}}else this.mSendingPage&&this.mSendingPage.pageKey===e||l.warn(`---- 检测到无效的 pageKey: ${e}`);else if(this.isPageKeyEnable?l.warn("---- <<< update print progress by printable>>>: pageKey 丢失!"):l.log("---- <<< update print progress by printable>>>:"),1!==t&&2!==t)if(e>0&&this.mPrintingMap.has(e))this.mPrintingMap.has(e)&&(s.set(e,this.mPrintingMap.get(e)),this.mPrintingMap.delete(e));else if(e>0&&l.info(`---- 检测到无效的 pageKey: ${e}`),this.mPrintingMap.size>0){for(const t of this.mPrintingMap)s.set(t[0],t[1]);this.mPrintingMap.clear();}if(s.size>0){for(const i of s){const s=i[1],n=s.job;l.info(`---- 检测到已经打印完毕的打印任务[${i[0]}], jobId = ${n.jobId}`),n.onPagePrintComplete&&n.onPagePrintComplete({statusCode:Ee.OK,printable:t,pageKey:s.pageKey,pageKey2:e,pageIndex:s.pageIndex,printPages:s.printPages,copyIndex:s.copyIndex,printCopies:s.printCopies},n);}const i=Array.from(this.mPrintingMap.keys());l.info(`---- 剩余打印页面:[${i.join(",")}]`);}this.mPrintJobList.length<=0&&this.mPausedPageMap.size<=0&&(this.mPrintingMap.size<=0||0===t)&&this.raisePrintStatusChanged(Ze.ReadyPrint);}}addPrintPage(t){if(this.isPageKeySupported||this.printByPrintable){this.mPrintingMap.set(t.pageKey,t);const e=Array.from(this.mPrintingMap.keys());l.info(`---- addPrintPage[${t}]: keys = [${e.join(", ")}]`);}}sendPausedPages(){return t(this,void 0,void 0,function*(){if(this.mPausedPageMap.size<=0)return Ee.OK;let t=Ee.OK;const e=Array.from(this.mPausedPageMap.keys());l.info(`#### #### sendPausedPages: 继续打印暂存的打印任务: [${e.join(",")}]`);const i=Array.from(this.mPausedPageMap.values());for(this.mPausedPageMap.clear();i.length>0;){const e=i.shift();if(e){if(this.printStatus>=Ze.Cancel){l.log("---- 取消打印正在进行的暂存任务!"),t=Ee.ERROR_JOB_CANCELED,this.raisePrintStatusChanged(Ze.ReadyPrint);break}const s=`J${e.job.jobId}-P${e.pageIndex}-C${e.copyIndex}`;if(Ke.updatePageKey(e.dataList,e.pageKey),t=yield this.sendPrintPage(e,s),this.mSendingPage=void 0,t===Ee.ERROR_PRINTER_NOT_AVAILABLE){this.backupPrintPages(e,...i),e.job.onPageSendComplete&&e.job.onPageSendComplete(Object.assign(Object.assign({},e),{statusCode:t,printable:this.printable}));break}if(t!==Ee.OK){const i=e.job;this.raisePrintStatusChanged(Ze.Cancel),i.onPageSendComplete&&i.onPageSendComplete(Object.assign(Object.assign({},e),{statusCode:t,printable:this.printable})),i.onPagePrintComplete&&i.onPagePrintComplete(Object.assign(Object.assign({},e),{statusCode:t,printable:this.printable}),i);break}e.job.onPageSendComplete&&e.job.onPageSendComplete(Object.assign(Object.assign({},e),{statusCode:t,printable:this.printable})),e.copyIndex+1>=e.printCopies&&e.job.onJobSendComplete&&e.job.onJobSendComplete(t),this.raisePrintStatusChanged(Ze.Printing),this.addPrintPage(e);}}if(t!==Ee.OK&&t!==Ee.ERROR_PRINTER_NOT_AVAILABLE){let e=-1;for(const i of this.mPausedPageMap.values())i.job.jobId!==e&&(i.job.onPagePrintComplete&&i.job.onPagePrintComplete(Object.assign(Object.assign({},i),{statusCode:t,printable:this.printable}),i.job),e=i.job.jobId);this.mPausedPageMap.clear();}return (this.isPageKeySupported||this.printByPrintable)&&this.checkPrintProgress(this.mPageKey),t})}popAndSendPrintJob(){return t(this,void 0,void 0,function*(){let t=Ee.OK;const e=this.mPrintJobList.shift();if(this.mPrintingJob=e,!e)return this.isPageKeySupported||this.printByPrintable?(this.raisePrintStatusChanged(Ze.Printing),yield this.checkPrintProgress(this.mPageKey,true),this.raisePrintStatusChanged(Ze.ReadyPrint)):this.raisePrintStatusChanged(Ze.ReadyPrint),Ee.OK;const i=e.jobOptions.imageDataArray||[],s=e.jobOptions.rawData||[],n=s.length>0,r=s.length>0?s.length:i.length;let a=e.jobOptions.printCopies||e.jobOptions.copies;a="number"==typeof a&&a>1?a:1,this.printStatus>=Ze.Paused&&this.raisePrintStatusChanged(Ze.ReadyPrint);for(let o=0;o<r;o++){const h={pageKey:this.mPageKey,statusCode:t,printable:this.printable,pageIndex:o,printPages:r,copyIndex:0,printCopies:a};l.info(`【${e.jobId}】 - 开始生成打印数据 page: [${o+1} - ${r}]!`);const c=n?s[o]:Ke.encodeImageData(Object.assign(Object.assign({},e.jobOptions),{imageData:i[o],pageKey:this.mPageKey}),this.printerInfo);if(c.length<=0){t=Ee.ERROR_PARAM,e.onPageSendComplete&&e.onPageSendComplete(h);break}for(let i=0;i<a;i++){h.copyIndex=i,h.pageKey=this.mPageKey,h.printable=this.printable,this.printStatus>=Ze.Cancel&&(t=Ee.ERROR_JOB_CANCELED);const s=`J${e.jobId}-P${o}-C${i}`,n=Object.assign(Object.assign({},h),{pageKey:this.mPageKey,job:e,dataList:c});if(t===Ee.OK&&(i>0&&Ke.updatePageKey(c,this.mPageKey),l.info(`【${e.jobId}】 - 准备发送第[${i+1} / ${a}] 份打印数据!`),t=yield this.sendPrintPage(n,s),this.mSendingPage=void 0),t===Ee.OK)this.raisePrintStatusChanged(Ze.Printing);else if(t!==Ee.ERROR_PRINTER_NOT_AVAILABLE){e.onPageSendComplete&&e.onPageSendComplete(Object.assign(Object.assign({},h),{printable:this.printable,statusCode:t})),this.raisePrintStatusChanged(Ze.Cancel);break}if(n.printable=this.printable,t===Ee.ERROR_PRINTER_NOT_AVAILABLE?(this.backupPrintPages(n),l.info(`---------- 暂存打印数据:${s}, pageKey: ${this.mPageKey}`)):t===Ee.OK&&this.addPrintPage(n),e.onPageSendComplete&&e.onPageSendComplete(Object.assign(Object.assign({},h),{printable:this.printable,statusCode:t})),this.mPageKey=Le.nextPageKey(this.mPageKey),t!==Ee.OK&&t!==Ee.ERROR_PRINTER_NOT_AVAILABLE)break}if(t!==Ee.OK)break}return l.info(`【${e.jobId}】 - 当前打印任务处理完毕, statusCode = ${t}!`),e.onJobSendComplete&&e.onJobSendComplete(t),t!==Ee.OK?(this.mPrintJobList.splice(0),this.raisePrintStatusChanged(Ze.ReadyPrint),this.mPrintingJob=void 0,t):this.popAndSendPrintJob()})}sendPrintPage(e,i){return t(this,void 0,void 0,function*(){if(!this.isConnected)return Ee.ERROR_DISCONNECTED;const t=yield this.checkPrintProgress(e.pageKey),s=e.pageKey;if(t>0)return t;l.info("<<<<==== 【DeviceConnection.sendPrintPage】 ====>>>>"),l.info(`---- jobKey : ${i}`),l.info(`---- jobId : ${e.job.jobId}`),l.info(`---- pageKey : ${s}`),l.info(`---- printable : ${this.printable}`),l.info(`---- bufferSize : ${this.mBufferSize}`),l.info("===================================================="),this.raisePrintStatusChanged(Ze.Sending);const n=e.dataList;let r=0,a=0,o=0;const h=Date.now();for(this.mSendingPage=e;a<n.length;){const t=n[a];if(this.printStatus>=Ze.Cancel)return l.warn(` [${s}] - 打印任务已取消,当前打印进度:[${a+1} / ${n.length}]!`),Ee.ERROR_JOB_CANCELED;const e=`[${a+1} / ${n.length}]`;if(l.log(` **** [${s}] - 数据发送进度: ${e}, dataLen: ${t.length}, bufferSize: ${this.mBufferSize}`),r=this.mMinBufferSize>t.length?this.mMinBufferSize:t.length,this.mBufferSize<=0?o++:o=0,o>=5)return l.warn(` ==== [${s}] - 缓存连续5次为空,多通道打印机可能被占用!`),Ee.ERROR_DATA_SEND_ERROR;if(this.mBufferSize<r){if(l.info(" ==== 打印机缓存不够,重新检查缓存大小:minBufferSize",r),yield Le.sleep(300),!(yield this.tryCheckPrintable(3,3e3)))return l.warn(` ==== [${s}] - 缓存检查失败,bufferSize: ${this.mBufferSize}`),l.warn(` ==== [${s}] - 数据接收异常,停止发送!`),Ee.ERROR_DATA_SEND_ERROR;if(this.isPrinterAvailable)l.log(` ==== [${s}] - bufferSize: ${this.mBufferSize}`);else {if(this.printable!==Ge.DZIP_TPHTOOHOT)return l.warn(` ==== [${s}] - 打印机异常,printable: ${this.printable}`),Ee.ERROR_PRINTER_NOT_AVAILABLE;l.warn(` ==== [${s}] - 打印头温度过高!`),yield Le.sleep(1e3);}}else {const e=yield this.writeData(t,a);if(e.statusCode>0)return l.warn(` ==== [${s}] - 数据发送异常,停止发送![${Ee[e.statusCode]}]`,e),Ee.ERROR_DATA_SEND_ERROR;a++;}}const c=(Date.now()-h)/1e3;return l.info(`【DeviceConnection】sendPrintPage: 标签[${s}]数据发送完毕,数据发送时间:${c}s`),yield Le.sleep(50),this.mSendingPage=void 0,Ee.OK})}checkPrintProgress(e,i){return t(this,void 0,void 0,function*(){this.mCheckPrintingKeys.push(e);const t=this.mCheckPrintingKeys.join(",");let s=true;if(l.log(`#### checkPrintProgress[${e}](isEndPage: ${i}, printable: ${this.printable});`),l.log(`@---- checkKeys: [${t}], isPageKeyValid:${this.isPageKeyValid}`),this.mCheckPrintingKeys.length>1){for(l.log("@@1---- 【NEW】 检测到上一个打印页面正在检测打印进度,正在等待上一个检测任务,请稍后...");;)if(yield Le.sleep(10),this.mCheckPrintingKeys.length<=1){l.log("@@3---- 【NEW】 上一个正在检测的打印进度已结束,开始重新检测打印进度!");break}s=false;}if(s){if(!(yield this.tryCheckPrintable(3,3e3)))return l.warn(`【DeviceConnection: endPage=${i}】checkPrintProgress: 打印机异常,数据发送失败!`),this.mCheckPrintingKeys.shift(),Ee.ERROR_DATA_SEND_ERROR}let n=Ee.OK,r=0;for(;;){const t=this.printable;if(!this.isPrinterAvailable){n=this.printable===Ge.DZIP_JOBCANCELED?Ee.ERROR_PRINTER_CANCELED:Ee.ERROR_PRINTER_NOT_AVAILABLE;break}if(this.mCheckPrintingKeys.length>1){l.log("@@2----【OLD】 检测到新的打印状态检测任务,已停止当前打印状态的检测!");break}if(this.mPrintingMap.size<=0)break;if(this.printByPrintable){if(t!==Ge.DZIP_ISPRINTING&&t!==Ge.DZIP_ISROTATING)break}else {if(!this.isPageKeySupported)break;if(this.isPageKeyValid&&!i){if((e>this.mIsPrPageKey?e:e+65534)-this.mIsPrPageKey<=1)break;if(t<=0){if(l.log(`checkPrintProgress: 检测到马达转动已停止! isMotorStoped = ${r}`),r>5){l.warn("---- checkPrintProgress: 检测到马达长时间没有转动,打印机状态检测自动停止!");break}r++;}}else {if(t!==Ge.DZIP_ISPRINTING&&t!==Ge.DZIP_ISROTATING)break;t>0?l.log(`---- isPageKeySupported: true, printable: ${t}, 状态异常!!!`):l.log("---- isPageKeySupported: true, 马达不转了!!!");}}if(yield Le.sleep(300),!this.isConnected){l.log(`---- checkPrintProgress: printable = ${this.printable}, 打印机连接已断开,无法继续检测!`),n=0===t?Ee.OK:Ee.ERROR_DISCONNECTED;break}if(!(yield this.tryCheckPrintable(3,3e3))){n=Ee.ERROR_DATA_SEND_ERROR;break}}return this.mCheckPrintingKeys.shift(),n})}}class oi{static createInstance(t){if(t&&!(t.length<14))return 53===t[0]&&51===t[1]?new oi(t):void 0}static uuidToString(t,e){if(!t)return "";const i=[];e&&i.push("0x");for(let e=t.length-1;e>=0;--e)i.push(Le.toHexByteString(t[e]));return i.join("")}get deviceMainType(){return this.data[2]}get suggestedMtuI(){return 20*this.data[3]}get suggestedWaitI(){return this.data[4]}get suggestedMtuA(){return 20*this.data[5]}get suggestedWaitA(){return this.data[6]}get suggestedMtuH(){return this.data.length>=16?10*this.data[14]:this.suggestedMtuA}get suggestedWaitH(){return this.data.length>=16?this.data[15]:this.suggestedWaitA}get suggestedUUID(){return oi.uuidToString(this.data.slice(7,11))}get locateArea(){const t=this.data[11];return t>=P.A&&t<=P.Z?String.fromCharCode(t):""}get deviceFlags(){return Ue.toShort(this.data[12],this.data[13])}constructor(t){this.data=t;}toString(){return `[${Le.arrayBufferToHex16(this.data,",")}]`}}!function(t){t[t.BROADCAST=1]="BROADCAST",t[t.READ=2]="READ",t[t.WRITE_NO_RESPONSE=4]="WRITE_NO_RESPONSE",t[t.WRITE=8]="WRITE",t[t.NOTIFY=16]="NOTIFY",t[t.INDICATE=32]="INDICATE";}(Ye||(Ye={})),function(t){t[t.BROADCAST=1]="BROADCAST",t[t.READ=2]="READ",t[t.WRITE_NO_RESPONSE=4]="WRITE_NO_RESPONSE",t[t.WRITE=8]="WRITE",t[t.NOTIFY=16]="NOTIFY",t[t.INDICATE=32]="INDICATE";}(Qe||(Qe={}));class hi extends ai{get device(){return this.mDevice}get adapter(){return this.mAdapter}get isConnected(){return this.mConnected}get requestMTUs(){return this.mRequestMTUs}get writeWaitMSs(){return this.mWriteWaitMSs}get enableFlowControl(){return "boolean"!=typeof this.connectInfo.enableFlowControl||this.connectInfo.enableFlowControl}get platform(){try{if(this.mDeviceInfo)return this.mDeviceInfo.platform||this.mDeviceInfo.system;if(navigator)return navigator.userAgent}catch(t){l.warn(t);}return ""}get isHarmonyOS(){var t,e;return Le.isHarmonyOS((null===(t=this.mDeviceInfo)||void 0===t?void 0:t.platform)||(null===(e=this.mDeviceInfo)||void 0===e?void 0:e.system))}get printerInfo(){var t,e;return Object.assign(Object.assign(Object.assign({},this.device),this.mPrinterInfo),{writeCharacteristicId:null===(t=this.mWriteCharacteristic)||void 0===t?void 0:t.uuid,notifyCharacteristicId:null===(e=this.mNotifyCharacteristic)||void 0===e?void 0:e.uuid})}get connectInfo(){return this.mInitOptions}constructor(t,e,i){if(super(t,e,i),this.mRequestMTUs=0,this.mWriteWaitMSs=0,this.mWriteExtendWaits=0,this.mReservedMTUs=0,this.mUserWriteWaits=0,this.mUserRequestMTUs=0,this.mDFType="",this.mFcCredit=0,this.mFcMTU=0,this.mFcCanUsed=false,e&&"function"==typeof e.getDeviceInfo&&(this.mDeviceInfo=e.getDeviceInfo()),i){"number"==typeof i.writeWaits&&(this.mUserWriteWaits=i.writeWaits),"number"==typeof i.requestMTUs&&(this.mUserRequestMTUs=i.requestMTUs);const t=i.writeExtendWaits;"number"==typeof t&&t>=0&&t<=30&&(this.mWriteExtendWaits=t),i.reservedMTUs&&i.reservedMTUs>3&&(this.mReservedMTUs=i.reservedMTUs);}}onFcDataReceived(t){if(!t||t.length<=0)return;const e=Le.arrayBufferToHex16(t,",");if(1===t[0]&&2===t.length)if(this.mFcCredit<0){this.mFcCredit=t[1];const i=this.enableFlowControl;l.info(`---- onFcDataReceived: mFcCredit = ${t[1]}, data = 0x[${e}]`),i&&this.mFcCanUsed?l.info(`---- onFCDataReceived: 侦测到信用流控初始令牌个数,mFcCanUsed: ${this.mFcCanUsed}`):i?l.warn(`---- onFCDataReceived: 信用流控响应时间超时,mFcCanUsed: ${this.mFcCanUsed}`):l.info(`---- onFCDataReceived: 用户未启用信用流控功能,enableFlowControl: ${i}`);}else this.mFcCredit+=t[1];else 2===t[0]&&3===t.length?(this.mFcMTU=Ue.toShort(t[1],t[2]),l.info(`---- mFcMTU = ${this.mFcMTU}, data = 0x[${e}]`)):l.warn(`---- 检测到未识别的信用流控指令:0x[${e}]`);}parseMTUInfo(t,e){var i;const s=this.platform,n=Le.isIOS(s),r=Le.isHarmonyOS(s);if(this.mRequestMTUs=123,this.mWriteWaitMSs=n?20:10,this.mDFType="",e){const t=e instanceof Uint8Array?e:new Uint8Array(e),i=new Ue(Ge.CMD_NULL,Array.from(t)).popString().toUpperCase();l.info(`---- 【BleConnection】parseMTUInfo by DFInfo: ${i}, platform = ${s}`);const n=i.lastIndexOf("-");this.mDFType=n>=0?i.substring(n+1):"";}if(t)return l.info(`【BleConnection】parseMTUInfo by factoryInfo: platform = ${null===(i=this.mDeviceInfo)||void 0===i?void 0:i.platform}`),n?(l.info(`---- factoryInfo.suggestedMtuI : ${t.suggestedMtuI}`),l.info(`---- factoryInfo.suggestedWaitI : ${t.suggestedWaitI}`),this.mRequestMTUs=t.suggestedMtuI+3,this.mWriteWaitMSs=t.suggestedWaitI):r?(l.info(`---- factoryInfo.suggestedMtuH : ${t.suggestedMtuH}`),l.info(`---- factoryInfo.suggestedWaitH : ${t.suggestedWaitH}`),this.mRequestMTUs=t.suggestedMtuH+3,this.mWriteWaitMSs=t.suggestedWaitH,this.mRequestMTUs>500?this.mWriteWaitMSs=20:this.mWriteWaitMSs=25):(l.info(`---- factoryInfo.suggestedMtuA : ${t.suggestedMtuA}`),l.info(`---- factoryInfo.suggestedWaitA : ${t.suggestedWaitA}`),this.mRequestMTUs=t.suggestedMtuA+3,this.mWriteWaitMSs=t.suggestedWaitA),this.mRequestMTUs>512&&(this.mRequestMTUs=512),true;if(this.mDFType){if("MT_DF1"===this.mDFType)this.mRequestMTUs=123,this.mWriteWaitMSs=n?18:15,r&&(this.mWriteWaitMSs=23);else {const t=/^DF(\d+)$/.exec(this.mDFType);if(t){const e=parseInt(t[1]);5&~e?4&e?(this.mRequestMTUs=183,this.mWriteWaitMSs=n?10:3,r&&(this.mWriteWaitMSs=23)):2&e?(this.mRequestMTUs=123,this.mWriteWaitMSs=n?20:10,r&&(this.mWriteWaitMSs=25)):1&e&&(this.mRequestMTUs=183,this.mWriteWaitMSs=n?18:15,r&&(this.mWriteWaitMSs=23)):(this.mRequestMTUs=503,this.mWriteWaitMSs=7,r&&(this.mWriteWaitMSs=20));}}return true}{this.mUserRequestMTUs>=23&&(this.mRequestMTUs=this.mUserRequestMTUs),this.mUserWriteWaits>0&&(this.mWriteWaitMSs=this.mUserWriteWaits);const t=e?Le.arrayBufferToHex16(e,""):"undefined";return l.warn(`---- prepareRequestMTU : DF信息获取失败, buffer = [${t}]`),l.info(`---- mRequestMTUs : ${this.mRequestMTUs}`),l.info(`---- mWriteWaitMSs : ${this.mWriteWaitMSs}`),l.info(`---- mUserRequestMTUs : ${this.mUserRequestMTUs}`),l.info(`---- mUserWriteWaits : ${this.mUserWriteWaits}`),l.info(`---- mWriteExtendWaits : ${this.mWriteExtendWaits}`),l.info(`---- mReservedMTUs : ${this.mReservedMTUs}`),false}}getGATTServices(e){return t(this,void 0,void 0,function*(){const t=[];if(!this.isConnected)return l.warn("---- 打印机链接已断开!"),t;for(let i=0;i<5&&this.mConnected;i++){const s=yield this.adapter.getGATTServices({deviceId:e});if(s&&s.length>0){l.info(`---- 【getGATTServices】: 第 [${i+1} / 5] 获取成功!`),t.push(...s);break}l.warn(`---- 【getGATTServices】: 第 [${i+1} / 5] 获取失败!`),yield Le.sleep(300);}return t})}setBleMtu(t){const e="MT_DF1"===this.mDFType||"DF1"===this.mDFType||"DF2"===this.mDFType;return this.adapter.setBleMtu({deviceId:t,mtu:this.mRequestMTUs,waits:this.mWriteWaitMSs,chipType:this.mDFType,required:e}).then(t=>{var i;return "number"==typeof t.waits&&t.waits>0&&(this.mWriteWaitMSs=t.waits),t.status>0?this.mDFType&&e&&(this.mRequestMTUs=23):"number"==typeof t.mtu&&(this.mRequestMTUs=t.mtu>23?t.mtu:23),l.info(`---- setBleMtu.resp.status : ${t.status}`),l.info(`---- setBleMtu.resp.mtu : ${t.mtu}`),l.info(`---- requestMTU.mDFType : ${this.mDFType}`),l.info(`---- requestMTU.mRequestMTUs : ${this.mRequestMTUs}`),l.info(`---- requestMTU.mWriteWaitMSs : ${this.mWriteWaitMSs}`),l.info(`---- requestMTU.mWriteExtendWaits : ${this.mWriteExtendWaits}`),l.info(`---- requestMTU.mReservedMTUs : ${this.mReservedMTUs}`),l.info(`-----platform : ${null===(i=this.mDeviceInfo)||void 0===i?void 0:i.platform}`),0!==t.status||Le.sleep(100,true)})}readDFInfo(e,i){return t(this,void 0,void 0,function*(){var t;const s="180A",n="2A24";l.log(`【BleConnection】readDFInfo from serviceID: ${s} dfInfoID: ${n}`);const r=i.find(t=>Le.isMatchedUUID(t,s));if(!r)return;const a=null===(t=(yield this.adapter.getGATTCharacteristics({deviceId:e,serviceId:r})).find(t=>Le.isMatchedUUID(t.uuid,n)))||void 0===t?void 0:t.uuid;if(!a)return void l.warn(`【BleConnection】readDFInfo: 未检测到[${n}]所对应的特征值!`);yield Le.sleep(30);const o=yield this.adapter.read({deviceId:e,serviceId:r,characteristicId:a});return 0===o.statusCode?"string"==typeof o.resultInfo?Le.hex16ToArrayBuffer(o.resultInfo):o.resultInfo:void 0})}readFactoryInfo(e,i){return t(this,void 0,void 0,function*(){var t;const s="180A",n="2A28";l.log(`【BleConnection】readFactoryInfo from serviceID: ${s} factoryInfoID: ${n}`);const r=i.find(t=>Le.isMatchedUUID(t,s));if(!r)return;const a=null===(t=(yield this.adapter.getGATTCharacteristics({deviceId:e,serviceId:r})).find(t=>Le.isMatchedUUID(t.uuid,n)))||void 0===t?void 0:t.uuid;if(!a)return void l.warn(`【BleConnection】readFactoryInfo: 未检测到[${n}]所对应的特征值!`);yield Le.sleep(30);const o=yield this.adapter.read({deviceId:e,serviceId:r,characteristicId:a});return 0===o.statusCode?"string"==typeof o.resultInfo?Le.hex16ToArrayBuffer(o.resultInfo):o.resultInfo:void 0})}getValidateCharacteristic(e,i){return t(this,void 0,void 0,function*(){const t=yield this.adapter.getGATTCharacteristics({deviceId:e,serviceId:i}),s=[];for(const e of t)if(0!==(e.properties&Ye.NOTIFY)&&0===(e.properties&Ye.INDICATE)&&(Le.isMatchedUUID(e.uuid,"FF03")?(s[2]=e,l.log(`---- 检测到 notify FC通道: {uuid: ${e.uuid}, properties:${e.properties}}`)):s[0]||(s[0]=e,l.log(`---- 检测到 notify DT通道: {uuid: ${e.uuid}, properties:${e.properties}}`))),0===(e.properties&Ye.WRITE)&&0===(e.properties&Ye.WRITE_NO_RESPONSE)||(Le.isMatchedUUID(e.uuid,"FF03")?(s[3]=e,l.log(`---- 检测到 write FC通道: {uuid: ${e.uuid}, properties:${e.properties}}`)):s[1]||(Le.isMatchedUUID(i,"FFE0")?Le.isMatchedUUID(e.uuid,"FFE1")&&(s[1]=e):s[1]=e,s[1]&&l.log(`---- 检测到 write WT通道: {uuid: ${e.uuid}, properties:${e.properties}}`))),s[0]&&s[1]&&s[2])break;return s[0]&&!s[0].serviceId&&(s[0].serviceId=i),s[1]&&!s[1].serviceId&&(s[1].serviceId=i),s[2]&&!s[2].serviceId&&(s[2].serviceId=i),s[3]&&!s[3].serviceId&&(s[3].serviceId=i),s})}getPrintCharacteristics(e,i,s){return t(this,void 0,void 0,function*(){let t,n,r,a;if(l.log(`---- suggestedService = ${s}`),s&&i.length>0&&(s=s.toUpperCase(),s=i.find(t=>Le.getFullUUID(t).startsWith(s))||""),s){const t=yield this.getValidateCharacteristic(e,s);if(t[0]&&t[1])return l.info(`---- 通过推荐的服务[${s}] 检测到了有效的读写通道!`),{notifyId:t[0],writeId:t[1],fcNotifyId:t[2],fcWriteId:t[3]};l.warn(`---- 通过推荐的服务[${s}] 未检测到有效的读写通道!`);}for(const s of i)if(Le.isSupportedService(s)){l.log(`---- 检测到可用 service: ${s}`);const i=yield this.getValidateCharacteristic(e,s);if(!t&&i[0]&&(t=i[0]),!n&&i[1]&&(n=i[1]),!r&&i[2]&&(r=i[2]),!a&&i[3]&&(a=i[3]),t&&n)return {notifyId:t,writeId:n,fcNotifyId:r,fcWriteId:a};l.log(`---- service ${s} 读写特征值不全!`);}else l.log(`---- 不可用 serviceId: ${s}`);return l.warn("---- 未检测到有效的打印通道!"),{}})}connect(e){return t(this,void 0,void 0,function*(){l.info(`---- BleConnection.connect(${this.deviceName}[${this.deviceId}])`);const t=this.device,i="number"==typeof e.tryTimes&&e.tryTimes>0?e.tryTimes:5;let s=0;const n={value:false},r=e.timeout||5e3;setTimeout(()=>{n.value=true;},r),this.mConnected=false;for(let a=0;a<i;a++){a>0&&(yield Le.sleep(100));if(s=(yield this.adapter.connect(Object.assign(Object.assign({},Le.filter_NoFuncAndNone(e)),{deviceId:t.deviceId,timeout:r,connectionStateChange:t=>{t.deviceId!==this.deviceId||t.connected||(this.disconnect(),e.connectionStateChange&&e.connectionStateChange(t));}}))).statusCode,s<=0){this.mConnected=true,l.info(`---- 【createBleConnection】: 第 [${a+1} / ${i}] 次链接成功!`);break}{const t=n.value?"超时":"失败";if(l.warn(`---- 【createBleConnection】: 第 [${a+1} / ${i}] 次链接${t}!`),n.value)break;if(s===Ee.ERROR_NO_BRIDGE)break}}return s>0?(this.raisePrintStatusChanged(Ze.None),Le.failResult({statusCode:s>Ee.ERROR_OTHER?s:Ee.ERROR_CONNECT_FAILED,resultInfo:"打印机链接失败!"})):(this.raisePrintStatusChanged(Ze.Connected),{statusCode:0,resultInfo:"OK"})})}disconnect(){return t(this,void 0,void 0,function*(){const t=this.deviceName,e=this.deviceId;return l.info(`---- BleConnection.disconnect(${e}), mConnected = ${this.mConnected}`),!this.mConnected||(this.mNotifyCharacteristic&&(yield this.adapter.notify({deviceId:e,serviceId:this.mNotifyCharacteristic.serviceId,characteristicId:this.mNotifyCharacteristic.uuid,state:false})),yield Le.sleep(10),this.mFcNotifyCharacteristic&&(yield this.adapter.notify({deviceId:e,serviceId:this.mFcNotifyCharacteristic.serviceId,characteristicId:this.mFcNotifyCharacteristic.uuid,state:false})),yield this.adapter.disconnect({name:t,deviceId:e||""}),this.mConnected=false,this.mWriteCharacteristic=void 0,this.mNotifyCharacteristic=void 0,this.raisePrintStatusChanged(Ze.None),l.info("---- 打印机断开成功!"),true)})}notifyData(e){return t(this,void 0,void 0,function*(){var t,i;const s=this.device||{},n=s.deviceId,r=s.advertisData?new Uint8Array(s.advertisData):void 0,a=r?Le.arrayBufferToHex16(r,","):"undefined";l.info(`---- BleConnection.notifyData: advertiseData = [${a}]`),this.mFactoryInfo=oi.createInstance(r),yield Le.sleep(100);const o=this.mFactoryInfo?this.mFactoryInfo.suggestedUUID:"",h=(yield this.getGATTServices(n)).map(t=>"string"==typeof t?t:(null==t?void 0:t.uuid)||"");if(yield Le.sleep(20),l.info(`---- serviceList.length: ${null==h?void 0:h.length}`),h.length<=0&&!o)return l.warn("---- 打印机服务列表获取失败!"),{statusCode:Ee.ERROR_GET_SERVICE};const c=yield this.getPrintCharacteristics(n,h||[],o),d=c.notifyId,u=c.writeId,g=c.fcNotifyId,p=c.fcWriteId;if(d&&u){l.info(`---- notifyId [${d.serviceId}]: ${d.uuid}`),l.info(`---- writeId [${u.serviceId}]: ${u.uuid}`);const s=yield this.readDFInfo(n,h||[]);if(!this.mFactoryInfo){const t=yield this.readFactoryInfo(n,h);if(t&&(this.mFactoryInfo=oi.createInstance(t),!this.mFactoryInfo)){const e=Le.arrayBufferToHex16(t);l.info(`【BleConnection】readFactoryInfo: 数据格式异常! data = [${e}]`);}}this.parseMTUInfo(this.mFactoryInfo,s),l.info(`---- ---- requestMtu: ${this.mRequestMTUs} (byte)`),l.info(`---- ---- writeWaits: ${this.mWriteWaitMSs} (ms)`),this.mWriteCharacteristic=u,this.mNotifyCharacteristic=d,this.mFcNotifyCharacteristic=void 0,this.mFcWriteCharacteristic=void 0,this.mFcMTU=0,this.mFcCredit=-1,this.mFcCanUsed=false;const r=yield this.adapter.notify({deviceId:n,serviceId:d.serviceId,characteristicId:d.uuid,state:true,dataReceived:t=>{"string"==typeof t&&(t=Le.hex16ToArrayBuffer(t)),e(t);}});if(yield Le.sleep(60),g&&this.enableFlowControl){this.mFcCanUsed=true;const t=Le.getShortUUID((null==g?void 0:g.uuid)||"");0===(yield this.adapter.notify({deviceId:n,serviceId:g.serviceId,characteristicId:g.uuid,state:true,dataReceived:t=>{"string"==typeof t&&(t=Le.hex16ToArrayBuffer(t)),this.onFcDataReceived(t);}})).statusCode?(l.info(`==== 【信用流控特征值[${t}]侦听启动成功!】 ====`),l.info(`---- 信用流控启用成功!enableFlowControl: ${this.enableFlowControl}`),this.mFcNotifyCharacteristic=g,this.mFcWriteCharacteristic=p):this.mFcCanUsed=false,yield Le.sleep(60);}return yield this.setBleMtu(n),{statusCode:r.statusCode,resultInfo:{dfType:this.mDFType,requestMTUs:this.mRequestMTUs,writeWaits:this.mWriteWaitMSs,fcMTU:this.mFcMTU,fcCredit:this.mFcCredit,fcNotifyCharacter:null===(t=this.mFcNotifyCharacteristic)||void 0===t?void 0:t.uuid,fcWriteCharacter:null===(i=this.mFcWriteCharacteristic)||void 0===i?void 0:i.uuid}}}return l.warn("---- 未检测到有效的服务!"),{statusCode:Ee.ERROR_GET_CHARACTERISTIC}})}loadPrinterInfo(){return this.mFcCredit<=0&&(this.mFcCanUsed=false),super.loadPrinterInfo()}writeDataWithFCCharacteristic(e,i,s){return t(this,void 0,void 0,function*(){var t,n;const r=this.mReservedMTUs>3&&this.mReservedMTUs<23?this.mReservedMTUs:3;i>512&&(i=512);const a=i-r,o=e.length;let h,c=0,d=0;for(let i=0,r=0;i<o;)if(this.mFcCredit<=0){if(c>=1e3)return l.warn("---- 特征值流控处理令牌长时间无响应,停止数据的写入操作!"),this.mFcCanUsed=false,{statusCode:Ee.ERROR_RESPONSE_TIMEOUT,resultInfo:"流控令牌无响应!"};yield Le.sleep(1),c++;}else {const o=this.mFcCredit;this.mFcCredit--,h=i+a<e.length?e.slice(i,i+a):e.slice(i),this.mWriteExtendWaits>0&&(yield Le.sleep(this.mWriteExtendWaits));const u=yield this.adapter.write({deviceId:this.deviceId||"",serviceId:(null===(t=this.mWriteCharacteristic)||void 0===t?void 0:t.serviceId)||"",characteristicId:(null===(n=this.mWriteCharacteristic)||void 0===n?void 0:n.uuid)||"",value:h,pkgIndex:s,subPkgIndex:r,enableFC:true});if(0!==u.statusCode){if(this.mFcCredit++,d++,l.warn(`---- <<<信用流控>>>数据发送失败,开始重新发送数据! currCredit: ${o}`),l.warn(`---- mFcMTU: ${this.mFcMTU}, mFcCredit: ${this.mFcCredit}`),l.warn(`---- writeMTU: ${a}, checkTimes: ${c}, sendTimes: ${d}`),d>=3)return u;yield Le.sleep(10);}else i+=a,r++,d=0;c=0;}return {statusCode:Ee.OK}})}writeDataWithDefaultFC(e,i,s){return t(this,void 0,void 0,function*(){var t,n;i>500&&(i=500);const r=i-3,a=e.length,o=this.mWriteWaitMSs+this.mWriteExtendWaits;let h,c={statusCode:Ee.OK};for(let i=0,d=0,u=0;i<a;)if(c={statusCode:Ee.ASYNC_WAIT},h=i+r<e.length?e.slice(i,i+r):e.slice(i),this.adapter.write({deviceId:this.deviceId||"",serviceId:(null===(t=this.mWriteCharacteristic)||void 0===t?void 0:t.serviceId)||"",characteristicId:(null===(n=this.mWriteCharacteristic)||void 0===n?void 0:n.uuid)||"",value:h,pkgIndex:s,subPkgIndex:u,writeWaits:o,complete:t=>{c=t;}}),yield Le.sleep(o>0?o:1),c.statusCode>Ee.OK){if(d++,l.warn(`---- 打印数据发送失败,正在重新发送打印数据[P ${s} - SUP ${u}], tryTimes = [${d} / 3]`),l.warn(`---- DFType: ${this.mDFType}, mtuSize: ${r} + 3, waitTimes: ${o}`),d>=3)break;yield Le.sleep(o);}else c.statusCode,Ee.OK,d=0,i+=r,u++;return c})}writeData(e,i){return t(this,void 0,void 0,function*(){return this.mBufferSize-=e.length,this.enableFlowControl&&this.mFcCanUsed&&this.mFcMTU>0?this.writeDataWithFCCharacteristic(e,this.mFcMTU,i):this.writeDataWithDefaultFC(e,this.mRequestMTUs,i)})}sendPrintPage(t,e){return l.info("<<<<==== 【BleConnection.sendPrintPage】 ====>>>>"),l.info(`---- mRequestMTUs : ${this.mRequestMTUs}`),l.info(`---- mWriteWaitMSs : ${this.mWriteWaitMSs}`),l.info(`---- mWriteExtendWaits : ${this.mWriteExtendWaits}`),l.info(`---- enableFlowControl : ${this.enableFlowControl}`),l.info(`---- mFCCanUsed : ${this.mFcCanUsed}`),l.info(`---- mFcMTU : ${this.mFcMTU}`),l.info(`---- mFcCredit : ${this.mFcCredit}`),l.info("================================================="),super.sendPrintPage(t,e)}}class ci{static getInstance(){return !this._instance&&this.isSupported()&&(this._instance=new ci),this._instance}static isSupported(){try{return navigator&&"bluetooth"in navigator}catch(t){return l.info("Catch Exception from WebBleAdapter.isSupported: ",t),false}}constructor(){this.mDeviceMap=new Map,this.mConnectMap=new Map,this.mShowWriteLog=false,ci.isSupported()?(this.mBluetooth=navigator.bluetooth,window&&window.addEventListener("error",t=>{l.warn(t.message+" (Your browser may not support this feature.)",t),t.preventDefault();})):l.warn("---- 当前环境不支持 WebBluetooth API 接口!");}authorize(t){return new Promise(e=>{Le.success("OK",t,e);})}watchAdvertisements(t,e){return new Promise((i,s)=>{const n=null==t?void 0:t.id,r={name:t.name||"",deviceId:t.id,type:ze.WEB_BLE,gattDevice:t};if("function"==typeof t.watchAdvertisements&&n){const a=new Map,o=e=>{l.info(`---- watchAdvertisements: 检测到设备[${e.device.name}]的广播信息:`,e),l.info("---- event.manufacturerData: ",e.manufacturerData),l.info("---- event.serviceData : ",e.serviceData),e.device&&e.device.id===n&&(t.removeEventListener("advertisementreceived",o),h.abort(),a.set(n,r),i(r));};l.info(`---- 【Start】advertisementreceived: ${t.name}`);const h=new AbortController;t.addEventListener("advertisementreceived",o),t.watchAdvertisements({signal:h.signal}).catch(t=>{l.warn("---- advertisementreceived.fail: ",t);}),setTimeout(()=>{a.get(n)||(t.removeEventListener("advertisementreceived",o),h.abort(),l.info("---- watchAdvertisements: 设备检测超时,未检测到设备的广播信息!"),s(r));},e||1500);}else n?(l.warn('---- watchAdvertisements: 当前环境不支持 "watchAdvertisements" 接口!'),i(r)):(l.warn("---- watchAdvertisements: 设备异常!",t),s(r));})}openAdapter(t){const e=t||{};return new Promise(t=>{if(!this.mBluetooth){const i="当前环境不支持 WebBluetooth 功能!";return l.warn(`---- ${i}`),Le.complete(Ee.ERROR_UN_SUPPORTED,i,e,t)}Le.success(true,e);})}closeAdapter(){return Promise.resolve({statusCode:0})}requestDevice(e){return t(this,void 0,void 0,function*(){const i=e||{};if(!this.mBluetooth){const t="当前环境不支持 WebBluetooth 功能!";return l.warn(`---- ${t}`),Le.complete(Ee.ERROR_UN_SUPPORTED,[],e)}let s=i.bleFilters?i.bleFilters.split(/[;]/).filter(t=>!!t):[];return s.length<=0?(s.push("DT"),s.push("DP"),s.push("P")):s.length<=1&&"*"===s[0].trim()&&(s=[]),l.info("【BLE_Request】requestDevice: ",e),l.info(`---- moduleList: [${s.join(", ")}], acceptAllDevices = ${s.length<=0}`),this.mBluetooth.requestDevice({optionalServices:["49535343-fe7d-4ae5-8fa9-9fafd205e455","0000180a-0000-1000-8000-00805f9b34fb","0000ff00-0000-1000-8000-00805f9b34fb","0000ff10-0000-1000-8000-00805f9b34fb"],acceptAllDevices:s.length<=0,filters:s.length<=0?void 0:s.map(t=>({namePrefix:t}))}).then(e=>t(this,void 0,void 0,function*(){l.info("---- 【BLE_Response】 requestDevice.success:",e),this.mDeviceMap.set(e.id,e);const t=[{name:e.name||"",deviceId:e.id,gattDevice:e,type:ze.WEB_BLE}];return i.deviceFound&&i.deviceFound(t),i.adapterStateChange&&i.adapterStateChange({discovering:false}),Le.success(t,i)})).catch(t=>(l.warn("---- 【BLE_Response】 requestDevice.fail:",t),i.adapterStateChange&&i.adapterStateChange({discovering:false}),Le.complete(Ee.ERROR_CANCEL,[],e)))})}startDiscovery(e){return t(this,void 0,void 0,function*(){const t=e||{};if(!this.mBluetooth){const t="当前环境不支持 WebBluetooth 功能!";return l.warn(`【BLE_Request.error】 startDiscovery: ${t}`,e),Le.complete(Ee.ERROR_UN_SUPPORTED,t,e)}return l.info("【BLE_Request】 startDiscovery: ",e),"function"==typeof this.mBluetooth.getDevices?this.getDevices(e).then(i=>{const s=i.resultInfo||[];return t.deviceFound&&t.deviceFound(s),t.adapterStateChange&&t.adapterStateChange({discovering:false}),Le.success(s,e)}):this.requestDevice(e)})}stopDiscovery(t){return new Promise(e=>{Le.success(true,t,e);})}getDevices(e){return t(this,void 0,void 0,function*(){if(!this.mBluetooth){const t="当前环境不支持 WebBluetooth 功能!";return l.warn(`【BLE_Request】 getDevices: ${t}`),Le.complete(Ee.ERROR_UN_SUPPORTED,[],e)}return "function"!=typeof this.mBluetooth.getDevices?(l.warn("---- navigator.bluetooth.getDevices() 方法不可用,无法获取已配对的蓝牙设备列表!"),Le.onResult({statusCode:Ee.ERROR_UN_SUPPORTED,resultInfo:[],errMsg:"navigator.bluetooth.getDevices() 方法不可用!"},e)):(console.log("【BLE_Request】getDevices: ",e),navigator.bluetooth.getDevices().then(t=>(l.info("---- 【BLE_Response】getDevices.success:",t),this.mDeviceMap.clear(),Le.success([],e))).catch(t=>(l.info("---- 【Response】getFoundDevices.fail:",t),Le.onResult({statusCode:Ee.ERROR_NO_PRINTER,errMsg:t.message||"未找到任何蓝牙设备!",resultInfo:[]},e))))})}connect(e){return t(this,void 0,void 0,function*(){const t=e||{},i=t.deviceId;if(!i)return l.warn(`---- 参数错误,未指定目标设备(${i})[${t.name||""}]!`),Le.complete(Ee.ERROR_PARAM,Ee.ERROR_NO_PRINTER,t);const s=this.mDeviceMap.get(i);if(!s)return l.warn(`---- 未检测到目标蓝牙设备(${i})[${t.name||""}]!`),Le.complete(Ee.ERROR_NO_PRINTER,Ee.ERROR_NO_PRINTER,t);if(!s.gatt)return l.warn("---- 未检测到 gattDevice.gatt 对象!",e),Le.complete(Ee.ERROR_PARAM,Ee.ERROR_PARAM,t);if(s.gatt.connected)return l.info("---- 打印机已连接 ----"),Le.success("OK",t);try{return l.info("### 【Request】 device.gatt.connect()",s),s.gatt.connect().then(e=>{if(l.info(`---- 【BLE_Response.success】device.gatt.connect[${e.connected}]:`,e),e.connected){let n=!0;return this.mConnectMap.set(i,{deviceId:i,device:s,gattServer:e,notifyCharacteristicMap:new Map}),this.mConnectionStateChange&&(s.removeEventListener("gattserverdisconnected",this.mConnectionStateChange),this.mConnectionStateChange=void 0),this.mConnectionStateChange=e=>{var i,r;l.warn("---- gattDevice.gattserverdisconnected: 打印机链接已断开!"),l.warn(`---- gattDevice.connected = ${null===(i=s.gatt)||void 0===i?void 0:i.connected}, connecting = ${n}`),this.mConnectionStateChange&&(s.removeEventListener("gattserverdisconnected",this.mConnectionStateChange),this.mConnectionStateChange=void 0),"function"!=typeof t.connectionStateChange||n||t.connectionStateChange({deviceId:s.id,connected:(null===(r=s.gatt)||void 0===r?void 0:r.connected)||!1});},s.addEventListener("gattserverdisconnected",this.mConnectionStateChange),new Promise(e=>{setTimeout(()=>{var i;n=!1,(null===(i=s.gatt)||void 0===i?void 0:i.connected)?Le.success("OK",t,e):Le.complete(Ee.ERROR_CONNECT_FAILED,"打印机链接失败!",t,e);},150);})}return Le.complete(Ee.ERROR_CONNECT_FAILED,"",t)}).catch(e=>(l.warn("【BLE_Response.fail 】 device.gatt.connect:",e),Le.complete(Ee.ERROR_CONNECT_FAILED,"",t)))}catch(e){return l.warn("----- try catch: device.gatt.connect:",e),Promise.resolve(Le.complete(Ee.ERROR_CONNECT_FAILED,"",t))}})}disconnect(e){return t(this,void 0,void 0,function*(){var t,i;const s=e||{},n=s.deviceId||(null===(t=this.mConnectMap.values().next().value)||void 0===t?void 0:t.deviceId),r=n?this.mConnectMap.get(n):void 0,a=null==r?void 0:r.device,o=null==r?void 0:r.gattServer;if(l.log(`---- WebBleAdapter.disconnect: gattDevice = ${a?a.name:"-"}`,e),!n||!a||!o)return l.log(`---- WebBleAdapter.disconnect: 蓝牙设备[${a?a.name:"-"}]已断开!`),Le.success(0,s);if(s.deviceId&&s.deviceId!==a.id)return l.info(`#### WebBleAdapter.disconnect Failed! {current: ${a.id}, target: ${s.deviceId}}`),Le.complete(Ee.ERROR_PARAM,"",s);if(!(null===(i=a.gatt)||void 0===i?void 0:i.connected))return Le.success(0,s);if(r.notifyCharacteristicMap.size>0){l.info("---- 关闭通知功能");for(const t of r.notifyCharacteristicMap.values()){const e=t.characteristic;e&&(t.characteristicValueChanged&&(e.removeEventListener("characteristicvaluechanged",t.characteristicValueChanged),t.characteristicValueChanged=void 0),yield e.stopNotifications().catch(t=>{l.warn("---- Catch exception from notifyCharacteristic.stopNotification: ",t);}));}}r.writeCharacteristic&&(r.writeCharacteristic=void 0),l.log("---- 【Request】mGattServer.disconnect():");try{a.gatt.disconnect(),l.info("#### WebBleAdapter.disconnect success!");}catch(t){l.warn("#### WebBleAdapter.disconnect catch!",t);}return this.mConnectMap.delete(n),l.info("---- 一切正常,game over !!!"),Le.success(0,s)})}getConnectedBleDevices(){return Promise.resolve([])}setBleMtu(e){return t(this,void 0,void 0,function*(){let t=e.mtu||0;return t>ci.MTU_MAX&&(t=ci.MTU_MAX),Le.isIOS()?{status:-1}:e.chipType&&!e.required?{status:-1,waits:e.waits?e.waits+5:e.waits}:{status:-1,waits:e.waits?e.waits+3:e.waits}})}isDeviceConnected(t){const e=this.mConnectMap.get(t);return !!(e&&e.gattServer&&e.gattServer.connected)&&e.deviceId===t}getGATTServices(e){return t(this,void 0,void 0,function*(){const t=[],i=e.deviceId||"",s=this.mConnectMap.get(i),n=null==s?void 0:s.device,r=null==s?void 0:s.gattServer;return l.info(`---- 【Request】getPrimaryServices(server: ${n?n.name:"undefined"})`),new Promise(i=>{r&&r.connected?r.getPrimaryServices().then(s=>{for(const e of s)l.log(`---- service uuid: ${e.uuid}`),t.push(e);e.complete&&e.complete(t),i(t);}).catch(t=>{l.warn("【WebBleAdapter.Response】getPrimaryServices.catch:",t),e.complete&&e.complete([]),i([]);}):(l.warn("---- 打印机未链接!",r),e.complete&&e.complete([]),i([]));})})}getGATTCharacteristics(e){return t(this,void 0,void 0,function*(){var t;const i=e||{},s=[],n=i.deviceId||(null===(t=this.mConnectMap.values().next().value)||void 0===t?void 0:t.deviceId)||"",r=n?this.mConnectMap.get(n):void 0,a=null==r?void 0:r.gattServer;return l.info("---- 【Request】getBleGATTCharacteristics"),new Promise(t=>a?i.serviceId?void a.getPrimaryService(i.serviceId).then(n=>{n?n.getCharacteristics().then(e=>{if(!e||e.length<=0)l.warn("---- 未检测到任何特征值!"),i.complete&&i.complete(s),t(s);else {for(const t of e){let e=0;t.properties.read&&(e|=Qe.READ),t.properties.writeWithoutResponse&&(e|=Qe.WRITE_NO_RESPONSE),t.properties.write&&(e|=Qe.WRITE),t.properties.notify&&(e|=Qe.NOTIFY),s.push({serviceId:i.serviceId,uuid:t.uuid,properties:e});}i.complete&&i.complete(s),t(s);}}).catch(e=>{l.warn("【WebBleAdapter.response】getCharacteristics.catch: ",e),i.complete&&i.complete(s),t(s);}):(l.warn(`---- 服务实例[${i.serviceId}] 获取失败!`),e.complete&&e.complete(s),t(s));}):(l.warn("---- 参数错误,未指定 serviceId 或者 characteristicId!"),e.complete&&e.complete(s),t(s),s):(l.warn("---- 打印机未链接!"),e.complete&&e.complete(s),void t(s)))})}read(e){return t(this,void 0,void 0,function*(){const t=e.deviceId||"",i=e.characteristicId,s=t?this.mConnectMap.get(t):void 0,n=null==s?void 0:s.gattServer;if(!t||!i||!n)return Le.complete(Ee.ERROR_PARAM,"参数异常",e);const r=Le.getFullUUID(e.serviceId),a=Le.getFullUUID(e.characteristicId),o=yield n.getPrimaryService(r.toLowerCase());if(!o)return Le.complete(Ee.ERROR_GET_SERVICE,"蓝牙服务获取失败",e);const h=yield o.getCharacteristic(a.toLowerCase());return h?(l.info(`【Request】characteristic[${e.shortCharacterId}].readValue: ${a}`),h.readValue().then(t=>(l.info(`【Response】characteristic[${e.shortCharacterId}].readValue: `,t),Le.complete(0,new Uint8Array(t.buffer),e))).catch(t=>(l.warn(`【Error】characteristic[${e.shortCharacterId}].readValue: `,t),Le.complete(Ee.ERROR_READ_CHARACTERISTIC,"")))):Le.complete(Ee.ERROR_GET_CHARACTERISTIC,"蓝牙特征值获取失败",e)})}notify(e){return t(this,void 0,void 0,function*(){const t=e.deviceId||"",i=e.characteristicId||"",s=t?this.mConnectMap.get(t):void 0,n=null==s?void 0:s.gattServer;if(l.info(`---- 【Request】startNotifications[${e.shortCharacterId}], state: ${e.state}`),!(t&&s&&e.serviceId&&i))return l.warn("---- 参数错误!"),Le.complete(Ee.ERROR_PARAM,"未检测到 serviceId 或者 characteristicId",e);if(!n||!n.connected)return l.warn("---- 打印机未链接!"),Le.complete(Ee.ERROR_DISCONNECTED,"打印机未连接",e);const r=yield n.getPrimaryService(e.serviceId);if(!r)return l.warn(`---- 服务实例[${e.serviceId}] 获取失败!`),Le.complete(Ee.ERROR_PARAM,"获取服务列表失败",e);if(e.state){l.info("【BLE_Request】startNotifications: ",e);const t=yield r.getCharacteristic(i);if(!t)return l.warn(`---- notify特征值实例 [${e.characteristicId}] 获取失败!`),Le.complete(Ee.ERROR_CONNECT_FAILED,"特征值获取失败",e);const n=t=>{const i=t.target;if(i.value){const t=new Uint8Array(i.value.buffer);e.dataReceived&&e.dataReceived(t);}},a={characteristic:t,characteristicValueChanged:n};s.notifyCharacteristicMap.set(i,a),t.addEventListener("characteristicvaluechanged",n);return (yield t.startNotifications().then(t=>(l.info("【BLE_Response.success】startNotifications: ",t),true)).catch(t=>(l.warn("【BLE_Response.fail 】startNotifications: ",t),false)))?Le.success("OK",e):(l.warn("---- #### startNotifications 失败!"),Le.complete(Ee.ERROR_CONNECT_FAILED,"startNotifications 失败",e))}if(l.info("【BLE_Request】stopNotifications: ",e),s.notifyCharacteristicMap.size>0){for(const t of s.notifyCharacteristicMap.values()){const e=t.characteristic;e&&t.characteristicValueChanged&&(e.removeEventListener("characteristicvaluechanged",t.characteristicValueChanged),yield e.stopNotifications().then(t=>(l.info(`【BLE_Response.success】stopNotifications(${e.uuid}): `,t),true)).catch(t=>(l.warn(`【BLE_Response.fail 】stopNotifications(${e.uuid}): `,t),true)));}s.notifyCharacteristicMap.clear();}return Le.success("OK",e)})}write(e){return t(this,void 0,void 0,function*(){const t=e.deviceId||"",i=t?this.mConnectMap.get(t):void 0,s=null==i?void 0:i.gattServer,n=e.value||e.data;if(!i||!s)return Le.onResult({statusCode:1,resultInfo:"打印机未连接"},e);if(!i.writeCharacteristic){const t=yield s.getPrimaryService(e.serviceId);if(!t)return l.warn(`---- 服务实例[${e.serviceId}] 获取失败!`),Le.onResult({statusCode:2,resultInfo:"获取服务失败!"},e);const n=yield t.getCharacteristic(e.characteristicId);if(!n)return l.warn(`---- write特征值实例 [${e.characteristicId}] 获取失败!`),Le.onResult({statusCode:3,resultInfo:"特征值获取失败"},e);i.writeCharacteristic=n;}if(i.writeCharacteristic&&n){const t=`[P ${e.pkgIndex} - SUP ${e.subPkgIndex}]`;return this.mShowWriteLog&&l.log(`#### 【Request】writeBLECharacteristicValue[${e.value.length}]: ${t}`),i.writeCharacteristic.writeValueWithoutResponse(new Uint8Array(n.buffer)).then(i=>(this.mShowWriteLog&&l.log(`#### 【Response.success】writeBLECharacteristicValue: ${t}`,i),this.mShowWriteLog=false,Le.success(i,e))).catch(i=>(l.warn(`###【Response.catch】writeBLECharacteristicValue: ${t}`,i),this.mShowWriteLog=true,Le.complete(Ee.ERROR_WRITE_CHARACTERISTIC,i,e)))}return Le.complete(Ee.ERROR_PARAM,"参数错误",e)})}}ci.MTU_MAX=512;class di{static isSupported(){return navigator&&"hid"in navigator&&"function"==typeof navigator.hid.requestDevice}static getDeviceName(t){if(!t)return "";const e=(t.split("@")[1]||"").trim();if(e)return e;{const e=/^.*?((\w+)\s+Label\s+Printer)\s*$/i.exec(t);return console.warn("---------- regMatcher: ",e),e?e[1]:""}}constructor(){this.mHid=null,this.mHidDeviceList=[],this.mConnectedMap=new Map,di.isSupported()?this.mHid=navigator.hid:console.warn("HID API is not supported in this environment. HIDManager will not function.");}getReports(e){return t(this,void 0,void 0,function*(){var t;if(!this.mHid){const t="当前环境不支持 WebHID 功能!";return l.warn(`---- ${t}`),Le.complete(Ee.ERROR_UN_SUPPORTED,void 0,e)}const i=e.deviceId||"";if(!i)return Le.complete(Ee.ERROR_PARAM,void 0,e);const s=i.toUpperCase(),n=null===(t=this.mConnectedMap.get(s))||void 0===t?void 0:t.device;if(!n||!n.opened)return l.warn(`---- HIDAdapter.getReports: 未找已连接设备[${e.deviceId}]的连接信息!`),Le.complete(Ee.ERROR_PARAM,void 0,e);const r=n.collections?n.collections[0]:void 0;if(!r||!r.inputReports||!r.outputReports)return l.warn(`---- HIDAdapter.getReports: 设备[${n.productName}]的collections信息不完整!`),Promise.resolve({statusCode:Ee.ERROR_PARAM,reports:[]});const a=r.inputReports||[],o=r.outputReports||[],h=r.featureReports||[];return Promise.resolve({statusCode:Ee.OK,resultInfo:{inputReports:a.map(t=>({reportId:t.reportId||0,items:t.items||[]})),outputReports:o.map(t=>({reportId:t.reportId||0,items:t.items||[]})),featureReports:h.map(t=>({reportId:t.reportId||0,items:t.items||[]}))}})})}authorize(t){return new Promise(e=>{Le.success("OK",t,e);})}openAdapter(t){const e=t||{};return l.log(`【HID_Request】 openAdapter(isAdapterOpened: force: ${e.force})`,t),new Promise(t=>{if(!this.mHid){const i="当前环境不支持 WebHID 功能!";return l.warn(`---- ${i}`),Le.complete(Ee.ERROR_UN_SUPPORTED,i,e,t)}this.mDisconnectAction||(l.info("---- 注册设备热插拔相关事件!"),this.mConnectAction=t=>{if(l.info(`----- WebHID.onConnectEvent: ${t.device.productName}`,t.device),"function"==typeof e.deviceConnectChange){const i=t.device,s=i.productName||"";e.deviceConnectChange({status:Xe.Connect,device:Object.assign(Object.assign({},i),{deviceId:s,name:di.getDeviceName(i.productName)})});}},this.mHid.addEventListener("connect",this.mConnectAction),this.mDisconnectAction=t=>{l.info(`----- WebHID.onDisconnectEvent: ${t.device.productName}`,t.device);const i=t.device,s=i.productName||"",n=s.toUpperCase(),r=this.mConnectedMap.get(n);r&&"function"==typeof r.disconnectAction&&r.disconnectAction(t),"function"==typeof e.deviceConnectChange&&e.deviceConnectChange({status:Xe.Disconnect,device:Object.assign(Object.assign({},i),{deviceId:s,name:di.getDeviceName(i.productName)})});},this.mHid.addEventListener("disconnect",this.mDisconnectAction)),Le.success(true,e,t);})}closeAdapter(){return Promise.resolve({statusCode:0})}requestDevice(e){return t(this,void 0,void 0,function*(){const t=e||{};return this.mHid?(yield this.openAdapter(e),this.mHid.requestDevice({filters:[{vendorId:13619},{vendorId:1155,productId:23057},{vendorId:1155,productId:23061},{vendorId:1155,productId:23062},{vendorId:1155,productId:23063},{vendorId:1155,productId:23065},{vendorId:1155,productId:23073},{vendorId:1155,productId:23573},{vendorId:1155,productId:23584},{vendorId:1155,productId:23585},{vendorId:1155,productId:23588},{vendorId:1155,productId:23589},{vendorId:1155,productId:23590},{vendorId:1155,productId:23591}]}).then(i=>(l.info("【HID_Response】startDiscovery.success: devices = ",i),this.getDevices().then(i=>(0===i.statusCode&&t.deviceFound&&t.deviceFound(i.resultInfo||[]),t.adapterStateChange&&t.adapterStateChange({discovering:false}),Le.onResult(i,e))))).catch(e=>(l.warn("---- 【Response】startBleDiscovery.fail:",e),t.adapterStateChange&&t.adapterStateChange({discovering:false}),Le.onResult({statusCode:Ee.ERROR_DISCONNECTED,resultInfo:e},t)))):Le.onResult({statusCode:Ee.ERROR_UN_SUPPORTED,message:"HID API is not supported in this environment."})})}startDiscovery(e){return t(this,void 0,void 0,function*(){const t=e||{};return di.isSupported()?(l.info("【HID_Request】 startDiscovery: ",e),t.requestDevice?this.requestDevice(e):this.getDevices(e).then(e=>{const i=e.resultInfo||[];return 0===e.statusCode&&t.deviceFound&&t.deviceFound(i),t.adapterStateChange&&t.adapterStateChange({discovering:false}),e})):Le.complete(Ee.ERROR_UN_SUPPORTED,"",e)})}stopDiscovery(t){return new Promise(e=>{Le.success(true,t,e);})}getDevices(e){return t(this,void 0,void 0,function*(){const t=e||{};return this.mHid?(yield this.openAdapter(e),this.mHid.getDevices().then(e=>{this.mHidDeviceList.splice(0),this.mHidDeviceList.push(...e),l.info("【HID_Response】getDevices: 成功获取到 HID 设备列表,devices =",e);const i=e.map(t=>{const e=t.productName||"",i=di.getDeviceName(e);return {vendorId:t.vendorId,productId:t.productId,productName:t.productName,deviceId:e,name:i||e,type:ze.WEB_HID}});return Le.success(i,t)}).catch(e=>(l.warn("【HID_Response】getDevices: Failed to get HID devices, res =",e),Le.onResult({statusCode:Ee.ERROR_DISCONNECTED,resultInfo:e},t)))):(l.warn("【HID_Request】getDevices: 当前环境不支持 WebHID 功能!"),Le.complete(Ee.ERROR_UN_SUPPORTED,[],t))})}registerDeviceConnectChangeEvent(){}connect(t){const e=t||{};if(!this.mHid){const t="当前环境不支持 WebHID 功能!";return l.warn(`---- ${t}`),Promise.resolve(Le.complete(Ee.ERROR_UN_SUPPORTED,t,e))}const i=e.deviceId||"",s=i.toUpperCase();if(!s)return l.warn("---- HIDAdapter.connect: 未指定要连接的设备ID!"),Promise.resolve(Le.complete(Ee.ERROR_PARAM,"未指定要连接的设备ID!",e));const n=this.mConnectedMap.get(s);return n&&n.device.opened?Promise.resolve(Le.success(n.device,t)):this.mHid.getDevices().then(t=>{this.mHidDeviceList.splice(0),this.mHidDeviceList.push(...t);const n=t.find(t=>(t.productName||"").toUpperCase()===s);return n?n.opened?(l.info(`---- HIDAdapter.connect: 设备[${n.productName}]已处于打开状态!`),this.mConnectedMap.set(s,{device:n}),Le.success(n,e)):n.open().then(()=>{l.info(`---- HIDAdapter.connect: 设备[${n.productName}]已成功连接!`);const t={device:n};return t.disconnectAction=t=>{const n=t.device.productName||"";n&&n.toUpperCase()===s&&(this.disconnect({deviceId:i}),e.connectionStateChange&&e.connectionStateChange({deviceId:i,connected:false}));},this.mConnectedMap.set(s,t),Le.success(n,e)}).catch(t=>(console.warn("---- Failed to open HID device:",t),Le.onResult({statusCode:Ee.ERROR_DISCONNECTED,resultInfo:t},e))):Le.onResult({statusCode:Ee.ERROR_NO_PRINTER,message:`未找到指定设备ID[${e.deviceId}]的设备!`},e)})}disconnect(e){return t(this,void 0,void 0,function*(){const t=e||{};if(!this.mHid){const e="当前环境不支持 WebHID 功能!";return l.warn(`---- ${e}`),Promise.resolve(Le.complete(Ee.ERROR_UN_SUPPORTED,e,t))}if(this.mConnectedMap.size<=0)return l.log("---- HIDAdapter.disconnect: 当前没有已连接的设备!"),Promise.resolve(Le.success(0,t));const i=t.deviceId||"",s=i.toUpperCase(),n=t.deviceId?this.mConnectedMap.get(s):this.mConnectedMap.values().next().value,r=null==n?void 0:n.device;return n&&r?("function"==typeof n.inputReportAction&&(yield this.notify({deviceId:i,reportId:di.REPORT_ID_PRINT,state:false})),r.opened?r.close().then(()=>(l.info(`---- HIDAdapter.disconnect: 设备[${r.productName}]已成功断开连接!`),this.mConnectedMap.delete(s),Le.success(0,t))).catch(e=>(l.warn(`---- HIDAdapter.disconnect: 设备[${r.productName}]断开连接失败!`,e),Le.complete(Ee.ERROR_DISCONNECTED,"",t))):(l.warn(`---- HIDAdapter.disconnect: 设备[${r.productName}]未处于打开状态!`),Promise.resolve(Le.success(0,t)))):(l.warn(`---- HIDAdapter.disconnect: 未找到指定设备[${t.deviceId}]的连接信息!`),Promise.resolve(Le.complete(Ee.ERROR_PARAM,"",t)))})}read(t){var e;const i=t||{},s=i.deviceId?i.deviceId.toUpperCase():"",n=i.deviceId?null===(e=this.mConnectedMap.get(s))||void 0===e?void 0:e.device:null;if(!this.mHid){const e="当前环境不支持 WebHID 功能!";return l.warn(`---- ${e}`),Promise.resolve(Le.complete(Ee.ERROR_UN_SUPPORTED,e,t))}return n&&i.reportId?n.opened?(n.sendFeatureReport(i.reportId,new Uint8Array(0)).catch(t=>{l.warn(`---- HIDAdapter.read: 向设备[${n.productName}]发送查询指令失败!`,t);}),n.receiveFeatureReport(i.reportId).then(t=>Le.success(new Uint8Array(t.buffer),i)).catch(t=>(l.warn(`---- HIDAdapter.read: 等待设备[${n.productName}]的响应数据失败!`,t),Le.complete(Ee.ERROR_DISCONNECTED,"",i)))):(l.warn(`---- HIDAdapter.read: 设备[${n.productName}]未处于打开状态!`),Promise.resolve(Le.complete(Ee.ERROR_DISCONNECTED,"",i))):(l.warn(`---- HIDAdapter.read: 未找到指定设备[${i.deviceId}]的连接信息!`),Promise.resolve(Le.complete(Ee.ERROR_PARAM,"",i)))}write(t){var e;const i=t||{},s=i.deviceId?i.deviceId.toUpperCase():"",n=i.value||i.data,r=i.deviceId?null===(e=this.mConnectedMap.get(s))||void 0===e?void 0:e.device:null;return r&&i.reportId?r.opened?!(n instanceof Uint8Array)||n.length<=0?(l.warn("---- HIDAdapter.write: 没有要发送的数据!",t),Promise.resolve(Le.complete(Ee.ERROR_PARAM,"没有要发送的数据!",i))):r.sendReport(i.reportId,n).then(()=>Le.success(0,i)).catch(t=>(l.warn(`---- HIDAdapter.write: 向设备[${r.productName}]发送数据失败!`,t),Le.complete(Ee.ERROR_DISCONNECTED,"",i))):(l.warn(`---- HIDAdapter.write: 设备[${r.productName}]未处于打开状态!`,r),Promise.resolve(Le.complete(Ee.ERROR_DISCONNECTED,"",i))):(l.warn(`---- HIDAdapter.write: 未找到指定设备[${i.deviceId}]的连接信息!`,t),Promise.resolve(Le.complete(Ee.ERROR_PARAM,"",i)))}notify(t){const e=t||{},i=e.deviceId?e.deviceId.toUpperCase():"",s=e.deviceId?this.mConnectedMap.get(i):null,n=null==s?void 0:s.device;return l.info(`【HID_Request】notify: status = ${e.state}, deviceId = ${e.deviceId}`,t),n?"boolean"!=typeof e.state||"boolean"==typeof e.state&&e.state?n.opened?(s.inputReportAction=t=>{const{data:i,device:s,reportId:n}=t,r=new Uint8Array(i.buffer);r[0]>0&&(n===di.REPORT_ID_PRINT?e.dataReceived&&e.dataReceived(r):n>=di.REPORT_ID_LOG_ERROR&&n<=di.REPORT_ID_LOG_VERBOSE&&l.info(`---- HIDAdapter.notify: 检测到设备[${s.productName}]的 RID[${n}]发送的日志信息L[${r.length}]:`,Le.arrayBufferToHex16(r)));},n.addEventListener("inputreport",s.inputReportAction),Promise.resolve(Le.success(0,e))):(l.warn(`---- HIDAdapter.notify: 设备[${n.productName}]未处于打开状态!`),Promise.resolve(Le.complete(Ee.ERROR_DISCONNECTED,"",e))):("function"==typeof s.inputReportAction&&(n.removeEventListener("inputreport",s.inputReportAction),s.inputReportAction=void 0),Promise.resolve(Le.success(0,e))):(l.warn(`---- HIDAdapter.notify: 未找到指定设备[${e.deviceId}]的连接信息!`),Promise.resolve(Le.complete(Ee.ERROR_PARAM,"",e)))}}di.REPORT_ID_LOG_LEVEL=16,di.REPORT_ID_LOG_ERROR=17,di.REPORT_ID_LOG_WARN=18,di.REPORT_ID_LOG_INFO=19,di.REPORT_ID_LOG_DEBUG=20,di.REPORT_ID_LOG_VERBOSE=21,di.REPORT_ID_PRINT=30;class ui{static create(t){return new ui(t)}get adapter(){return this.mAdapter}constructor(t){this.mAdapter=t;}authorize(t){return "function"==typeof this.adapter.authorize?this.adapter.authorize(t):Promise.resolve({statusCode:Ee.OK,resultInfo:"暂不支持该操作"})}createConnection(t){return new ai(t.device,this.adapter,t)}openAdapter(t){return this.adapter.openAdapter(t)}closeAdapter(t){return "function"==typeof this.adapter.closeAdapter?this.adapter.closeAdapter(t):Promise.resolve(Le.complete(Ee.ERROR_NO_IMPLEMENT,"",t))}resetAdapter(t){return "function"==typeof this.adapter.resetAdapter?this.adapter.resetAdapter(t):this.adapter.closeAdapter(t).then(e=>0===e.statusCode?this.adapter.openAdapter(t):e)}startDiscovery(t){return "function"==typeof this.adapter.startDiscovery?this.adapter.startDiscovery(t):Promise.resolve(Le.onResult({statusCode:Ee.ERROR_NO_IMPLEMENT}))}stopDiscovery(){return "function"==typeof this.adapter.stopDiscovery?this.adapter.stopDiscovery():Promise.resolve(Le.onResult({statusCode:Ee.ERROR_NO_IMPLEMENT}))}getFoundDevices(t){return "function"==typeof this.adapter.getFoundDevices?this.adapter.getFoundDevices(t):"function"==typeof this.adapter.getBluetoothDevices?this.adapter.getBluetoothDevices(t):Promise.resolve(Le.complete(Ee.ERROR_NO_IMPLEMENT,[],t))}getConnectedDevices(t){return "function"==typeof this.adapter.getConnectedDevices?this.adapter.getConnectedDevices(t):Promise.resolve(Le.complete(Ee.ERROR_NO_IMPLEMENT,[],t))}requestDevice(t){return "function"==typeof this.adapter.requestDevice?this.adapter.requestDevice(t):Promise.resolve(Le.complete(Ee.ERROR_NO_IMPLEMENT,[],t))}getDevices(t){return "function"==typeof this.adapter.getDevices?this.adapter.getDevices(t):Promise.resolve(Le.complete(Ee.ERROR_NO_IMPLEMENT,[],t))}}class li extends ui{constructor(t){super(t);}createConnection(t){return new gi(t.device,this,t)}}class gi extends ai{get device(){return this.mDevice}get adapter(){return this.mAdapter}constructor(t,e,i){super(t,e.adapter,i),this.mInputReportMap=new Map,this.mOutputReportMap=new Map,this.mFeatureReportMap=new Map,this.mWriteReportSize=0;}notifyData(e){return t(this,void 0,void 0,function*(){this.mInputReportMap.clear(),this.mOutputReportMap.clear(),this.mFeatureReportMap.clear(),this.mReadReport=void 0,this.mWriteReport=void 0,this.mWriteReportSize=0;const t=yield this.adapter.getReports(this.device),i=0===t.statusCode?t.resultInfo:void 0;if(!i)return {statusCode:Ee.ERROR_NOTIFY_CHARACTERISTIC,message:"无法获取设备报告信息"};if(i.inputReports&&i.inputReports.length>0)for(const t of i.inputReports)t.reportId&&t.items&&t.items.length>0&&this.mInputReportMap.set(t.reportId,t),t.reportId===gi.REPORT_ID_DATA&&(this.mReadReport=t,l.info(`HIDConnection: 获取到数据读取报告,reportId=${t.reportId}`,t));if(i.outputReports&&i.outputReports.length>0)for(const t of i.outputReports)if(t.reportId&&t.items&&t.items.length>0&&this.mOutputReportMap.set(t.reportId,t),t.reportId===gi.REPORT_ID_DATA){this.mWriteReport=t;const e=t.items[0];this.mWriteReportSize=e.reportCount||0,l.info(`HIDConnection: 获取到数据写入报告,reportId=${t.reportId}, writeReportSize=${this.mWriteReportSize} Bytes`,t);}if(i.featureReports&&i.featureReports.length>0)for(const t of i.featureReports)t.reportId&&t.items&&t.items.length>0&&this.mFeatureReportMap.set(t.reportId,t);return this.mReadReport&&this.mWriteReport?this.adapter.notify({deviceId:this.deviceId,reportId:this.mReadReport.reportId,dataReceived:t=>{if("string"==typeof t&&(t=Le.hex16ToArrayBuffer(t)),t.length>1){let i=null;if(t[0]>=192){const e=Ue.toEBV(t[1],t[0]);i=e>0?t.slice(2,e+2):null;}else {const e=t[0];i=e>0?t.slice(1,e+1):null;}i&&i.length>0&&e(i);}else l.warn(`【HIDConnection】dataReceived: 接收到异常的数据,data: [${Le.arrayBufferToHex16(t)}]`);}}).then(t=>({statusCode:t.statusCode,resultInfo:"object"==typeof t.resultInfo?t.resultInfo:void 0})):{statusCode:Ee.ERROR_NOTIFY_CHARACTERISTIC,message:"设备报告信息不完整,无法进行数据传输"}})}writeHidData(t,e){return this.mWriteReport?(this.mBufferSize-=t.length,this.adapter.write({deviceId:this.deviceId,reportId:this.mWriteReport.reportId,value:t})):Promise.resolve({statusCode:Ee.ERROR_WRITE_CHARACTERISTIC,message:"设备写入报告信息不完整,无法进行数据传输"})}writeData(e,i){return t(this,void 0,void 0,function*(){if(!this.mWriteReport||this.mWriteReportSize<=0)return Promise.reject({statusCode:Ee.ERROR_NOTIFY_CHARACTERISTIC,message:"设备报告信息不完整,无法进行数据传输"});let t=0;for(let s=0,n=e.length;s<n;s+=t)if(t=this.mWriteReportSize>=194?this.mWriteReportSize-2:this.mWriteReportSize-1,t>n-s&&(t=n-s),t>=192){const n=new Uint8Array(2);n[0]=t>>>8|192,n[1]=255&t;const r=e.slice(s,s+t),a=new Uint8Array(n.length+r.length);a.set(n,0),a.set(r,n.length);const o=yield this.writeHidData(r,i);if(0!==o.statusCode)return o}else {const n=new Uint8Array(t+1);n[0]=t,n.set(e.slice(s,s+t),1);const r=yield this.writeHidData(n,i);if(0!==r.statusCode)return r}return {statusCode:Ee.OK,message:"数据发送成功"}})}}gi.REPORT_ID_DATA=30,gi.REPORT_ID_LOG_ERROR=17,gi.REPORT_ID_LOG_VERBOSE=21;class pi extends ui{static create(t){return new pi(t)}get adapter(){return this.mAdapter}constructor(t){super(t);}createConnection(t){return new hi(t.device,this.adapter,t)}}!function(t){t[t.Binary=1]="Binary",t[t.Hex16=2]="Hex16",t[t.Base64=3]="Base64";}(ti||(ti={}));class fi{static getModelName(t){const e=(t||"").lastIndexOf("-");return e>0?[t.substring(0,e),t.substring(e+1)]:[]}get Models(){return this.models}constructor(t){this.includeModels=new Set,this.excludeModels=new Set,this.includePatterns=new Set,this.excludePatterns=new Set,this.models=t||"";const e=this.models.split(";");for(const t of e){if(!t)continue;let e=t;switch(t[0]){case "+":case "-":case "*":e=t.substring(1);}const i="-"===t[0];/[(){}[\],^$\\*?.]/.test(e)?i?this.excludePatterns.add(e):this.includePatterns.add(e):e&&(i?this.excludeModels.add(e.toUpperCase()):this.includeModels.add(e.toUpperCase()));}}isSupport(t){if(!t)return false;if(this.includeModels.size<=0&&this.excludeModels.size<=0&&this.includePatterns.size<=0&&this.excludePatterns.size<=0)return true;if(fi.patternSuperD.exec(t))return true;if(fi.patternSuperO.exec(t))return true;const e=fi.getModelName(t),i=e[0]?e[0].toUpperCase():"";if(this.excludeModels&&this.excludeModels.has(i))return false;if(this.excludePatterns.size>0)for(const e of this.excludePatterns)if(t.match(new RegExp(e)))return false;if(this.includeModels.size>0||this.includePatterns.size>0){if(this.includeModels.size>0&&this.includeModels.has(i))return true;if(this.includePatterns.size>0)for(const e of this.includePatterns)if(t.match(new RegExp(e)))return true;return false}return true}}fi.patternSuperD=/^(.*)-(D[0-9]{4,5}[0-9A-Z]{2,5}[0-9]{2})$/,fi.patternSuperO=/^(.*)-(O[0-9]{4,5}[0-9A-Z]{2,5}[0-9]{2})$/;class mi{static cancelCloseTimer(){this.closeTimer&&this.closeTimer>0&&(clearTimeout(this.closeTimer),this.closeTimer=0,"function"==typeof mi.closeAction&&mi.closeAction({statusCode:Ee.ERROR_CANCEL,resultInfo:false}));}static getPrinterNameInfo(t){t=t||"";const e=mi.patternGeneral.exec(t);if(!e)return;let i=e[2];const s=/^\d+$/.exec(i);let n="",r=0;if(i[1]<"0"||i[1]>"9"?(n=i.substring(0,2),i=i.substring(2),r+=11*n.charCodeAt(0),r+=13*n.charCodeAt(1)):(i[0]<"0"||i[0]>"9")&&(n=i.substring(0,1),i=i.substring(1),r+=17*n.charCodeAt(0)),!(i.length<8)){if(!s||i.length>=9||i.charCodeAt(3)!=P.num_0){if(s){r+=2*parseInt(i.charAt(0)),r+=3*parseInt(i.charAt(1)),r+=5*parseInt(i.charAt(2));for(var a=4;a<i.length;++a)r+=parseInt(i.charAt(a))*(1&a?9:7);}else {r+=2*Number(i.charAt(0)),r+=3*Number(i.charAt(1)),r+=5*Number(i.charAt(2));for(a=4;a<i.length;++a)r+=i.charCodeAt(a)*(1&a?9:7);}var o=r%10;if(mi.sDeTongCheckSum.charAt(o)!=i.charAt(3))return}return {model:e[0],serials:i,trade:n,checkSum:r}}}static isSupperTrade(t,e){if(!t)return false;return ["D","O",...e&&e.length>0?e:[]].indexOf(t)>=0}static setSupportModels(t){const e=Array.isArray(t)?t.join(";"):t||"";mi.models!==e&&(mi.models=e,mi.matcher=e?new fi(e):void 0);}static setBleFilters(t){mi.bleFilters=t;}static isTradeSupported(t,e){return !e||e.length<=0||!!t&&(!!mi.isSupperTrade(t)||e.indexOf(t)>=0)}static filterSupperTrades(t){return t.filter(t=>t&&"#"===t[0]).map(t=>t.substring(1))}static filterNormalTrades(t){return t.filter(t=>t&&"#"!==t[0])}static createWebHIDManager(){const t=di.isSupported()?new di:void 0;return t?new li(t):void 0}static createWebBLEManager(){const t=ci.getInstance();return t?pi.create(t):void 0}static isSupportedDevice(t,e,i){const s=mi.getPrinterNameInfo(t);if(!s)return false;if(!i||!e){const t=mi.trades?mi.trades.split(";"):[];i||(i=mi.filterSupperTrades(t)),e||(e=mi.filterNormalTrades(t));}return !!mi.isSupperTrade(s.trade,i)||(e.length>0&&!mi.isTradeSupported(s.trade,e)?(l.info(`---- ----: 不支持的 [TRADE]: ${t}`),false):!(mi.matcher&&!mi.matcher.isSupport(t))||(l.info(`---- ----: 不支持的 [MODEL]: ${t}`),false))}static isSupperDevice(t){const e=mi.getPrinterNameInfo(t);if(!e||!e.trade)return false;const i=mi.trades?mi.trades.split(";"):[],s=mi.filterSupperTrades(i);return mi.isSupperTrade(e.trade,s)}static test(){}constructor(t){this.mManagerMap=new Map,this.mJobId=0,this.mInitOptions={},this.mConnMap=new Map,this.mDeviceMap=new Map,this.mConnectingMap=new Map,t&&this.setManager(t);}get Manager(){return this.mManagerMap.get(ze.AUTO)}set Manager(t){const e=this.mManagerMap.get(ze.AUTO);t&&t!==e&&this.mManagerMap.set(ze.AUTO,t);}get PrinterDPI(){var t;const e=(null===(t=this.mConnection)||void 0===t?void 0:t.printerInfo)||{};return e.printerDPI&&e.printerDPI>0?e.printerDPI:Ke.PRINTER_DPI_DEFAULT}get PrinterWidth(){var t;const e=(null===(t=this.mConnection)||void 0===t?void 0:t.printerInfo)||{};return e.printerWidth&&e.printerWidth>0?e.printerWidth:Ke.PRINTER_WIDTH_DEFAULT}get Printable(){return this.mConnection?this.mConnection.printerInfo.printable:0}get PrintStatus(){return this.mConnection?this.mConnection.printStatus:Ze.None}get IsConnected(){return this.mConnection&&this.mConnection.isConnected&&this.PrintStatus>Ze.Checking}setInitOptions(t){t&&(Object.assign(this.mInitOptions,t),this.mConnection&&this.mConnection.setOptions(t));}getHIDManager(t){let e=this.mManagerMap.get(ze.WEB_HID);return !e&&t&&di.isSupported()&&(e=mi.createWebHIDManager(),e&&this.mManagerMap.set(ze.WEB_HID,e)),e}getBLEManager(t){let e=this.mManagerMap.get(ze.WEB_BLE);return !e&&t&&ci.isSupported()&&(e=mi.createWebBLEManager(),e&&this.mManagerMap.set(ze.WEB_BLE,e)),e}getManager(t){return t===ze.WEB_HID?this.getHIDManager(true):t===ze.WEB_BLE?this.getBLEManager(true):this.mManagerMap.size>0?this.mManagerMap.values().next().value:ci.isSupported()?this.getBLEManager(true):this.getHIDManager(true)}setManager(t,e){t&&(e===ze.WEB_BLE||e===ze.WEB_HID?this.mManagerMap.set(e,t):this.mManagerMap.set(ze.AUTO,t));}openAdapter(e){return t(this,void 0,void 0,function*(){const t=e||{},i=t.webBLE?ze.WEB_BLE:t.webHID?ze.WEB_HID:ze.AUTO,s=this.getManager(i);return s?s.openAdapter(e):Le.complete(Ee.ERROR_UN_SUPPORTED,"",e)})}resetAdapter(e){return t(this,void 0,void 0,function*(){const t=this.getManager();return t?t.resetAdapter(e):Le.complete(Ee.ERROR_UN_SUPPORTED,"",e)})}closeAdapter(e){return t(this,void 0,void 0,function*(){const t=this.getManager();return t?t.closeAdapter(e):Le.complete(Ee.ERROR_UN_SUPPORTED,"",e)})}parsePositioningPackage(t){if(t.cmd!==Ge.CMD_POSITIONING)return Le.complete(Ee.ERROR_PARAM,"指令错误,无法解析!");const e=t.Data[0],i=t.Data[2],s=Le.getString(Uint8Array.from(t.Data),3);if(l.warn(`subCmd = ${e}, deviceState = ${i}, positionStr = ${s}`),1===e){const t=s.split(","),e=t[3],i=t[4],n={mode:t[0]?parseInt(t[0]):0,signalType:t[1],satellites:t[2]?parseInt(t[2]):0,utcDate:e,utcTime:i,ew:t[5],longitude:t[6],ns:t[7],latitude:t[8],height:t[9]?parseFloat(t[9]):0,heightAnomaly:t[10]?parseFloat(t[10]):void 0};if(e&&i){const t=parseInt(e.substring(0,2)),s=parseInt(e.substring(2,4)),r=parseInt(`20${e.substring(4,6)}`),a=parseInt(i.substring(0,2)),o=parseInt(i.substring(2,4)),h=parseInt(i.substring(4,6)),c=Date.UTC(r,s-1,t,a,o,h);n.dateTime=new Date(c);}return 0===n.mode&&l.warn("---- 定位不可用或定位无效!"),Le.success(n)}return Le.complete(Ee.ERROR_PARAM,"不支持的子命令!")}static trimDeviceName(t){return t.replace(/[\ufffd\u007f\u0000-\u001f]/g,"")}updateDeviceList(t,e,i,s){const n=[];if(!i||!s){const t=mi.trades?mi.trades.split(";"):[];s||(s=mi.filterSupperTrades(t)),i||(i=mi.filterNormalTrades(t));}if(t&&t.length>0)for(const r of t)if(r.name&&r.deviceId)if(r.name=mi.trimDeviceName(r.name||r.localName||""),mi.isSupportedDevice(r.name,i,s)){const t=r;t.advertisData&&"string"==typeof t.advertisData&&(t.advertisData=Le.hex16ToArrayBuffer(t.advertisData)),!e&&this.mDeviceMap.has(r.deviceId)||this.mDeviceMap.set(r.deviceId,r),n.push(r);}else /^(\w+)\s+Label\s+Printer$/.exec(r.name)&&(this.mDeviceMap.has(r.deviceId)||(this.mDeviceMap.set(r.deviceId,r),n.push(r)));return n}getPrinters(t){return Array.from(this.mDeviceMap.values()).sort((t,e)=>t.RSSI&&e.RSSI?e.RSSI-t.RSSI:e.RSSI?1:t.RSSI?-1:0)}getDeviceType(t){const e=t||{};return e.webBLE?ze.WEB_BLE:e.webHID||e.webUSB?ze.WEB_HID:ze.AUTO}getCacheDevices(e){return t(this,void 0,void 0,function*(){const t=yield e.getConnectedDevices(),i=[];0===t.statusCode&&t.resultInfo&&i.push(...t.resultInfo);const s=yield e.getFoundDevices();return 0===s.statusCode&&s.resultInfo&&i.push(...s.resultInfo),i})}startDiscovery(e){return t(this,void 0,void 0,function*(){const t=e||{};t.trades?mi.trades=t.trades:mi.trades&&(t.trades=mi.trades),t.models?mi.setSupportModels(t.models):mi.models&&(t.models=mi.models);const i=this.getDeviceType(t),s=this.getManager(i);if(!s)return Le.complete(Ee.ERROR_UN_SUPPORTED,"",e);const n=mi.trades?mi.trades.split(";"):[],r=mi.filterSupperTrades(n),a=mi.filterNormalTrades(n),o=yield this.getCacheDevices(s);let h="",c="",d="",u=[];const g="number"==typeof t.timeout?t.timeout:void 0;if(this.mDiscovering=true,this.mDeviceMap.clear(),o&&o.length>0){this.updateDeviceList(o,true,a,r),u=this.getPrinters();try{t.deviceFound&&t.deviceFound(u);}catch(t){l.warn("---- capture exception from opt.deviceFound",t);}}return !t.bleFilters&&mi.bleFilters&&(t.bleFilters=mi.bleFilters),s.startDiscovery(Object.assign(Object.assign({},t),{deviceFound:e=>{if(this.updateDeviceList(e,true,a,r),u=this.getPrinters(),c=u.map(t=>t.deviceId).join(";"),d=u.map(t=>t.name).join(";"),c!==h){l.info(`---- ---- 检测到新设备:【${d}】`),h=c;try{t.deviceFound&&t.deviceFound(u);}catch(t){l.warn("---- capture exception from opt.deviceFound",t);}"number"==typeof g&&g<=0&&(l.info(`---- 检测到打印机,自动停止搜索(timeout: ${g})!`),this.stopDiscovery());}},adapterStateChange:e=>{e.discovering||(this.mDiscovering=e.discovering,this.stopDiscovery()),t.adapterStateChange&&t.adapterStateChange(e);},complete:i=>{if(0===i.statusCode&&(g&&g>0&&(l.info("---- 启动蓝牙搜索定时器:"),mi.scanTimer=setTimeout(()=>{l.info(`---- 蓝牙搜索超时时间到:[timeout = ${g}]`),mi.scanTimer=0,this.stopDiscovery();},g)),this.mConnection&&this.mConnection.isConnected)){const e=this.mConnection.device;e&&(l.info(`---- 检测到已连接设备:${e.name}`),this.updateDeviceList([e],true,a,r),u=this.getPrinters(),u.length>0&&t.deviceFound&&t.deviceFound(u));}0===i.statusCode&&l.log("---- 蓝牙搜索启动成功!"),Le.onResult(i,e);}}))})}stopDiscovery(){return t(this,void 0,void 0,function*(){mi.scanTimer&&mi.scanTimer>0&&(l.info("---- 停止扫描超时定时器:"),clearTimeout(mi.scanTimer),mi.scanTimer=0);const t=this.getManager();return t?t.stopDiscovery():Le.complete(Ee.ERROR_UN_SUPPORTED,"")})}getFoundDevices(t){const e=this.getManager();return e?e.getFoundDevices().then(e=>{if(0===e.statusCode){const i=e.resultInfo;if(i&&i.length>0){this.updateDeviceList(i,false);const e=this.getPrinters();return Le.successResult(e,t)}return Le.successResult([],t)}return Le.successResult([],t)}):Promise.resolve([])}requestDevice(t){const e=t||{},i=this.getDeviceType(e),s=this.getManager(i);return s?(!e.bleFilters&&mi.bleFilters&&(e.bleFilters=mi.bleFilters),s.requestDevice(e).then(e=>{const i=e.resultInfo||[];if(0===e.statusCode&&i.length>0){this.updateDeviceList(i,true);const e=this.getPrinters();return Le.success(e,t)}return Le.success([],t)})):Promise.resolve(Le.complete(Ee.ERROR_UN_SUPPORTED,[],t))}getDevices(e){return t(this,void 0,void 0,function*(){const t=this.getDeviceType(e),i=this.getManager(t);return i?i.getDevices(e).then(t=>{const i=t.resultInfo||[];if(0===t.statusCode&&i.length>0){this.updateDeviceList(i,true);const t=this.getPrinters();return Le.success(t,e)}return Le.success([],e)}):Le.complete(Ee.ERROR_UN_SUPPORTED,[],e)})}searchPrinter(e){return t(this,void 0,void 0,function*(){const t=e||{};return new Promise(e=>{let i=false;this.startDiscovery({timeout:t.timeout||0,models:t.models,deviceFound:s=>{if((null==s?void 0:s.length)>0){let n;for(const e of s){if(!t.name&&!t.deviceId){n=e;break}if(t.name&&t.name===e.name){n=e;break}if(t.deviceId&&t.deviceId===e.deviceId){n=e;break}}n&&(i=true,e(n),this.stopDiscovery());}},adapterStateChange:t=>{t.discovering||i||(i=true,e(void 0));}}).then(t=>{0!==t.statusCode&&e(void 0);});})})}openPrinter(e){return t(this,void 0,void 0,function*(){const t=e||{},i=this.getManager();if(!i)return Le.complete(Ee.ERROR_UN_SUPPORTED,{},e);mi.cancelCloseTimer();const s=yield i.getConnectedDevices(),n=this.updateDeviceList(0===s.statusCode&&s.resultInfo||[],true),r=this.getPrinters();let a;if(t.name||t.deviceId)for(const e of r){if(e.deviceId===t.deviceId||e.name===t.name){a=e;break}if(t.name&&(e.name.startsWith(t.name.toUpperCase())||t.name===e.deviceName||t.name===e.printerName)){a=e;break}}else if(this.IsConnected)return Le.onResult({statusCode:Ee.OK},t);if(!a)if(t.name&&t.deviceId)if(mi.isSupportedDevice(t.name))a=Object.assign(Object.assign({},t),{callback:void 0});else {if("boolean"!=typeof t.checkDeviceName||t.checkDeviceName)return Le.onResult({statusCode:Ee.ERROR_UN_SUPPORTED,errMsg:`不支持的打印机设备:[${t.name}]!`},t);a=Object.assign(Object.assign({},t),{callback:void 0});}else t.name||t.deviceId?"boolean"!=typeof t.checkDeviceName||t.checkDeviceName||(a=Object.assign(Object.assign({},t),{callback:void 0})):n.length>0&&(a=n[0]);if(!a){if("boolean"!=typeof t.autoScan&&(t.autoScan=true),!t.autoScan)return Le.onResult({statusCode:Ee.ERROR_NO_PRINTER,errMsg:"未指定目标打印机"},t);if(l.info(`#### 未检测到缓存的蓝牙设备,正在进行重新搜索:{ name: ${t.name}, deviceId: ${t.deviceId} }`),a=yield this.searchPrinter({name:t.name,deviceId:t.deviceId,models:t.models,timeout:5e3}),!a)return l.warn("#### 未检测到匹配的蓝牙设备!"),Le.onResult({statusCode:Ee.ERROR_NO_PRINTER,errMsg:"未搜索到到打印机设备!"},t)}l.info(`#### 正在链接打印机设备:{ name: ${a.name}, deviceId: ${a.deviceId} }...`),this.mDiscovering&&(yield this.stopDiscovery());const o=yield this.connect(Object.assign(Object.assign({},t),{device:a}));return o.statusCode===Ee.OK?(l.info("★★★★★★ 打印机链接成功!★★★★★★"),Le.onResult(o,t)):(l.info(`★★★★★★ 打印机链接失败[${o.statusCode}]!★★★★★★`),Le.onResult(o,t))})}closePrinter(e){return t(this,void 0,void 0,function*(){const t=e||{},i=t.deviceId||t.name||t.deviceName?{deviceId:t.deviceId||"",name:t.name||t.deviceName||""}:t.device;if(mi.cancelCloseTimer(),t.force){return (i?this.disconnect(i,true):this.disconnectAll(true)).then(t=>Le.complete(t?0:Ee.ERROR_OTHER,t,e))}return new Promise(s=>{mi.closeAction=t=>{Le.onResult(t,e,s),mi.closeAction=void 0;},mi.closeTimer=setTimeout(()=>{mi.closeTimer=0,mi.closeAction=void 0,i?this.disconnect(i).then(t=>Le.complete(t?0:Ee.ERROR_OTHER,t,e,s)):this.disconnectAll().then(t=>Le.complete(t?0:Ee.ERROR_OTHER,t,e,s));},t.delay);})})}getPrinterInfo(){return this.mConnection&&this.PrintStatus>Ze.Checking?this.mConnection.printerInfo:{}}createConnection(e){return t(this,void 0,void 0,function*(){const t=e.device||{},i=t.deviceId,s=this.getManager(t.type);if(!s)return Le.complete(Ee.ERROR_UN_SUPPORTED,"",e);if(this.mConnectingMap.get(i)){const e=`设备[${t.name}]正在连接中,不能重复连接,请稍后重试!`;return l.warn(`DzPrinter.createConnection: ${e}`),Le.complete(Ee.ERROR_CONNECT_FAILED,e)}this.mConnectingMap.set(i,true),setTimeout(()=>{this.mConnectingMap.get(i)&&this.mConnectingMap.delete(i);},8e3);const n=Object.assign(Object.assign(Object.assign({},this.mInitOptions),e),{device:t}),r=s.createConnection(n),a=yield r.connect(Object.assign(Object.assign({},e),{connectionStateChange:t=>{t.connected||this.disconnect({deviceId:t.deviceId,name:""}),e.connectionStateChange&&e.connectionStateChange(t);}}));if(0!==a.statusCode)return this.mConnectingMap.delete(i),Le.onResult({statusCode:a.statusCode,resultInfo:"打印机链接失败!"});const o=yield r.checkPrinterInfo();if(o.statusCode!==Ee.OK)return l.error(`---- 打印机相关参数获取失败(statusCode: ${o.statusCode})!`),yield this.disconnect(t),this.mConnectingMap.delete(i),Le.onResult(o);this.mConnMap.set(i,r),this.mConnection=r,this.mConnectingMap.delete(i);const h=o.resultInfo;return l.info(`========== deviceInfo: ${t.name} ==========`,h),l.info(`---- deviceName : ${t.name}`),l.info(`---- deviceId : ${i}`),l.info(`---- printerDPI : ${h.printerDPI}`),l.info(`---- printerWidth : ${h.printerWidth}`),l.info(`---- hardwareFlags : ${Le.toHexString(h.hardwareFlags,"0x")}`),l.info(`---- softwareFlags : ${Le.toHexString(h.softwareFlags,"0x")}`),l.info(`---- softwareVersion : ${h.softwareVersion}`),l.info("---- printerAlignment[R0/C2/L4] : "+((1536&h.softwareFlags)>>8)),l.info(`---- mIsPrPageKey[ >= 0 is ok] : ${h.isPrPageKey}`),l.info(`---- dfType : ${h.dfType}`),l.info(`---- requestMTUs : ${h.requestMTUs}`),l.info(`---- writeWaits : ${h.writeWaits}`),l.info(`---- fcMTU : ${h.fcMTU}`),l.info(`---- fcCredit : ${h.fcCredit}`),l.info(`---- fcNotifyCharacter : ${h.fcNotifyCharacter}`),l.info(`---- fcWriteCharacter : ${h.fcWriteCharacter}`),l.info("--------------------------------------------------"),"number"==typeof n.clientType&&l.info(`---- options.clientType : ${n.clientType}`),"boolean"==typeof n.enableMcuId&&l.info(`---- options.enableMcuId : ${n.enableMcuId}`),"number"==typeof n.requestMTUs&&l.info(`---- options.requestMTUs : ${n.requestMTUs}`),"number"==typeof n.writeWaits&&l.info(`---- options.writeWaits : ${n.writeWaits}`),"number"==typeof n.writeExtendWaits&&l.info(`---- options.writeExtendWaits : ${n.writeExtendWaits}`),"number"==typeof n.reservedMTUs&&l.info(`---- options.reservedMTUs : ${n.reservedMTUs}`),"number"==typeof n.minBufferSize&&l.info(`---- options.minBufferSize : ${n.minBufferSize}`),"number"==typeof n.dataSendMode&&l.info(`---- options.dataSendMode : ${n.dataSendMode}`),"boolean"==typeof n.enablePageKey&&l.info(`---- options.enablePageKey : ${n.enablePageKey}`),"boolean"==typeof n.enableFlowControl&&l.info(`---- options.enableFlowControl : ${n.enableFlowControl}`),l.info("================================================"),Le.successResult({statusCode:Ee.OK,resultInfo:this.getPrinterInfo()})})}isDeviceConnected(t){return !!this.mConnection&&(this.PrintStatus>=Ze.ReadyPrint&&this.mConnection.deviceId===t)}getConnection(t){for(const e of this.mConnMap){if(t.deviceId&&t.deviceId===e[0])return e[1];if(t.name&&t.name===e[1].deviceName)return e[1]}return null}connect(e){return t(this,void 0,void 0,function*(){const t=e.device||{},i=t.deviceId;if(l.log(`---- DzPrinter.connect(${i}[${t.name}]), mPrintStatus: ${this.PrintStatus}`,e),!i)return {statusCode:Ee.ERROR_PARAM,errMsg:"未指定设备ID!"};const s=this.getConnection(t);if(s)if(s.isConnected){if(this.PrintStatus>Ze.Checking)return l.info(`---- 打印机已连接:${i}`),{statusCode:Ee.OK,errMsg:"设备已连接!",resultInfo:this.getPrinterInfo()};if(this.PrintStatus>Ze.Connected)return l.warn("---- 正在链接,请稍后..."),new Promise(t=>{const e=s.PrintStatusChanged.on(i=>{i===Ze.ReadyPrint?(s.PrintStatusChanged.off(e),t({statusCode:Ee.OK,resultInfo:this.getPrinterInfo()})):i===Ze.None&&(s.PrintStatusChanged.off(e),t({statusCode:Ee.ERROR_CONNECT_FAILED}));});})}else yield this.disconnectAll();else this.mConnection&&(yield this.disconnectAll());return yield this.createConnection(e)})}disconnectAll(e){return t(this,void 0,void 0,function*(){for(const t of this.mConnMap.values()){const i=yield this.disconnect(t.device,e);if(!i)return i}return true})}disconnect(e,i){return t(this,void 0,void 0,function*(){let t="string"==typeof e?{deviceId:e,name:e}:e;const s=t?this.getConnection(t):this.mConnection;if(!s)return true;if(t=s.device,t)if(t.deviceId){if(t.deviceId!==s.deviceId)return l.log(`---- 目标设备 ${t.name}[${t.deviceId}] 未连接,不需要执行断开操作!`),true}else if(t.name&&t.name!==s.deviceName)return l.log(`---- 目标设备 ${t.name} 未连接,不需要执行断开操作!`),true;const n=s.deviceName,r=s.deviceId;return l.info(`【DzPrinter】disconnect(${n}[${r}]) mPrintStatus: ${Ze[this.PrintStatus]}`),this.PrintStatus!==Ze.Printing||i||(yield new Promise(t=>{const e=s.PrintStatusChanged.on(i=>{(i===Ze.ReadyPrint||i>Ze.Printing)&&(s.PrintStatusChanged.off(e),t(e));});})),this.mConnMap.has(s.deviceId)&&this.mConnMap.delete(s.deviceId),this.mConnection===s&&(this.mConnection=void 0),s.disconnect()})}setPrinterParam(t){!this.mConnection||this.PrintStatus<Ze.ReadyPrint||this.PrintStatus===Ze.Sending||this.mConnection.checkAndSendPrintParams(t);}pushPrintJob(t){if(!this.mConnection)return false;const e=Ze[this.mConnection.printStatus];return l.info(`<<<--- ❤️❤️❤️ ■#■#■ pushImageData[${this.mJobId+1}], PrintStatus: ${e} ■#■#■ ❤️❤️❤️ ---\x3e>>`),this.mConnection.printJob(t)}stopPrint(){this.mConnection&&this.mConnection.cancelPrintJob();}continuePrint(){return this.mConnection&&this.mConnection.isConnected?this.mConnection.continuePrintJob():Promise.resolve(Ee.ERROR_DISCONNECTED)}encodeImageData(t){t.data&&t.width&&t.height&&("string"==typeof t.data&&(t.data=Le.hex16ToArrayBuffer(t.data)),t.imageData={width:t.width,height:t.height,data:t.data,colorSpace:"srgb"});const e=Ke.encodeImageData(t),i={valueType:t.valueType||ti.Binary,values:e};return i.valueType===ti.Hex16?i.values=e.map(t=>Le.arrayBufferToHex16(t)):i.valueType===ti.Base64&&(i.values=e.map(t=>Le.arrayBufferToBase64(t))),i}pushImageData(t){const e={statusCode:Ee.OK};this.PrintStatus===Ze.Paused&&this.stopPrint(),t.data&&t.width&&t.height&&("string"==typeof t.data&&(t.data=Le.hex16ToArrayBuffer(t.data)),t.imageData={width:t.width,height:t.height,data:t.data,colorSpace:"srgb"});const i=t.imageDataArray||[];if(i.length<=0&&t.imageData&&i.push(t.imageData),!i||i.length<=0)return e.statusCode=Ee.ERROR_PARAM,e.status=e.statusCode,t.onJobComplete&&t.onJobComplete(e),e;if(this.PrintStatus<Ze.ReadyPrint)return e.statusCode=Ee.ERROR_DISCONNECTED,e.status=e.statusCode,t.onJobComplete&&t.onJobComplete(e),e;{const s=this.mJobId++;return t.imageDataArray=i,this.pushPrintJob({jobId:s,jobOptions:t,jobPushed:()=>{l.info(`======== 打印任务 [${s}] 添加成功!`),t.jobPushed&&t.jobPushed(s);},onPageSendComplete:e=>{const i=e.pageKey||0;l.log(`---- 打印页面 [${s} - ${i}(0x${i.toString(16)})] 数据发送结束: { result: ${e.statusCode}, page: [${e.pageIndex+1} / ${e.printPages}], copy: [${e.copyIndex+1} / ${e.printCopies}]}`),e.status=e.statusCode,t.onPageComplete&&t.onPageComplete(e);},onPagePrintComplete:(i,n)=>{const r=i.pageKey||0;l.log(`---- 打印页面 [${s} - ${r}(0x${r.toString(16)})] 打印结束: { result: ${i.statusCode}, page: [${i.pageIndex+1} / ${i.printPages}], copy: [${i.copyIndex+1} / ${i.printCopies}]}`),t.onPagePrintComplete&&t.onPagePrintComplete(i),e.statusCode=i.statusCode,e.printable=i.printable,i.statusCode!==Ee.OK?t.onJobPrintComplete&&t.onJobPrintComplete(e):i.pageIndex+1===i.printPages&&i.copyIndex+1===i.printCopies&&(l.info(`★★★★★ 打印任务【${n.jobId}】 打印完毕全部打印完毕! ★★★★★`),t.onJobPrintComplete&&t.onJobPrintComplete(e));},onJobSendComplete:i=>{l.info(`======== 打印任务 [${s}] 处理完毕!`),Object.assign(e,{statusCode:i,status:i,printable:this.Printable}),t.onJobComplete&&t.onJobComplete(e);}}),e}}pushRawData(t){const e={statusCode:Ee.OK};this.PrintStatus===Ze.Paused&&this.stopPrint();const i=t.rawData;if(!i||i.length<=0)return e.statusCode=Ee.ERROR_PARAM,e.status=e.statusCode,t.onJobComplete&&t.onJobComplete(e),e;if(this.PrintStatus<Ze.ReadyPrint)return e.statusCode=Ee.ERROR_DISCONNECTED,e.status=e.statusCode,t.onJobComplete&&t.onJobComplete(e),e;{const s=this.mJobId++;return t.rawData=i,this.pushPrintJob({jobId:s,jobOptions:t,jobPushed:()=>{l.info(`======== 打印任务 [${s}] 添加成功!`),t.jobPushed&&t.jobPushed(s);},onPageSendComplete:e=>{const i=e.pageKey||0;l.log(`---- 打印页面 [${s} - ${i}(0x${i.toString(16)})] 数据发送结束: { result: ${e.statusCode}, page: [${e.pageIndex+1} / ${e.printPages}], copy: [${e.copyIndex+1} / ${e.printCopies}]}`),e.status=e.statusCode,t.onPageComplete&&t.onPageComplete(e);},onPagePrintComplete:(i,n)=>{const r=i.pageKey||0;l.log(`---- 打印页面 [${s} - ${r}(0x${r.toString(16)})] 打印结束: { result: ${i.statusCode}, page: [${i.pageIndex+1} / ${i.printPages}], copy: [${i.copyIndex+1} / ${i.printCopies}]}`),t.onPagePrintComplete&&t.onPagePrintComplete(i),e.statusCode=i.statusCode,e.printable=i.printable,i.statusCode!==Ee.OK?t.onJobPrintComplete&&t.onJobPrintComplete(e):i.pageIndex+1===i.printPages&&i.copyIndex+1===i.printCopies&&(l.info(`★★★★★ 打印任务【${n.jobId}】 打印完毕全部打印完毕! ★★★★★`),t.onJobPrintComplete&&t.onJobPrintComplete(e));},onJobSendComplete:i=>{l.info(`======== 打印任务 [${s}] 处理完毕!`),Object.assign(e,{statusCode:i,status:i,printable:this.Printable}),t.onJobComplete&&t.onJobComplete(e);}}),e}}printImageData(t){return new Promise(e=>{this.pushImageData(Object.assign(Object.assign({},t),{onJobComplete:i=>{t.onJobComplete&&t.onJobComplete(i),e(i);}}));})}printRawData(t){return new Promise(e=>{this.pushRawData(Object.assign(Object.assign({},t),{onJobComplete:i=>{t.onJobComplete&&t.onJobComplete(i),e(i);}}));})}queryCommand(e,i){return t(this,void 0,void 0,function*(){return this.mConnection?this.mConnection.queryCommand(e,i):Le.complete(Ee.ERROR_DISCONNECTED,void 0)})}writeCommands(e){return t(this,void 0,void 0,function*(){if(!this.mConnection||!this.IsConnected)return Le.complete(Ee.ERROR_DISCONNECTED,"设备未连接!",e);const t=ai.parsePackageList(e.value,[],[]);return !t||t.length<=0?Le.complete(Ee.ERROR_PARAM,`无效的指令:${Le.arrayBufferToHex16(e.value)}`,e):this.mConnection.pushPackageListRequest(t,e.timeout).then(t=>{if(0!==t.statusCode)return Le.complete(t.statusCode,t.resultInfo,e);const i=t.resultInfo,s=i.pkgList.map(t=>{var e;return null===(e=t.receivedPkg)||void 0===e?void 0:e.getRawData()});return Le.complete(t.statusCode,Object.assign(Object.assign({},i),{sendData:i.sendData,data:Le.concatUint8Array(s)}),e)})})}requestPositioningInfo(e){return t(this,void 0,void 0,function*(){var t;const e=this.mConnection;if(!e||!e.isConnected)return Le.complete(Ee.ERROR_DISCONNECTED,"打印机未连接");const i=e.printerInfo.hardwareFlags||0;if(!(8&i))return l.warn(`---- 当前打印机不支持北斗定位功能,hardwareFlags = ${Le.toHexString(i,"0x")}`),Le.complete(Ee.ERROR_UN_SUPPORTED,"当前设备不支持北斗定位功能!");const s=yield this.queryCommand(Ge.CMD_POSITIONING,[1]),n=null===(t=s.resultInfo)||void 0===t?void 0:t.respPkg;return 0==s.statusCode&&n?this.parsePositioningPackage(n):Le.complete(s.statusCode,s.errMsg||"")})}}mi.trades="",mi.sDeTongCheckSum="5682904137",mi.patternGeneral=/^(.*)-([A-Z]{0,2}[0-9]{4,5}[0-9A-Z]{2,5}[0-9]{2})$/,function(t){t.text="text";}(ei||(ei={}));class Ci{static createDomParser(){try{return window.DOMParser?new DOMParser:void 0}catch(t){return void l.warn(t)}}static parseXmlDocument(t,e){if(t)try{const i=e||new DOMParser;return t?i.parseFromString(t,"text/xml"):void 0}catch(t){l.warn("xml parse error:"),l.warn(t);}}static splitEqual(t,e){const i=(t||"").split(";");for(const t of i)if(t===e)return true;return false}static getElementsByTagName(t,e,i,s){if(!t||!e||t.childElementCount<=0)return [];if(i){const i=[],n=t.children||t.childNodes;let r="";for(let t=0;t<n.length&&(r=n[t].tagName||n[t].nodeName,r.toLowerCase()!==e.toLocaleLowerCase()||(i.push(n[t]),!s));t++);return i}return t.getElementsByTagName(e)}static getElementByTagName(t,e,i){return this.getElementsByTagName(t,e,i,true)[0]}static getElementValue(t){try{return t.childNodes[0].nodeValue||""}catch(t){return ""}}static getElementValueByTagName(t,e){if(!e)return "";const i=e.split(";");for(let e=0;e<i.length;e++){const s=i[e];if(!s)continue;const n=this.getElementsByTagName(t,s,true,true);if(n.length>0)return this.getElementValue(n[0])}return ""}static isNumberString(t,e){return !!t&&(!!(t=t.trim()).match(/^[-+]?[0-9]*\.?[0-9]+$/)||!(!e||!t.match(/^(0x)?[0-9a-f]+$/i)))}static isHexString(t){return !!t&&!!t.match(/^(0x)?[0-9a-f]+$/i)}static optNumber(t,e){return "number"==typeof t?t:(t=(t||"").trim(),this.isNumberString(t)?Number(t):this.isHexString(t)?parseInt(t,16):e||0)}static isBooleanString(t){return !!t&&!!(t=t.trim()).match(/^(yes)|(no)|(true)|(false)$/i)}static optBoolean(t,e){return !!(t=(t||"").trim()).match(/^(yes)|(true)$/i)||!t.match(/^(no)|(false)$/i)&&("boolean"==typeof e&&e)}static decodeBase64File(t,e){const i=Le.decodeBase64(t);if(i){try{return new File([i],e)}catch(t){l.warn(t);}try{return new Blob([i])}catch(t){l.warn(t);}}}static parseEmbeddedImg(t,e){if(!t)return t;const i=t.indexOf(Ci.EmbeddedSeparator);if(i<0)return t;let s=t.substring(0,i).trim().toLowerCase();return "."===s[0]&&(s=s.substring(1)),"svg"===s&&(s="svg+xml"),t=t.substring(i+Ci.EmbeddedSeparator.length),e&&e(s,t),`data:image/${s};base64,${t}`}static parseEmbeddedFile(t){if(!(t=(t||"").trim()))return;const e=t.indexOf(Ci.EmbeddedSeparator);let i;if(e>=0){const s=t.substring(0,e),n=t.substring(e+Ci.EmbeddedSeparator.length);i=Ci.decodeBase64File(n,s);}else i=Ci.decodeBase64File(t,"");return i}}Ci.EmbeddedSeparator="*****";class Pi{static isWdfxJob(t){const e=t||{};return !(!e.layerClass||!e.templateID)&&("LPAPI"===e.layerClass.toUpperCase()&&(e.Page||e.page||[]).length>0)}static getDefaultBarcodeContent(t,e){return e&&"string"==typeof e.defaultBarcodeContent?e.defaultBarcodeContent:t===b.EAN13?"690123456789":t===b.EAN8?"6901234":t===b.UPC_A?"69012345678":t===b.UPC_E?"0123456":t===b.ISBN?"978012345678":"12345678"}static getDefaultQrcodeContent(t){return "string"==typeof t.defaultQrcodeContent?t.defaultQrcodeContent:"http://detonger.com/wdbq"}static getDefaultTextContent(t){return "string"==typeof t.defaultTextContent?t.defaultTextContent:""}static getContentText(t,e,i){const s="number"==typeof e.contentType?e.contentType:0,n=e.content||e.text,r=i||{};if(t=t.toLowerCase(),2===s){if(!n){if(t===ve.barcode){const t=Ci.optNumber(e.barcodeType);return Pi.getDefaultBarcodeContent(t,r)}if(t===ve.qrcode)return Pi.getDefaultQrcodeContent(r)}return n}if(s>0||n)return n;if(t===ve.text)return n||Pi.getDefaultTextContent(r);if(t===ve.qrcode)return n||Pi.getDefaultQrcodeContent(r);if(t===ve.barcode){const t=Ci.optNumber(e.barcodeType);return Pi.getDefaultBarcodeContent(t,r)}return n}static rotateRect(t,e){(e=(e+360)%360)>3&&(e=Math.floor(e/90));const i=t.x||0,s=t.y||0,n=t.width||0,r=t.height||0,a=i+.5*n,o=s+.5*r;return 1!==e&&3!==e||(t.x=a-.5*r,t.y=o-.5*n,t.width=r,t.height=n),t}static getDateTime(t){const i=t.dateFormat||"",s=t.timeFormat||"",n=t.dateOffset||t.dateDiff||0,r=t.hourOffset||t.hourDiff||0,a=t.minuteOffset||t.minuteDiff||0,o=t.secondOffset||t.secondDiff||0,h=new Date;if(n||r||a||o){let t=h.getTime();n&&(t+=864e5*n),r&&(t+=36e5*r),a&&(t+=6e4*a),o&&(t+=1e3*o),h.setTime(t);}return i&&s?e.formatDate(`${i} ${s}`):i||s?e.formatDate(i||s,h):e.formatDate("yyyy年MM月dd日")}static parseWdxNode(t,e,i){if(t.children&&t.children.length>0){const s={},n=[];for(let r=0;r<t.children.length;r++){const a=t.children[r],o="function"==typeof e&&e(a,t),h=this.parseWdxNode(a,e,o);i?("object"!=typeof h||Array.isArray(h)||(h.layerClass=a.tagName),n.push(h)):s[a.tagName]=h;}return i?n:s}if(t.childNodes&&t.childNodes.length>1){const s={},n=[];for(let r=0;r<t.childNodes.length;r++){const a=t.childNodes[r];if(a.nodeName===Pi.NODE_NAME_TEXT)continue;const o="function"==typeof e&&e(a,t),h=this.parseWdxNode(a,e,o);i?("object"!=typeof h||Array.isArray(h)||(h.layerClass=a.nodeName),n.push(h)):s[a.nodeName]=h;}return i?n:s}return t.childNodes&&t.childNodes.length>0&&t.childNodes[0].nodeValue||""}static getAutoValue(t){const e=t?t.toLowerCase():"";return "true"===e||"yes"===e||"false"!==e&&"no"!==e&&(Ci.isNumberString(e)?Number(e):t)}static loadWdfxContent(t,e){const i=Ci.parseXmlDocument(t||"",e),s=i?i.getElementsByTagName("LPAPI"):void 0,n=s&&s.length>0?s[0]:void 0;if(!n)return;const r=this.parseWdxNode(n,(t,e)=>{const i=(t.tagName||t.nodeName||"").toLowerCase(),s=(e.tagName||e.nodeName||"").toLowerCase();return e===n&&"page"===i||"table"===s&&"cells"===i});return "string"==typeof r||Array.isArray(r)?void 0:(r.layerClass=n.tagName,r)}static updateWdfOptions(t,i,s){const n=t,r=t;for(const t of Object.keys(r)){let e=r[t];"drawColorHex"!==t?("string"==typeof e&&(r[t]=e=Pi.getAutoValue(e)),"labelWidth"===t?(n.jobWidth=e,delete r[t]):"labelHeight"===t?(n.jobHeight=e,delete r[t]):"labelName"===t?(n.jobName=e,delete r[t]):"printOrientation"===t&&(n.orientation=e,delete r[t])):e&&"0"!==e&&(n.drawColor=e);}n.jobWidth||n.width||(n.jobWidth=40),n.jobHeight||n.height||(n.jobHeight=30),"string"==typeof n.background&&(n.background=Ci.parseEmbeddedImg(n.background));let a=[];if(t.Page?(a=t.Page,delete t.Page):t.page&&(a=t.page,delete t.page),n.border&&"string"==typeof n.border)try{const t=Ci.parseEmbeddedImg(n.border,(t,s)=>{if(n.borderType=t,i||"undefined"==typeof DOMParser||(i=new DOMParser),"svg+xml"===t&&i){"number"!=typeof n.borderScale&&(n.borderScale=1);try{const t=i.parseFromString(Le.atob(s),"image/svg+xml"),r=t?t.getElementsByTagName("svg"):void 0,a=r&&r.length>0?r[0]:void 0;if(a&&(n.svgElement=a,a.width&&(n.svgWidth=a.width.baseVal.value),a.height&&(n.svgHeight=a.height.baseVal.value),a.viewBox&&(n.svgViewBox=a.viewBox.baseVal),!n.svgViewBox&&a.attributes&&a.attributes.length>0))for(let t=0;t<a.attributes.length;t++){const i=a.attributes[t],s=i.name||i.nodeName||i.localName;if("width"===s){const t=i.value||i.nodeValue||"";!n.svgWidth&&Ci.isNumberString(t)&&(n.svgWidth=Ci.optNumber(t));}else if("height"===s){const t=i.value||i.nodeValue||"";!n.svgHeight&&Ci.isNumberString(t)&&(n.svgHeight=Ci.optNumber(t));}else if("viewBox"===s){const t=i.value||i.nodeValue||"";!n.svgViewBox&&t&&(n.svgViewBox=e.parseRect(t));}}}catch(t){l.warn(t);}}});n.border=t;}catch(t){l.warn(t);}const h=[];if(a&&a.length>0)for(const t of a){const e=t,i=e.layerClass?e.layerClass.toLowerCase():"";for(const t of Object.keys(e)){const i=e[t];"content"!==t&&"lineSpace"!==t&&"columnName"!==t&&("drawColorHex"!==t?"dataColumnName"===t&&void 0!==e.dataColumnName&&void 0===e.columnName?e.columnName=e.dataColumnName:"string"==typeof i&&(e[t]=Pi.getAutoValue(i)):i&&"0"!==i&&(e.color=i));}if(void 0===e.horizontalAlignment&&"number"==typeof e.horAlignment&&(e.horizontalAlignment=e.horAlignment),void 0===e.verticalAlignment&&"number"==typeof e.verAlignment&&(e.verticalAlignment=e.verAlignment),i===ve.line){const t=e.x1||0,i=e.y1||0,s=e.x2||0,n=e.y2||0;"number"==typeof e.x1&&delete e.x1,"number"==typeof e.y1&&delete e.y1,"number"==typeof e.x2&&delete e.x2,"number"==typeof e.y2&&delete e.y2,e.x=Math.min(t,s),e.y=Math.min(i,n),e.width=Math.abs(t-s),e.height=Math.abs(i-n);}if(e.width&&e.height&&e.orientation&&Pi.rotateRect(e,-e.orientation),i===ve.text)e.text=Pi.getContentText(i,e,s),h.push(Object.assign(Object.assign({},e),{lineSpaceMode:g.getLineMode(e.lineSpace),lineSpace:g.valueOf(e.lineSpace,e.fontHeight||2.5),type:ve.text,rotateMode:o.RotateCanvas}));else if("time"===i||"date"===i)e.text=Pi.getDateTime(e),h.push(Object.assign(Object.assign({},e),{type:ve.text,rotateMode:o.RotateCanvas}));else if("arctext"===i)e.text||(e.text=Pi.getContentText(ve.text,e,s)),h.push(Object.assign(Object.assign({},e),{lineWidth:"number"==typeof e.lineWidth?e.lineWidth:.5,type:ve.arcText}));else if(i===ve.barcode)e.text=Pi.getContentText(i,e,s),"number"!=typeof e.horizontalAlignment&&(e.horizontalAlignment=1),h.push(Object.assign(Object.assign({},e),{barcodeType:"number"==typeof e.type?e.type:e.barcodeType,type:ve.barcode}));else if(i===ve.qrcode)e.text=Pi.getContentText(i,e,s),"number"!=typeof e.horizontalAlignment&&(e.horizontalAlignment=1),"number"!=typeof e.verticalAlignment&&(e.verticalAlignment=1),h.push(Object.assign(Object.assign({},e),{type:ve.qrcode,barcodeType:e.type}));else if("image"===i||"logo"===i){const t=e.content||e.text;e.content&&delete e.content,e.text&&delete e.text,h.push(Object.assign(Object.assign({},e),{image:Ci.parseEmbeddedImg(t),alignment:e.tile?3:1,type:ve.image}));}else if("rectangle"===i||"rect"===i){let t=ve.rect;"boolean"==typeof e.filled&&e.filled&&(e.fill=true,delete e.filled),("number"!=typeof e.lineWidth||e.lineWidth<=0)&&(e.lineWidth=.5),1===e.type?("number"!=typeof e.cornerWidth||e.cornerWidth<=0)&&(e.cornerWidth=1):2===e.type?t=ve.ellipse:3===e.type?t=ve.circle:e.cornerWidth&&delete e.cornerWidth,h.push(Object.assign(Object.assign({},e),{type:t}));}else if(i===ve.line){const t="number"==typeof e.type?e.type:0,i="number"==typeof e.dashGap&&e.dashGap>0?e.dashGap:1;1===t&&(e.dashLens=[i]),e.dashGap&&delete e.dashGap,h.push(Object.assign(Object.assign({},e),{type:ve.line}));}else if(i===ve.table){const t=e.Cells||e.cells||[];if(e.Cells&&delete e.Cells,Array.isArray(t)&&t.length>0)for(const e of t)for(const t of Object.keys(e)){const i=e[t];"content"!==t&&"lineSpace"!==t&&"dataColumnName"!==t&&"columnName"!==t&&("string"==typeof i&&(e[t]=Pi.getAutoValue(e[t])));}h.push(Object.assign(Object.assign({},e),{rowCount:e.rows,columnCount:e.cols,cells:t,type:ve.table}));}else i?h.push(Object.assign(Object.assign({},e),{type:i})):"string"==typeof e.type&&h.push(e);}return {jobInfo:t,jobPage:h}}static parseWdfx(t,e){let i;i="object"==typeof t?t:{content:t,domParser:e};const s=Pi.loadWdfxContent(i.content,i.domParser);return s&&Pi.isWdfxJob(s)?Pi.updateWdfOptions(s,i.domParser):void 0}}Pi.NODE_NAME_TEXT="#text",function(t){t[t.RawData=1]="RawData",t[t.Preview=2]="Preview",t[t.Image=32]="Image",t[t.ImageData=33]="ImageData",t[t.Transparent=128]="Transparent",t[t.TransPrev=130]="TransPrev",t[t.Print=4096]="Print";}(ii||(ii={}));class Ri{static getInstance(t){const e=t||{};return this.sInstance?t&&this.sInstance.setOptions(t):this.sInstance=new Ri(e),this.sInstance}static create(t){return new Ri(t)}static isPreviewJobName(t){return !!t&&xe.isPreviewJobName(t)}static isTransPrevJob(t){return !!t&&xe.isTransPrevJob(t)}static isWhitePrevJob(t){return !!t&&xe.isWhitePrevJob(t)}static registerBarcode1DEncoder(t,e){Mt.registerBarcodeCreator(t,e);}static registerBarcode2DEncoder(t){Re.getInstance().register(t);}static loadImageSrc(t){return xe.loadImageSrc(t)}static loadHtmlImage(t){return xe.html2Image(t)}static getRawData(t){return Ke.encodeImageData({imageData:t,printerDPI:203,printerWidth:384})}static setLogLevel(t){"number"==typeof t?l.setLevel(t):"boolean"==typeof t&&l.setLevel(t?3:0);}static getResultMessage(t){return Le.getResultMessage(t)}static getPrintableMessage(t){return Ge.getPrintableMessage(t)}static getJobName(t,e,i){return t&&t>0&&(t&ii.Preview?e=t&ii.Transparent?Ae.JOB_NAME_TRANS:Ae.JOB_NAME_PREV:t&ii.RawData&&(e=t&ii.Image?Ae.JOB_NAME_DATA_IMAGE:Ae.JOB_NAME_DATA)),e||(i?Ae.JOB_NAME_PREV:"")}static getJobAction(t,e,i){return !t&&e&&((e=e.toLowerCase()).startsWith(Ae.JOB_NAME_TRANS.substring(0,8))?t=ii.TransPrev:e.startsWith(Ae.JOB_NAME_PREV.substring(0,7))?t=ii.Preview:e.startsWith(Ae.JOB_NAME_DATA.substring(0,6))?t=ii.RawData:e.startsWith(Ae.JOB_NAME_DATA_IMAGE.substring(0,12))&&(t=ii.ImageData)),t&&t>0?t:i?ii.Preview:ii.Print}static test(){}constructor(t){this.mJsonMode=false,this.mLineHeight=0,this.mCurrPosY=0,this.mJobPage=[],this.mTotalPages=1,this.mPageIndex=0,this.mPageList=[];const e=t||{};this.mInitInfo=e,this.setOptions(t);}authorize(t){const e=this.mPrinter.Manager;return e?e.authorize(t):Promise.resolve(Le.complete(Ee.ERROR_UN_SUPPORTED,"",t))}init(t){return this.authorize(t)}setOptions(t){const e=t||{},i=this.mPrinter?this.mPrinter.Manager:void 0;e.manager&&e.manager!==i?this.setDeviceManager(e.manager):e.adapter&&!i?this.setDeviceManager(pi.create(e.adapter)):this.setDeviceManager(void 0),this.mInitInfo=Object.assign(this.mInitInfo,e),e.context&&this.setDrawContext(e.context),e.models&&this.setSupportPrefixes(e.models),"string"==typeof e.bleFilters&&mi.setBleFilters(e.bleFilters),this.mJobPrintOptions&&e.resetJob&&this.abortJob(),this.mPrinter.setInitOptions(e),Ri.setLogLevel("number"==typeof e.logLevel?e.logLevel:e.showLog);}getBarcode2DEncoder(t){return t?Re.getEncoder(t):void 0}setBarcode2DEncoder(t){return "object"==typeof t&&Re.setEncoder(t.barcodeType,t)}isPreviewMode(t,e){if(e&&e>0){if(e&ii.RawData||e&ii.Print)return false;if(e&ii.Preview)return true}const i=!!t.jobName&&xe.isPreviewJobName(t.jobName);return this.Context.isPreviewMode(t,i)}setDeviceManager(t){this.mPrinter?this.mPrinter.Manager=t:this.mPrinter=new mi(t);}getContext(){if(!this.mContext){let t=this.mInitInfo.createContext?this.mInitInfo.createContext({}):void 0;t||(t=new xe({adjustFontSize:this.mInitInfo.adjustFontSize})),this.setDrawContext(t);}return this.mContext}get Context(){return this.getContext()}get drawContext(){return this.mContext}get Printer(){return this.mPrinter}requestPositioningInfo(t){return this.mPrinter.requestPositioningInfo(t)}setDrawContext(t){var e;l.log("#### 【LPAPI.setDrawContext】:",t),t&&t!==this.mContext&&t.instanceId!==(null===(e=this.mContext)||void 0===e?void 0:e.instanceId)&&(l.log("---- oldContext: ",this.mContext),this._abortJob(),t.IsApiMode=true,this.mContext=t,t.resetCanvas({jobWidth:this.mInitInfo.jobWidth,jobHeight:this.mInitInfo.jobHeight}));}createDrawContext(t){return this.mInitInfo.createContext?this.mInitInfo.createContext(t):new xe(Object.assign({apiMode:true,willReadFrequently:true,adjustFontSize:this.mInitInfo.adjustFontSize},t))}loadImage(t,e){return this.Context.loadImage(t).then(t=>(e&&e(t),t))}loadHtml(t){return this.Context.loadHtml("string"==typeof t?t:t?t.innerHTML:"")}setSupportPrefixes(t){mi.setSupportModels(t);}setSupportTrades(t){mi.trades=Array.isArray(t)?t.join(";"):t||"",mi.trades&&(mi.trades=mi.trades.toUpperCase());}openAdapter(t){const e=t||{};return this.mPrinter.openAdapter(Object.assign({webBLE:this.mInitInfo.webBLE,webHID:this.mInitInfo.webHID,webUSB:this.mInitInfo.webUSB},e))}closeAdapter(t){return this.closePrinter().then(()=>this.mPrinter.closeAdapter(t))}resetAdapter(t){return this.closePrinter().then(()=>this.mPrinter.resetAdapter(t))}startBleDiscovery(e){return t(this,void 0,void 0,function*(){const t=e||{};return l.log(t,"【LPAPI.startBleDiscovery】options:"),this.mPrinter.startDiscovery(t)})}startDiscovery(e){return t(this,void 0,void 0,function*(){const t=e||{};return l.log(t,"【LPAPI.startDiscovery】 options:",e),this.mPrinter.startDiscovery(t)})}stopBleDiscovery(){return t(this,void 0,void 0,function*(){return this.mPrinter.stopDiscovery()})}stopDiscovery(){return t(this,void 0,void 0,function*(){return this.mPrinter.stopDiscovery()})}searchPrinter(e){return t(this,void 0,void 0,function*(){const t=e||{};return new Promise(e=>{let i=false;this.startDiscovery({timeout:t.timeout||0,models:t.models,deviceFound:s=>{if((null==s?void 0:s.length)>0){let n;for(const e of s){if(!t.name&&!t.deviceId){n=e;break}if(t.name&&t.name===e.name){n=e;break}if(t.deviceId&&t.deviceId===e.deviceId){n=e;break}}n&&(i=true,e(n),this.stopDiscovery());}},adapterStateChange:t=>{t.discovering||i||(i=true,e(void 0));}}).then(t=>{0!==t.statusCode&&e(void 0);});})})}getPrinters(t){return this.mPrinter.getPrinters(t)}getFoundDevices(t){return this.mPrinter.getFoundDevices(t)}requestDevice(e){return t(this,void 0,void 0,function*(){return this.mPrinter.requestDevice(e)})}getDevices(t){return this.mPrinter.getDevices(t)}getPrinterInfo(){return this.mPrinter.getPrinterInfo()}getPrinterWidthMM(){const t=this.mPrinter.getPrinterInfo();return t&&t.printerWidth>0&&t.printerDPI>0?t.printerWidth/t.printerDPI*25.4:48}isPrinterOpened(){return this.mPrinter.IsConnected||false}isConnected(){return this.mPrinter.IsConnected||false}isJobPaused(){return this.mPrinter.PrintStatus===Ze.Paused}openPrinter(e){return t(this,void 0,void 0,function*(){l.log("#### 【LPAPI.openPrinter】options:",e);const t="function"==typeof e?e:void 0,i="string"==typeof e?e:void 0,s=!!i&&mi.isSupportedDevice(i),n="object"==typeof e?e:{name:s?i:"",deviceId:s?"":i,complete:t};return !n.deviceId&&n.id&&(n.deviceId=n.id),this.mPrinter.openPrinter(n)})}closePrinter(e,i){return t(this,void 0,void 0,function*(){const t="string"==typeof e?{deviceId:e,callback:i}:"function"==typeof e?{callback:e}:e;return this.stopPrint(),this.abortJob(),this.mPrinter.closePrinter(t)})}stopPrint(){this.mPrinter.stopPrint(),this.mPausedPrintInfo&&(this.mPausedPrintInfo=void 0);}isPrintJob(){return this.Context.isPrintJob}startJob(t){if(t||(t={}),"number"!=typeof t.width&&(t.width=0),"number"!=typeof t.height&&(t.height=0),l.info("#### 【LPAPI.startJob】:",t),t.context&&t.context!==this.mContext&&this.setDrawContext(t.context),!this.Context)return void l.warn("---- 未检测到绘制上下文!");if(this.mJobPrintOptions){if(!t.resetJob||!t.autoAbort)return void l.warn("---- 有未完成的打印任务!");this.abortJob();}if(this.isPrinterOpened()){const e=this.mPrinter.getPrinterInfo();t.dpi=e.printerDPI,t.printerDpi=e.printerDPI,t.printerWidth=e.printerWidth;}else t.dpi||(t.dpi=this.mPrinter.PrinterDPI),t.printerDpi||(t.printerDpi=t.dpi),t.printerWidth||(t.printerWidth=this.mPrinter.PrinterWidth);const e=t.action||0;"boolean"!=typeof t.isPreview&&(t.isPreview=this.isPreviewMode(t,e)),t.jobName||(t.isPreview?t.jobName=e&ii.Transparent?Ri.JOB_NAME_TRANS:Ri.JOB_NAME_PREV:t.jobName=e&ii.RawData?Ri.JOB_NAME_RAW_DATA:Ri.JOB_NAME_PRINT);const i="object"==typeof t.printerInfo?t.printerInfo:{};i.name||(i.name=t.deviceName||t.printerName),i.deviceId||(i.deviceId=t.deviceId),i.printerDPI||(i.printerDPI=t.printerDpi),i.printerWidth||(i.printerWidth=t.printerWidth),"boolean"!=typeof t.jsonMode&&(t.height<=0?t.jsonMode=true:t.isPreview||this.isPrinterOpened()||!i.name&&!i.deviceId||t.action&&t.action===ii.RawData||(t.jsonMode=true)),this.mJsonMode="boolean"==typeof t.jsonMode&&t.jsonMode;const s=xe.getMargins(t);return this.mLineHeight="number"==typeof t.lineHeight?t.lineHeight:0,this.mLineHeight<0&&(this.mLineHeight=0),this.mJobPrintOptions={jobInfo:Object.assign(Object.assign({},t),{jobWidth:t.width,jobHeight:t.height}),printerInfo:i,jobPages:[],jobArguments:t.jobArguments,onJobCreated:t.onJobCreated},this.mJobPage.splice(0),this.mJsonMode?this.mCurrPosY=s[0]>0?s[0]:0:(t.width<=0&&(t.width=this.getPrinterWidthMM()),this.mPageList.splice(0),this.mTotalPages=t.printPages||0,this.mPageIndex=0,this.mPageInfo=void 0),this.startPage()}startPrintJob(e,i){return t(this,void 0,void 0,function*(){"function"==typeof e.callback&&(i=e.callback),"boolean"!=typeof e.isPreview&&(e.isPreview=this.isPreviewMode(e));const t=Ri.getJobAction(e.action,e.jobName,e.isPreview);if(!(t&ii.Preview||t&ii.RawData)){const t=yield this.openPrinter({name:e.printerName||e.deviceName,deviceId:e.deviceId,autoScan:false});if(t.statusCode!==Ee.OK)return i&&i(t),t}const s=this.startJob(e),n={statusCode:s?Ee.OK:Ee.ERROR_JOB_CREATE,resultInfo:s};return i&&i(n),n})}_abortJob(){this.mPageInfo=void 0,this.mJobPrintOptions=void 0;}abortJob(){l.log("#### 【LPAPI.abortJob】"),this._abortJob();}toDataURL(){return this.Context.CanvasElement.toDataURL()}nextLine(t){"number"==typeof t&&(this.mLineHeight=t),this.mCurrPosY+=this.mLineHeight;}getPosY(){return this.mCurrPosY}getCommandDatas(){}commitJob(e,i){return t(this,void 0,void 0,function*(){var t;const s="function"==typeof e?{onJobComplete:e}:e||{};"function"!=typeof s.onJobComplete&&"function"==typeof i&&(s.onJobComplete=i);const n=null===(t=this.mJobPrintOptions)||void 0===t?void 0:t.jobInfo;return n?(l.info("#### 【LPAPI.commitJob - start】options:",s),this.endPage(Object.assign({},s)).then(t=>{const i=this.mJobPrintOptions;if(l.info(`$$$$ 【LPAPI.commitJob - end】 statusCode: ${t.statusCode}`),this.mJobPrintOptions=void 0,t.statusCode===Ee.OK){if(this.mJsonMode){if(i&&i.jobPages&&i.jobPages.length>0){const t=i.jobInfo||{};let e;const n=s;for(const s of Object.keys(n))e=n[s],"function"==typeof e?i[s]=e:null!=e&&(t[s]=e);const r=s.jobArguments?s.jobArguments:i.jobArguments;return this.print(Object.assign(Object.assign({},i),{jobArguments:r}))}return Le.failResult({statusCode:Ee.ERROR_PARAM,resultInfo:"接口调用错误,未检测到有效的打印参数"})}const r=this.mPageList.map(t=>t.printData).filter(t=>!!t),a=this.mPageList.map(t=>t.imageData).filter(t=>!!t),o=Ri.getJobPrintResult(t,this.mPageList,t,r.length>0?r:void 0,a);return s.onJobComplete?s.onJobComplete(o):s.jobComplete&&s.jobComplete(o),n.onJobComplete?n.onJobComplete(o):n.jobComplete&&n.jobComplete(o),Le.successResult(o,e)}return s.onJobComplete?s.onJobComplete(t):s.jobComplete&&s.jobComplete(t),n.onJobComplete?n.onJobComplete(t):n.jobComplete&&n.jobComplete(t),Le.onResult(t,e)}).catch(t=>(l.warn("$$$$ 【commitJob - exception】",t),s.onJobComplete&&s.onJobComplete({statusCode:Ee.ERROR_EXCEPTION,resultInfo:t}),Le.complete(Ee.ERROR_EXCEPTION,t,e)))):(l.warn("#### 【LPAPI.commitJob - start】未检测到打印任务!options:",s,this.mJobPrintOptions),Le.failResult({statusCode:Ee.ERROR_PARAM,resultInfo:"未检测到打印任务!"}))})}startPage(){var t;if(l.info("#### 【LPAPI.startPage】",this.mJobPrintOptions),this.mJsonMode)return this.mJobPage.length>0&&this.endPage({}),{};const e=null===(t=this.mJobPrintOptions)||void 0===t?void 0:t.jobInfo;if(!e)return void l.warn("---- 未检测到打印任务相关信息!");if(this.mPageInfo)return this.mPageInfo;const i=this.Context,s=i.startJob(Object.assign({},e));return s?(this.mInitInfo.fontName&&i.setFontName(this.mInitInfo.fontName),this.mInitInfo.fontHeight&&i.setFontHeight(this.mInitInfo.fontHeight),this.mInitInfo.lineWidth&&i.setLineWidth(this.mInitInfo.lineWidth),this.mTotalPages<=this.mPageIndex&&(this.mTotalPages=this.mPageIndex+1),this.mPageResult=void 0,this.mPageInfo=s):(e.onJobComplete&&e.onJobComplete({statusCode:Ee.ERROR_JOB_CANCELED}),e.onPagePrintComplete&&e.onPagePrintComplete({statusCode:Ee.ERROR_PARAM}),void l.warn(`---- 打印任务创建失败: {width: ${e.width}, height: ${e.height}}`))}endPage(e){return t(this,void 0,void 0,function*(){var t;const i="function"==typeof e?{onPageComplete:e}:e||{},s=!this.isPrintJob(),n=this.mPageInfo,r=null===(t=this.mJobPrintOptions)||void 0===t?void 0:t.jobInfo;l.info(`#### 【LPAPI.endPage】isPreview: ${null==r?void 0:r.isPreview}, jsonMode: ${this.mJsonMode}`);const a={statusCode:Ee.OK,printPages:this.mTotalPages,pageIndex:this.mPageIndex};if(this.mJsonMode){const t=this.mJobPage||[];if(this.mJobPrintOptions&&t.length>0){const e=this.mJobPrintOptions.jobPages||[];this.mJobPrintOptions.jobPages||(this.mJobPrintOptions.jobPages=e),e.push([...t]),t.splice(0);}else a.statusCode=Ee.ERROR_PARAM;return a}if(!n)return this.mJobPrintOptions&&this.mPageResult?Le.successResult(this.mPageResult):(l.warn("---- 打印任务异常,未检测到有效的打印 Page 信息!"),a.statusCode=Ee.ERROR_OTHER,a);if(!r)return a.statusCode=Ee.ERROR_OTHER,a;i.orientation||(i.orientation=this.Context.Orientation);const o=this.Context.JobInfo;return o&&("boolean"==typeof i.antiColor&&(o.antiColor=i.antiColor),"boolean"==typeof i.horizontalFlip&&(o.horizontalFlip=i.horizontalFlip)),this.Context.commitJob().then(t=>{this.mPageInfo=void 0,this.mPageIndex++;const e=t=>{"function"==typeof i.onPageComplete?i.onPageComplete(t):"function"==typeof i.pageComplete&&i.pageComplete(t),"function"==typeof r.onPageComplete?r.onPageComplete(t):"function"==typeof r.pageComplete&&r.pageComplete(t);};if(!t)return a.statusCode=Ee.ERROR_OTHER,e(a),a;if(Object.assign(a,t),s)return l.info("---- 预览任务处理完毕!"),a.statusCode=Ee.OK,e(a),a;{const s=(r.jobName||"").toLowerCase(),n=t.imageData;if(!r.action){const t=Ae.JOB_NAME_DATA_IMAGE.substring(0,12),e=Ae.JOB_NAME_DATA.substring(0,6);s.startsWith(t)?r.action=ii.ImageData:s.startsWith(e)&&(r.action=ii.RawData);}const o=r.action||0;if(n){if(o&ii.RawData){if(o&ii.Image)a.imageData=n;else {const t=this.mPrinter.encodeImageData(Object.assign(Object.assign({},r),{imageData:n}));a.printData=t.values;}return e(a),a}{const t=t=>{"function"==typeof i.onPagePrintComplete?i.onPagePrintComplete(t):"function"==typeof i.pagePrintComplete&&i.pagePrintComplete(t),"function"==typeof r.onPagePrintComplete?r.onPagePrintComplete(t):"function"==typeof r.pagePrintComplete&&r.pagePrintComplete(t);};if(!this.mPrinter.IsConnected)return a.statusCode=Ee.ERROR_DISCONNECTED,e(a),t(a),a;l.info("---- 开始打印......");const s=Le.filter(Object.assign(Object.assign({},r),i),(t,e)=>"function"!=typeof e);return this.printImageData(Object.assign(Object.assign({},s),{imageData:n,onPageComplete:t=>{t.errMsg||(t.errMsg=Le.getResultMessage(t.statusCode)),e(t);},onPagePrintComplete:e=>{e.errMsg||(e.errMsg=Le.getResultMessage(e.statusCode)),t(e);}})).then(t=>(a.statusCode=t.statusCode,t.errMsg||(t.errMsg=Le.getResultMessage(t.statusCode)),t.statusCode===Ee.OK&&t.printData&&(a.printData=t.printData[0]),a))}}return l.warn("---- imageData获取失败!"),a.statusCode=Ee.ERROR_GET_IMAGE_DATA,e(a),a}}).then(t=>(this.mPageInfo=void 0,this.mPageResult=t,this.mPageList.push(t),t))})}setItemHorizontalAlignment(t){this.Context.setItemHorizontalAlignment(t);}setItemVerticalAlignment(t){this.Context.setItemVerticalAlignment(t);}setItemOrientation(t){this.Context.setItemOrientation(t);}drawText(t){if(l.log("#### 【LPAPI.drawText】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),!this.mJsonMode)return this.Context.drawText(t);this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.text}));}splitText(t){return l.log("#### 【LPAPI.splitText】:",t),this.Context?this.Context.splitText(t):(l.warn("---- 未检测到绘制上下文,无法进行文本拆分!"),[])}measureText(t){return l.log("#### 【LPAPI.measureText】:",t),this.Context?this.Context.measureText(t):(l.warn("---- 未检测到绘制上下文,无法进行文本拆分!"),{})}drawBarcode(t){return "string"==typeof t.barcodeType?this.draw2DBarcode(t):this.draw1DBarcode(t)}draw1DBarcode(t){return l.log(`#### 【LPAPI.draw1DBarcode】type[${t.barcodeType}], options:`,t),void 0===t.y&&(t.y=this.mCurrPosY),this.mJsonMode?("number"==typeof t.type&&"number"!=typeof t.barcodeType&&(t.barcodeType=t.type),this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.barcode})),true):this.Context.draw1DBarcode(t)}draw2DBarcode(t){return l.log(`#### 【LPAPI.draw2DBarcode】type[${t.barcodeType}], options:`,t),void 0===t.y&&(t.y=this.mCurrPosY),this.mJsonMode?(this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.qrcode})),true):this.Context.draw2DBarcode(t)}drawQRCode(t){if(l.log("#### 【LPAPI.drawQRCode】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),!this.mJsonMode)return this.Context.drawQRCode(t);this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.qrcode}));}draw2DQRCode(t){return this.drawQRCode(t)}drawPDF417(t){if(l.log("#### 【LPAPI.drawPDF417】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),!this.mJsonMode)return this.Context.drawPDF417(t);this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.pdf417}));}draw2DPdf417(t){return this.drawPDF417(t)}drawDataMatrix(t){return l.log("#### 【LPAPI.drawDataMatrix】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),this.mJsonMode?(this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.dataMatrix})),true):this.Context.drawDataMatrix(t)}draw2DDataMatrix(t){return this.drawDataMatrix(t)}drawRectangle(t){return l.log("#### 【LPAPI.drawRectangle】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),this.mJsonMode?(this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.rect})),true):t.cornerWidth||t.cornerHeight?this.Context.drawRoundRect(t):this.Context.drawRect(t)}drawRect(t){return this.drawRectangle(t)}drawEllipse(t){if(l.log("#### 【LPAPI.drawEllipse】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),!this.mJsonMode)return this.Context.drawEllipse(t);this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.ellipse}));}drawCircle(t){if(l.log("#### 【LPAPI.drawCircle】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),!this.mJsonMode)return this.Context.drawCircle(t);this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.circle}));}drawLine(t){if(l.log("#### 【LPAPI.drawLine】options:",t),"number"!=typeof t.y1&&"number"!=typeof t.y2&&(t.y1=t.y2=this.mCurrPosY),!this.mJsonMode)return this.Context.drawLine(t);this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.line}));}drawImage(t){return l.log("#### 【LPAPI.drawImage】options:",t),void 0===t.y&&(t.y=this.mCurrPosY),this.mJsonMode?(this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.image})),true):this.Context.drawImage(t)}drawImageAsync(e){return t(this,void 0,void 0,function*(){if(this.mJsonMode||"string"!=typeof e.image)return this.drawImage(e);{const t="number"==typeof e.y?e.y:this.mCurrPosY;return this.Context.loadImage(Object.assign(Object.assign({},e),{src:e.image})).then(i=>this.drawImage(Object.assign(Object.assign({},e),{y:t,image:i})))}})}drawImagePath(t){const e=t;return "string"==typeof e.src&&(e.image=e.src),this.drawImageAsync(t)}drawTable(t){l.log("#### 【LPAPI.drawTable】options:",t),void 0===t.y&&(t.y=this.mCurrPosY);const e=t;if(("number"==typeof t.height&&t.height>0?t.height:0)<=0){const i=t.columnCount||t.columns||e.cols||0;if(!t.tableRows)if(Array.isArray(t.rows))t.tableRows=t.rows;else if(t.cells&&i>0){t.tableRows=[];for(let e=0;e<t.cells.length;e+=i)t.tableRows.push(t.cells.slice(e,e+i));}if(t.tableRows){let i=t.rowCount||("number"==typeof t.rows?t.rows:0);if(("number"!=typeof i||i<=0)&&(i=t.tableRows.length),t.rowHeights&&Array.isArray(t.rowHeights)||("number"==typeof t.rowHeights&&t.rowHeights>0?t.rowHeights=[t.rowHeights]:"number"==typeof e.rowHeight&&e.rowHeight>0&&(t.rowHeights=[e.rowHeight])),t.rowHeights&&Array.isArray(t.rowHeights)&&t.rowHeights.length>0){const e=t.rowHeights.length;if(e<i){const s=t.rowHeights[e-1];t.rowHeights=t.rowHeights.concat(Array(i-e).fill(s));}t.height=t.rowHeights.reduce((t,e)=>t+e,0);}}}return this.mJsonMode?(this.mJobPage.push(Object.assign(Object.assign({},t),{type:ve.table})),true):this.Context.drawTable(t)}printImage(t){return this.openPrinter({name:t.printerName||t.deviceName||t.name,deviceId:t.deviceId,autoScan:t.autoScan}).then(e=>e.statusCode!==Ee.OK?e:("string"==typeof t.image&&(t.src=t.image,t.image=void 0),Promise.resolve(t.image||this.Context.loadImage(Object.assign(Object.assign({},t),{src:t.src||""}))).then(e=>{if(!e)return Le.setFailResult({statusCode:Ee.ERROR_PARAM});const i=!(t.width&&t.height),s=i?e.width:t.width,n=i?e.height:t.height;if(!s&&!n)return Le.setFailResult({statusCode:Ee.ERROR_PARAM});const r=this.startJob({width:s,height:n,orientation:t.orientation,scaleUnit:i?u.Pix:u.MM});return r?Promise.resolve("function"!=typeof t.onJobCreated||t.onJobCreated(r)).then(()=>(this.drawImage({image:e,width:s,height:n,sx:t.sx,sy:t.sy,swidth:t.swidth,sheight:t.sheight}),this.commitJob(Le.filter_NoFuncAndNone(t)))):Le.setFailResult({statusCode:Ee.ERROR_JOB_CREATE})}))).then(e=>e.statusCode!==Ee.OK?Le.setFailResult(e,t):Le.setSuccessResult(e,t))}pushImageData(t){const e=t||{};return t.imageData||t.data?("boolean"!=typeof e.enableSuperBitmap&&(this.mInitInfo.enableSuperBitmap,1)&&(e.enableSuperBitmap=this.mInitInfo.enableSuperBitmap),this.mPrinter.pushImageData(Object.assign(Object.assign({},e),{onJobComplete:e=>{e.statusCode===Ee.OK?Le.setSuccessResult(e,t):Le.setFailResult(e,t);}}))):{statusCode:Ee.ERROR_PARAM}}printImageData(t){l.log("#### 【LPAPI.printImageData】options:");const e=t||{};return "boolean"!=typeof e.enableSuperBitmap&&"boolean"==typeof this.mInitInfo.enableSuperBitmap&&(e.enableSuperBitmap=this.mInitInfo.enableSuperBitmap),this.mPrinter.printImageData(e).then(e=>e.statusCode===Ee.OK?(l.info("#### 【LPAPI.printImageData.resp】打印成功! "),Le.successResult(e,t)):(l.warn(`#### 【LPAPI.printImageData.resp】打印失败, statusCode: ${e.statusCode}, printable: ${this.mPrinter.Printable}`),Le.failResult(e,t)))}printRawData(t){l.log("#### 【LPAPI.printRawData】options:");const e=t||{};if((!e.rawData||e.rawData.length<=0)&&e.data&&e.data.length>0){let i=e.data.filter(t=>Array.isArray(t));const s=e.data.filter(t=>"string"==typeof t||t instanceof Uint8Array);if(i.length<=0&&s.length>0&&(i=[s]),i.length>0){const s=[];for(const t of i){const i=t.map(t=>"string"==typeof t?"base64"===e.dataType?Le.base64ToArrayBuffer(t):Le.hex16ToArrayBuffer(t):t instanceof Uint8Array?t:null),n=i.filter(t=>t&&t.length>0);s.push(n);}s.length>0&&(t.rawData=s);}}return e.rawData&&e.rawData.length>0&&e.rawData.filter(t=>Array.isArray(t)).length<=0&&e.rawData.filter(t=>t instanceof Uint8Array).length>0&&(e.rawData=[e.rawData]),this.mPrinter.printRawData(e).then(e=>e.statusCode===Ee.OK?(l.info("#### 【LPAPI.printImageData.resp】打印成功! "),Le.successResult(e,t)):(l.warn(`#### 【LPAPI.printRawData.resp】打印失败, statusCode: ${e.statusCode}, printable: ${this.mPrinter.Printable}`),Le.failResult(e,t)))}writeCommands(t){return this.mPrinter.writeCommands(t)}encodeImageData(t){return this.mPrinter.encodeImageData(t)}static getJobPrintResult(t,e,i,s,n){const r=e.map(t=>t.dataUrl||""),a=Object.assign(Object.assign({},i),{statusCode:t.statusCode,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable,previewData:r,pages:e.slice(0),printData:s,imageData:n,pageKey:t.pageKey});return a.resultInfo=a,a}validateJsonPrintOptions(t){const e=t.parser;if(t.content&&e&&"function"==typeof e.isSupported&&e.isSupported(t.content)){const i=e.parse(t.content);i&&i.jobInfo&&(i.jobPage||i.jobPages)&&delete(t=Object.assign(Object.assign({},i),t)).content;}let i;if(t.jobPages&&t.jobPages.length>0?Array.isArray(t.jobPages[0])||(t.jobPages=[t.jobPages]):t.jobPage&&t.jobPage.length>0&&Array.isArray(t.jobPage[0])&&(t.jobPages=t.jobPage,delete t.jobPage),t.content)try{t.content=t.content.replace(/[\r\n\t]/g,"");const e=JSON.parse(t.content);Pi.isWdfxJob(e)?t.wdfData=e:"object"!=typeof e||Array.isArray(e)||(i=e),delete t.content;}catch(t){l.warn("---- content 格式异常,解析失败!"),l.warn(t);}return t.wdfData&&(i=Pi.updateWdfOptions(t.wdfData,t.domParser,t.wdfConfig),delete t.wdfData),i&&("object"==typeof i.jobInfo&&(t.jobInfo=Object.assign(Object.assign({},i.jobInfo),t.jobInfo||{})),i.jobPages&&i.jobPages.length>0?Array.isArray(i.jobPages[0])||(i.jobPages=[i.jobPages]):i.jobPage&&i.jobPage.length>0&&Array.isArray(i.jobPage[0])&&(i.jobPages=i.jobPage,delete i.jobPage),i.jobPages&&i.jobPages.length>0?t.jobPages&&t.jobPages.length>0?t.jobPages=[...i.jobPages,...t.jobPages]:t.jobPage&&t.jobPage.length>0?(t.jobPages=[...i.jobPages,t.jobPage],delete t.jobPage):t.jobPages=[...i.jobPages]:i.jobPage&&i.jobPage.length>0&&(t.jobPages&&t.jobPages.length>0?t.jobPages=[i.jobPage,...t.jobPages]:t.jobPage&&t.jobPage.length>0?(t.jobPages=[[...i.jobPage,...t.jobPage]],delete t.jobPage):t.jobPages=[i.jobPage]),!t.jobArguments&&i.jobArguments&&(t.jobArguments=i.jobArguments)),t.jobPage&&t.jobPage.length>0&&(!t.jobPages||t.jobPages.length<=0)&&(t.jobPages=[t.jobPage],delete t.jobPage),t}print(e){return t(this,void 0,void 0,function*(){const t="function"==typeof e?e():e;l.log("#### 【LPAPI.print】options:",t);const i=t.printerInfo||{};this.mPausedPrintInfo&&(t.continueJob||this.mPrinter.PrintStatus!==Ze.Paused||this.mPrinter.stopPrint(),this.mPausedPrintInfo=void 0),this.validateJsonPrintOptions(t);const s=t.jobPages||[];if(!t.jobInfo||s.length<=0){const e=Le.getResultMessage(Ee.ERROR_PARAM),i={statusCode:Ee.ERROR_PARAM,resultInfo:e,errMsg:e};return t.onJobComplete&&t.onJobComplete(i),Le.failResult(i)}const n=t.jobInfo,r=t.action||0;"boolean"!=typeof n.isPreview&&(n.isPreview=this.isPreviewMode(t.jobInfo,r));const a=n.isPreview;r&ii.RawData?r&ii.Image?n.jobName=Ae.JOB_NAME_DATA_IMAGE:n.jobName=Ae.JOB_NAME_DATA:r&ii.Print?n.jobName||(n.jobName=Ri.JOB_NAME_PRINT):r&ii.TransPrev?n.jobName=Ri.JOB_NAME_TRANS:r&ii.Preview&&(n.jobName=Ri.JOB_NAME_PREV);const o=t.jobInfo;if(n.jobWidth||("number"==typeof o.width&&o.width>0?n.jobWidth=o.width:o.labelWidth&&(n.jobWidth=1*o.labelWidth)),n.jobHeight||("number"==typeof o.height&&o.height>0?n.jobHeight=o.height:o.labelHeight&&(n.jobHeight=1*o.labelHeight)),"number"!=typeof n.orientation&&("number"==typeof o.printOrientation?n.orientation=o.printOrientation:o.printOrientation&&(n.orientation=1*o.printOrientation)),!a){const e=yield this.openPrinter(Object.assign(Object.assign({},i),{name:i.name||i.printerName,autoScan:false}));if(e.statusCode!==Ee.OK)return t.onJobComplete&&t.onJobComplete(e),Le.failResult(e);i.printerDPI=this.mPrinter.PrinterDPI,i.printerWidth=this.mPrinter.PrinterWidth;}n.context&&n.context!==this.mContext&&this.setDrawContext(n.context);const h=t.onJobCreated||t.jobCreated||t.jobStarted;if("number"!=typeof n.jobHeight||n.jobHeight<=0){const e=t.jobPages||[],i=xe.getMargins(n);n.jobHeight=xe.calcPageHeight(e[0],i[2]);}const c=this.startJob({width:n.jobWidth||0,height:n.jobHeight,orientation:n.orientation,jobName:n.jobName});if(this.abortJob(),!c){const e={statusCode:Ee.ERROR_JOB_CREATE};return t.onJobComplete&&t.onJobComplete(e),Le.failResult(e)}return h&&(yield Promise.resolve(h(c,t))),yield this.Context.autoLoadImage(t),new Promise(e=>{const i=[],s=[],o=[];t.syncMode?this.Context.drawJob(Le.filterAndAssign(t,{onPageComplete:h=>{l.log(`#### drawJob.onPageComplete: pages = [${h.pageIndex+1} / ${h.printPages}], copies = [${h.copyIndex+1} / ${h.printCopies}]`);let c=h.copyIndex;const d=t.onPageCreated||t.pageCreated,u=t.onPageComplete||t.pageComplete,g=t.onJobComplete||t.jobComplete,p=t.onPagePrintComplete||t.pagePrintComplete,f=t.onJobPrintComplete||t.jobPrintComplete;if("function"==typeof d&&d(h),r&ii.RawData){const t=h.imageData;if(t)if(r&ii.Image)o.push(t);else {delete h.imageData;const e=this.mPrinter.encodeImageData(Object.assign(Object.assign({},n),{imageData:t}));s.push(e.values);}if(u&&u(Object.assign(Object.assign({},h),{statusCode:Ee.OK,pageKey:0})),h.isEndCopy&&h.isEndPage){const t=Ri.getJobPrintResult({statusCode:Ee.OK},i,h,s,o);g&&g(t),e(t);}return Ee.OK}if(a){if(i.push(h),u&&u(Object.assign(Object.assign({},h),{statusCode:Ee.OK,pageKey:0})),h.isEndCopy&&h.isEndPage){const t=Ri.getJobPrintResult({statusCode:Ee.OK},i,h);g&&g(t),e(t);}return Ee.OK}return this.pushImageData(Object.assign(Object.assign({},n),{printCopies:n.autoPage?0:n.printCopies,imageData:h.imageData,onPageComplete:t=>{c=n.autoPage?h.copyIndex:t.copyIndex;const e=Object.assign(Object.assign({},h),{pageKey:t.pageKey,statusCode:t.statusCode,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable,copyIndex:c,isEndCopy:n.autoPage?h.isEndCopy:c+1>=h.printCopies});i.push(e),u&&u(e);},onPagePrintComplete:t=>{c=n.autoPage?h.copyIndex:t.copyIndex,p&&p(Object.assign(Object.assign({},h),{pageKey:t.pageKey,statusCode:t.statusCode,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable,copyIndex:c,isEndCopy:n.autoPage?h.isEndCopy:c+1>=h.printCopies}));const e=h.isEndCopy&&h.isEndPage&&c+1>=h.printCopies;(t.statusCode!==Ee.OK||e)&&f&&f(Object.assign(Object.assign({},t),{statusCode:Ee.OK,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable}));},onJobComplete:n=>{if(n.statusCode!==Ee.OK){if(n.statusCode===Ee.ERROR_PRINTER_NOT_AVAILABLE){const e=t.jobInfo||{};this.mPausedPrintInfo={printInfo:t,autoPage:e.autoPage,printPages:h.printPages,printCopies:h.printCopies,pageIndex:h.pageIndex,copyIndex:h.copyIndex},l.warn(`打印机异常 [printable = ${n.printable}] at drawJob.onJobComplete`);}const s=Ri.getJobPrintResult(n,i,h);g&&g(s),e(s);}else {const t=Ri.getJobPrintResult(n,i,h,s);l.log("#### 打印完成 at drawJob.onJobComplete:",h,t),h.isEndCopy&&h.isEndPage&&(c+1>=h.printCopies&&g&&g(t),e(t));}}})).statusCode}})):this.Context.drawAsyncJob(Le.filterAndAssign(t,{onPageComplete:h=>{let c=h.copyIndex;l.log(`#### drawAsyncJob.onPageComplete: pages = [${h.pageIndex+1} / ${h.printPages}], copies = [${h.copyIndex+1} / ${h.printCopies}]`);const d=t.onPageCreated||t.pageCreated,u=t.onPageComplete||t.pageComplete,g=t.onJobComplete||t.jobComplete,p=t.onPagePrintComplete||t.pagePrintComplete,f=t.onJobPrintComplete||t.jobPrintComplete;if("function"==typeof d&&d(h),r&ii.RawData){const t=h.imageData;if(t)if(r&ii.Image)o.push(t);else {delete h.imageData;const e=this.mPrinter.encodeImageData(Object.assign(Object.assign({},n),{imageData:t,valueType:ti.Hex16}));s.push(e.values);}if(u&&u(Object.assign(Object.assign({},h),{statusCode:Ee.OK,pageKey:0})),h.isEndCopy&&h.isEndPage){const t=Ri.getJobPrintResult({statusCode:Ee.OK},i,h,s,o);g&&g(t),e(t);}return Ee.OK}if(a){if(i.push(h),u&&u(Object.assign(Object.assign({},h),{statusCode:Ee.OK,pageKey:0})),h.isEndCopy&&h.isEndPage){const t=Ri.getJobPrintResult({statusCode:Ee.OK},i,h);g&&g(t),e(t);}return Ee.OK}{const r=h.imageData;return h.imageData=void 0,this.printImageData(Object.assign(Object.assign({},n),{printCopies:n.autoPage?0:h.printCopies,imageData:r,onPageComplete:t=>{c=n.autoPage?h.copyIndex:t.copyIndex;const e=Object.assign(Object.assign({},h),{statusCode:t.statusCode,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable,pageKey:t.pageKey,copyIndex:c,isEndCopy:n.autoPage?h.isEndCopy:c+1>=h.printCopies});i.push(e),u&&u(e);},onPagePrintComplete:t=>{c=n.autoPage?h.copyIndex:t.copyIndex,p&&p(Object.assign(Object.assign({},h),{statusCode:t.statusCode,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable,pageKey:t.pageKey,copyIndex:c,isEndCopy:n.autoPage?h.isEndCopy:c+1>=h.printCopies}));const e=h.isEndCopy&&h.isEndPage&&c+1>=h.printCopies;(t.statusCode!==Ee.OK||e)&&f&&f(Object.assign(Object.assign({},t),{statusCode:t.statusCode,errMsg:t.errMsg||Le.getResultMessage(t.statusCode),printable:t.printable}));},onJobComplete:n=>{if(n.statusCode!==Ee.OK){if(n.statusCode===Ee.ERROR_PRINTER_NOT_AVAILABLE){const e=t.jobInfo||{};this.mPausedPrintInfo={printInfo:t,autoPage:e.autoPage,printPages:h.printPages,printCopies:h.printCopies,pageIndex:h.pageIndex,copyIndex:h.copyIndex},l.warn(`打印机异常 [printable = ${n.printable}] at drawAsyncJob.onJobComplete`);}const s=Ri.getJobPrintResult(n,i,h);g&&g(s),e(s);}else {const t=Ri.getJobPrintResult(n,i,h,s);l.info("#### 打印完成 at drawAsyncJob.onJobComplete:",h,t),h.isEndCopy&&h.isEndPage&&(c+1>=h.printCopies&&g&&g(t),e(t));}}})).then(t=>t.statusCode)}}}));})})}continuePrint(){return t(this,void 0,void 0,function*(){const t=this.mPausedPrintInfo;if(yield this.mPrinter.continuePrint(),!t||!t.printInfo.jobInfo)return true;const e=t.printInfo,i=e.jobInfo,s=t.pageIndex,n=t.copyIndex,r=t.printPages,a=t.printCopies,o=a-n-1;if(t.autoPage){const t=r-s-1;if(t>0&&t<r){if((yield this.print(Object.assign(Object.assign({},e),{continueJob:true,jobInfo:Object.assign(Object.assign({},i),{autoPage:true,startCopy:n,printCopies:1,remainCopies:o,startPage:s+1,printPages:t})}))).statusCode!==Ee.OK)return false}if(a>n+1){return (yield this.print(Object.assign(Object.assign({},e),{continueJob:true,jobInfo:Object.assign(Object.assign({},i),{autoPage:true,startCopy:n+1,printCopies:o,remainCopies:0,startPage:0,printPages:r})}))).statusCode===Ee.OK}}else if(r>s+1){return (yield this.print(Object.assign(Object.assign({},e),{continueJob:true,jobInfo:Object.assign(Object.assign({},i),{printCopies:a,startPage:s+1,printPages:r-s-1})}))).statusCode===Ee.OK}return true})}printWdfx(e){return t(this,void 0,void 0,function*(){if(l.log("#### 【LPAPI.printWdfx】options:"),!e.content||"string"!=typeof e.content)return l.warn("---- 未检测到 wdfx 字符串!"),l.warn(e.content),Le.failResult({statusCode:Ee.ERROR_PARAM});const t=Pi.loadWdfxContent(e.content,e.domParser);return t?this.print(Object.assign(Object.assign({},e),{wdfData:t,content:void 0})):(l.warn("---- wdfx内容解析错误, content:"),l.warn(e.content.length>200?`${e.content.substring(0,200)}...`:e.content),Le.failResult({statusCode:Ee.ERROR_DATA_PARSE}))})}loadWdfxInfo(t){const e="string"==typeof t?{content:t}:t,i="string"==typeof e.content?e.content:"";let s="object"==typeof e.wdfData?e.wdfData:void 0;if(e.content||s)return !s&&i&&(s=Pi.loadWdfxContent(i,e.domParser)),s?this.validateJsonPrintOptions(Object.assign(Object.assign({},e),{content:void 0,wdfData:s})):(l.warn("---- wdfx内容解析错误, content:"),void l.warn(i.length>200?`${i.substring(0,200)}...`:i));l.warn("---- 未检测到 wdfx 字符串!",t);}renderToElement(t){try{const e="string"==typeof t.element?document.getElementById(t.element):t.element;if(!e)return void l.warn("---- 未检测到标签渲染的目标位置");this.validateJsonPrintOptions(t);const i=t.jobPages||[];if(!t.jobInfo||i.length<=0)return void l.warn("---- 参数异常:",t);const s=new Te({data:t,radius:.8,margin:[]});return s.attachTo({element:e,position:"absolute",styles:t.styles,adjustFontSize:this.mInitInfo.adjustFontSize}),s}catch(t){return void l.warn("【Exception】renderToElement: ",t)}}renderWdfxToElement(t){l.log("#### 【LPAPI.renderWdfxToElement】options:");const e="string"==typeof t.content?t.content:"";if(t.content||t.wdfData)return !t.wdfData&&e&&(t.wdfData=Pi.loadWdfxContent(e,t.domParser)),t.wdfData?this.renderToElement(Object.assign(Object.assign({},t),{wdfData:t.wdfData,content:void 0})):(l.warn("---- wdfx内容解析错误, content:"),void l.warn(e.length>200?`${e.substring(0,200)}...`:t.content));l.warn("---- 未检测到 wdfx 字符串!",t);}quit(){return this.closePrinter().then(()=>(this.mInitInfo.onQuit&&this.mInitInfo.onQuit(),this.stopPrint(),this.abortJob(),this.mPausedPrintInfo=void 0,this.mContext=void 0,this.mPrinter.closeAdapter()))}}Ri.JOB_NAME_TRANS="#!#transparent#!#",Ri.JOB_NAME_PREV="#!#preview#!#",Ri.JOB_NAME_PRINT="LPAPI",Ri.JOB_NAME_RAW_DATA="#!#RawData#!#",Ri.COLOR_WHITE="#fff";
|
||
|
||
class UniCanvas {
|
||
get width() {
|
||
return this._width;
|
||
}
|
||
set width(v) {
|
||
this._width = v;
|
||
}
|
||
get height() {
|
||
return this._height;
|
||
}
|
||
set height(v) {
|
||
this._height = v;
|
||
}
|
||
get canvasId() {
|
||
return this.mContext.canvasId;
|
||
}
|
||
constructor(context) {
|
||
this._width = 0;
|
||
this._height = 0;
|
||
this.mContext = context;
|
||
}
|
||
getContext(options) {
|
||
if (!this.mCanvasContext) {
|
||
this.mCanvasContext = uni.createCanvasContext(this.mContext.canvasId || "", this.mContext.componentInstance);
|
||
}
|
||
return this.mCanvasContext;
|
||
}
|
||
toDataURL(type, quality) {
|
||
return this.mDataUrl || "";
|
||
}
|
||
getImageData() {
|
||
return new Promise((resolve) => {
|
||
const context = this.mCanvasContext;
|
||
if (!context) {
|
||
resolve(undefined);
|
||
return;
|
||
}
|
||
const funcType = typeof context.getImageData;
|
||
l.info(`【UniCanvas.Request】 getImageData: typeof context.getImageData = ${funcType}`);
|
||
if (this.mContext.isAlipay) {
|
||
// 支付宝小程序旧版本,只能异步获取ImageData;
|
||
// 备注:这个地方会报错,报 toJSON 错误,但是不影响打印,后期需要升级 context 获取方式;
|
||
if (this.mContext.canvas) {
|
||
// 新版本不需要特殊处理
|
||
resolve(undefined);
|
||
}
|
||
else {
|
||
// 旧版本需要异步处理;
|
||
if (funcType === "function") {
|
||
const timer = setTimeout(() => {
|
||
l.warn(`【UniCanvas.Response.timeout】 getImageData 请求超时!`);
|
||
resolve(undefined);
|
||
}, 5000);
|
||
const resolveData = (data) => {
|
||
clearTimeout(timer);
|
||
resolve(data);
|
||
};
|
||
const res = context.getImageData({
|
||
x: 0,
|
||
y: 0,
|
||
width: this.width,
|
||
height: this.height,
|
||
success: (res) => {
|
||
l.info(`【UniCanvas.Response.success】 getImageData:`);
|
||
clearTimeout(timer);
|
||
resolveData(res);
|
||
},
|
||
fail: (resp) => {
|
||
l.warn(resp, `【UniCanvas.Response.fail】 getImageData:`, resp);
|
||
clearTimeout(timer);
|
||
resolveData(undefined);
|
||
},
|
||
});
|
||
// 钉钉小程序返回值是 Promise,支付宝小程序返回值为空。
|
||
if (Le.isPromise(res)) {
|
||
Promise.resolve(res)
|
||
.then((_res) => {
|
||
// logger.info(`【UniCanvas.Response.then】 getImageData:`, _res);
|
||
})
|
||
.catch((err) => {
|
||
l.info(`【UniCanvas.Response.catch】 getImageData:`, err);
|
||
resolveData(undefined);
|
||
});
|
||
}
|
||
}
|
||
else {
|
||
l.warn(`【UniCanvas.Response】 getImageData: 不支持的方法:`);
|
||
resolve(undefined);
|
||
}
|
||
}
|
||
}
|
||
else if (typeof uni.canvasGetImageData === "function") {
|
||
// APP、微信小程序等,需要通过 canvasGetImageData 来获取imageData 对象;
|
||
l.info(`#### 【Request】 uni.canvasGetImageData:`);
|
||
uni.canvasGetImageData({
|
||
x: 0,
|
||
y: 0,
|
||
width: this.width,
|
||
height: this.height,
|
||
canvasId: this.mContext.canvasId || "",
|
||
success: (res) => {
|
||
l.info(`#### 【Response.success】 uni.canvasGetImageData:`);
|
||
resolve(res);
|
||
},
|
||
fail: (res) => {
|
||
l.error(`#### 【Response.fail】uni.canvasGetImageData:`);
|
||
l.error(JSON.stringify(res));
|
||
resolve(undefined);
|
||
},
|
||
}, this.mContext.componentInstance);
|
||
}
|
||
else {
|
||
resolve(undefined);
|
||
}
|
||
});
|
||
}
|
||
static getTempFilePath(options, callback) {
|
||
l.info(`#### 【Request】uni.canvasToTempFilePath:`);
|
||
let timer = setTimeout(() => {
|
||
l.warn(`#### 【Response.timeout】uni.canvasToTempFilePath:`);
|
||
callback("");
|
||
}, 3000);
|
||
//
|
||
uni.canvasToTempFilePath({
|
||
// 保存canvas为图片
|
||
canvasId: options.canvasId || "",
|
||
canvas: options.canvas,
|
||
quality: 1,
|
||
success: (res) => {
|
||
l.info(res, `#### 【Response.success】uni.canvasToTempFilePath:`);
|
||
// 备注:钉钉小程序需要通过 filePath来获取
|
||
// uni.setStorageSync('filePath',res.tempFilePath) //保存临时文件路径到缓存
|
||
clearTimeout(timer);
|
||
callback(res.tempFilePath || res.filePath);
|
||
},
|
||
fail: (res) => {
|
||
l.warn(res, `#### 【Response.fail】uni.canvasToTempFilePath:`);
|
||
clearTimeout(timer);
|
||
callback("");
|
||
},
|
||
}, options.componentInstance);
|
||
}
|
||
start(options) {
|
||
this.mDataUrl = "";
|
||
}
|
||
draw(context, printMode, reserve) {
|
||
l.log(`---- UniCanvas.draw: typeof context.draw = ${typeof context.draw}`);
|
||
return new Promise((resolve) => {
|
||
if (!context) {
|
||
resolve("");
|
||
return;
|
||
}
|
||
const getTempPathAction = () => {
|
||
const ddContext = context;
|
||
const funcType = this.mContext.isAlipay ? typeof ddContext.toTempFilePath : undefined;
|
||
console.warn(`---- typeof context.toTempFilePath = ${funcType}`);
|
||
// 备注:支付宝小程序也支持 toTempFilePath,但是返回的图片是空白。
|
||
if (this.mContext.isDingTalk && funcType === "function") {
|
||
const timer = setTimeout(() => {
|
||
l.log(`【UniCanvas.Response.timeout】 dd.Context.toTempFilePath:`);
|
||
resolve("");
|
||
}, 3000);
|
||
const resolveUrl = (url) => {
|
||
clearTimeout(timer);
|
||
resolve(url);
|
||
};
|
||
//
|
||
l.log(`【UniCanvas.Request】 dd.Context.toTempFilePath:`);
|
||
const res = ddContext.toTempFilePath({
|
||
x: 0,
|
||
y: 0,
|
||
width: this.width,
|
||
height: this.height,
|
||
success: (res) => {
|
||
const url = res.tempFilePath || res.url || "";
|
||
this.mDataUrl = url;
|
||
l.log(`【UniCanvas.Response.success】 context.toTempFilePath:`, res);
|
||
resolveUrl(url);
|
||
},
|
||
fail: (err) => {
|
||
l.log(`【UniCanvas.Response.fail】 context.toTempFilePath:`, err);
|
||
console.warn(`---- is fail to getTempFilePath: `, err);
|
||
resolveUrl("");
|
||
},
|
||
});
|
||
// 钉钉小程序返回值是 Promise,支付宝小程序返回值为空。
|
||
if (Le.isPromise(res)) {
|
||
Promise.resolve(res)
|
||
.then((res) => {
|
||
l.log(`【UniCanvas.Response.then】 context.toTempFilePath:`, res);
|
||
})
|
||
.catch((err) => {
|
||
l.log(`【UniCanvas.Response.catch】 context.toTempFilePath:`, err);
|
||
resolveUrl("");
|
||
});
|
||
}
|
||
}
|
||
else {
|
||
UniCanvas.getTempFilePath(this.mContext, (tempPath) => {
|
||
this.mDataUrl = tempPath;
|
||
resolve(tempPath);
|
||
});
|
||
}
|
||
};
|
||
if (this.mContext.isAlipay) {
|
||
// 支付宝小程序 draw函数没有回调。
|
||
if (typeof context.draw === "function") {
|
||
context.draw(reserve);
|
||
}
|
||
//
|
||
if (printMode) {
|
||
resolve("");
|
||
}
|
||
else {
|
||
setTimeout(() => {
|
||
getTempPathAction();
|
||
}, this.mContext.drawTimeout || 100);
|
||
}
|
||
}
|
||
else if (typeof context.draw === "function") {
|
||
let hasDraw = false;
|
||
context.draw(reserve, () => {
|
||
hasDraw = true;
|
||
if (!printMode) {
|
||
// 微信小程序中为了避免生成预览图片黑块的问题
|
||
setTimeout(getTempPathAction, this.mContext.drawTimeout || 100);
|
||
}
|
||
else {
|
||
resolve("");
|
||
}
|
||
});
|
||
setTimeout(() => {
|
||
if (!hasDraw) {
|
||
l.warn(`---- Canvas.draw 函数长时间未响应,请检查目标 Canvas 是否已经销毁。`);
|
||
resolve("");
|
||
}
|
||
}, 3000);
|
||
}
|
||
else if (this.mContext.canvas && !printMode) {
|
||
// 为了避免出现黑块,暂时等待1秒,具体待测试。
|
||
setTimeout(() => {
|
||
getTempPathAction();
|
||
}, 10);
|
||
}
|
||
else {
|
||
resolve("");
|
||
}
|
||
});
|
||
}
|
||
saveBase64Image(dataUrl, callback) {
|
||
const groups = /^data:(\S+)\/(\S+);base64,.*/.exec(dataUrl || "");
|
||
if (groups && plus && plus.nativeObj.Bitmap) {
|
||
if (groups[2] === "svg+xml") {
|
||
callback && callback(dataUrl);
|
||
}
|
||
else {
|
||
const fileName = `border.${groups[2]}`;
|
||
const bitmap = new plus.nativeObj.Bitmap(`bitmap${Date.now()}`);
|
||
try {
|
||
bitmap.loadBase64Data(dataUrl, () => {
|
||
const filePath = `_doc/temp/${fileName}`;
|
||
bitmap.save(filePath, { overwrite: true }, (res) => {
|
||
bitmap.clear();
|
||
callback && callback(res);
|
||
}, (res) => {
|
||
bitmap.clear();
|
||
l.warn(`---- 图片保存失败!`);
|
||
l.warn(res);
|
||
callback && callback(dataUrl);
|
||
});
|
||
}, (res) => {
|
||
bitmap.clear();
|
||
l.warn(`---- base64 字符串加载失败:`);
|
||
l.warn(res);
|
||
callback && callback(dataUrl);
|
||
});
|
||
}
|
||
catch (error) {
|
||
l.warn(`---- base64 字符串load 异常!`);
|
||
l.warn(error);
|
||
bitmap.clear();
|
||
callback && callback(dataUrl);
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
callback && callback(dataUrl);
|
||
}
|
||
}
|
||
loadImage(options) {
|
||
const opts = typeof options === "string" ? { src: options } : options;
|
||
l.log(`UniCanvas.loadImage: ${opts.src.length > 100 ? opts.src.substring(0, 100) : opts.src}`);
|
||
return new Promise((resolve) => {
|
||
if (opts.src.startsWith("http")) {
|
||
uni.getImageInfo({
|
||
src: opts.src,
|
||
success: (res) => {
|
||
l.log(`res, 【Response.success】uni.getImageInfo:`);
|
||
resolve({
|
||
width: res.width,
|
||
height: res.height,
|
||
dzSrc: res.path,
|
||
});
|
||
},
|
||
fail: (res) => {
|
||
l.warn(res, `【Response.fail】uni.getImageInfo:`);
|
||
resolve("");
|
||
},
|
||
});
|
||
}
|
||
else if (opts.src.startsWith("data:")) {
|
||
if (opts.withSize) {
|
||
this.saveBase64Image(opts.src, (result) => {
|
||
if (result && typeof result !== "string" && result.width && result.height) {
|
||
resolve({
|
||
width: result.width,
|
||
height: result.height,
|
||
dzSrc: result.target,
|
||
});
|
||
}
|
||
else {
|
||
resolve(opts.src);
|
||
}
|
||
});
|
||
}
|
||
else {
|
||
resolve(opts.src);
|
||
}
|
||
}
|
||
else {
|
||
resolve(opts.src);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
class UniContext extends xe {
|
||
static createInstance(options, prevContext) {
|
||
const opts = options || {};
|
||
if (prevContext) {
|
||
const prevCanvas = prevContext.CanvasElement;
|
||
if (options.canvas && options.canvas === prevCanvas) {
|
||
return prevContext;
|
||
}
|
||
else if (options.canvasId &&
|
||
prevCanvas instanceof UniCanvas &&
|
||
options.canvasId === prevCanvas.canvasId) {
|
||
return prevContext;
|
||
}
|
||
}
|
||
//
|
||
return opts.canvas || opts.canvasId ? new UniContext(opts) : undefined;
|
||
}
|
||
static isDingTalk() {
|
||
try {
|
||
if (typeof dd === "object") {
|
||
return true;
|
||
}
|
||
}
|
||
catch (error) {
|
||
l.log(`---- UniContext.isDingTalk.exception: `, error);
|
||
}
|
||
return false;
|
||
}
|
||
constructor(context) {
|
||
super(Object.assign({ apiMode: true }, (context || {})));
|
||
//
|
||
this.init(context || {});
|
||
//
|
||
l.log(`==== 【UniContext】constructor(${this.instanceId}) ====`, this.mOptions);
|
||
}
|
||
init(options) {
|
||
const opts = options || {};
|
||
// #ifdef APP-PLUS
|
||
opts.isAppPlus = true;
|
||
// #endif
|
||
// #ifdef H5
|
||
opts.isH5 = true;
|
||
// #endif
|
||
// #ifdef MP-WEIXIN
|
||
opts.isWeiXin = true;
|
||
// #endif
|
||
// #ifdef MP-ALIPAY
|
||
opts.isAlipay = true;
|
||
// #endif
|
||
//
|
||
if (opts.isAlipay) {
|
||
opts.isDingTalk = UniContext.isDingTalk();
|
||
}
|
||
//
|
||
this.mOptions = opts;
|
||
}
|
||
createCanvas() {
|
||
const context = this.mOptions;
|
||
l.info(`【UniContext】createCanvas: create by options: `, this.mOptions);
|
||
//
|
||
if (!this.mCanvas) {
|
||
if (document && typeof document.createElement === "function") {
|
||
l.log('【UniContext】createCanvas by document.createElement("canvas")!');
|
||
// H5环境适配
|
||
this.mCanvas = document.createElement("canvas");
|
||
}
|
||
else if (context.canvas && typeof context.canvas.getContext === "function") {
|
||
l.log("【UniContext】createCanvas by options.canvas!");
|
||
// 新版在屏 canvas 适配,canvas必须支持获取绘制上下文才可以使用
|
||
this.mCanvas = context.canvas;
|
||
}
|
||
else if (context.canvasId) {
|
||
l.log("【UniContext】createCanvas by canvasId!");
|
||
// 旧版在屏 canvas 适配
|
||
this.mCanvas = new UniCanvas(this.mOptions);
|
||
}
|
||
else {
|
||
l.log("【UniContext】createCanvas by uni.createOffscreenCanvas!");
|
||
// 离屏 canvas 适配
|
||
if (typeof uni.createOffscreenCanvas === "function") {
|
||
this.mCanvas = uni.createOffscreenCanvas({ type: "2d" });
|
||
}
|
||
if (!this.mCanvas) {
|
||
if (context.isWeiXin) {
|
||
l.warn("================================");
|
||
l.warn("==== 真机调试请使用 2.0 模式 ====");
|
||
l.warn("================================");
|
||
}
|
||
else {
|
||
l.warn("=======================================");
|
||
l.warn("==== 当前环境不支持 OffscreenCanvas ====");
|
||
l.warn("=======================================");
|
||
}
|
||
}
|
||
else {
|
||
l.info("==================================");
|
||
l.info("==== OffscreenCanvas创建成功! ====");
|
||
l.info("==================================");
|
||
}
|
||
}
|
||
}
|
||
//
|
||
return this.mCanvas;
|
||
}
|
||
/**
|
||
* 通过 canvas 来创建 Image 对象。
|
||
*/
|
||
createImage(canvas, src, timeout) {
|
||
// 注意:
|
||
// 1. 不知道为什么,通过canvas.createImage创建的Image在小程序中第二次加载图片的时候不会触发 onload 方法;
|
||
// 2. Image本身就可以加载网络图片,所以也不需要使用 getImageInfo来缓存;
|
||
// 3. 网络图片可以通过添加随机参数来避免第二次无法加载的问题,本地图片该方法不可行;
|
||
// 4. 加载完之后,不能立即将 image.src 设置为空,设置为空后图片显示黑块;
|
||
return new Promise((resolve) => {
|
||
const imgSrc = src.startsWith("http") ? `${src}?${new Date().getTime()}${Math.random()}` : src;
|
||
// const canvas = uni.createOffscreenCanvas({ type: "2d" }) as any;
|
||
const image = canvas.createImage();
|
||
const subImagePath = imgSrc.length > 100 ? `${imgSrc.substring(0, 100)}...` : imgSrc;
|
||
let processed = false;
|
||
l.info(`---- canvas.createImage: ${subImagePath}`);
|
||
image.onload = () => {
|
||
l.info(`---- image.onload`);
|
||
if (processed) {
|
||
l.warn(`图片加载时间太长了,已经进行超时处理了!`);
|
||
}
|
||
else {
|
||
processed = true;
|
||
resolve(image);
|
||
}
|
||
};
|
||
image.onerror = (res) => {
|
||
l.warn(res, `---- image.onerror:${subImagePath}`);
|
||
processed = true;
|
||
resolve(imgSrc);
|
||
};
|
||
//
|
||
setTimeout(() => {
|
||
if (!processed) {
|
||
l.warn(`---- 图片加载超时:`);
|
||
processed = true;
|
||
resolve(image);
|
||
}
|
||
}, timeout || 3000);
|
||
image.src = imgSrc;
|
||
});
|
||
}
|
||
loadImage(options) {
|
||
const _super = Object.create(null, {
|
||
loadImage: { get: () => super.loadImage }
|
||
});
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
l.log(`---- UniContext.loadImage:`);
|
||
const opts = typeof options === "string" ? { src: options } : options;
|
||
if (!opts || !opts.src) {
|
||
return null;
|
||
}
|
||
const canvas = this.createCanvas();
|
||
if (canvas instanceof UniCanvas) {
|
||
// 通过 canvasId 来创建上下文的情况;
|
||
return canvas.loadImage(opts);
|
||
}
|
||
else if (document && typeof document.createElement === "function") {
|
||
return _super.loadImage.call(this, opts.src);
|
||
}
|
||
else if (canvas && canvas === this.mOptions.canvas) {
|
||
// 新版的在屏 canvas 适配;
|
||
return this.createImage(canvas, opts.src, 0);
|
||
}
|
||
else if (typeof uni.createOffscreenCanvas === "function") {
|
||
// 兼容微信小程序离屏Canvas
|
||
return this.createImage(canvas, opts.src, 0);
|
||
}
|
||
else {
|
||
return _super.loadImage.call(this, opts.src);
|
||
}
|
||
});
|
||
}
|
||
startJob(options) {
|
||
l.log(`#### UniContext.startJob - before super.startJob:`);
|
||
// 通过 querySelector 方式获取到 canvas后,已经直接将canvas配置到了 DzCanvas的初始化函数中了;
|
||
// 所以底层不会再调用 createCanvas了,所以此处需要重新获取下 canvas。
|
||
if (!this.mCanvas) {
|
||
this.createCanvas();
|
||
}
|
||
if (!this.mCanvas) {
|
||
l.warn(`#### UniContext.startJob: 未获取到有效的 canvas 实例,无法进行标签绘制!`, this.mCanvas);
|
||
return undefined;
|
||
}
|
||
//
|
||
const res = super.startJob(options);
|
||
l.log(`#### UniContext.startJob - after super.startJob:`, res);
|
||
if (!res)
|
||
return res;
|
||
//
|
||
if (this.mCanvas && this.mCanvas instanceof UniCanvas) {
|
||
this.mCanvas.start(res);
|
||
}
|
||
return Object.assign(Object.assign({}, res), { canvas: this.mCanvas });
|
||
}
|
||
onCanvasClear(canvas, context) {
|
||
// if (canvas && canvas instanceof UniCanvas) {
|
||
// canvas.draw(context as any, this.IsApiMode, true);
|
||
// }
|
||
}
|
||
commitJob() {
|
||
l.info(`---- [UniContext] DrawContext.commitJob ====> before super.commitJob:`);
|
||
return super.commitJob().then((res) => {
|
||
l.info(`---- [UniContext] DrawContext.commitJob ====> after super.commitJob:`, res);
|
||
if (!res)
|
||
return res;
|
||
//
|
||
const canvas = this.mCanvas;
|
||
const jobInfo = this.jobOptions || {};
|
||
if (canvas && canvas instanceof UniCanvas) {
|
||
const context = canvas.getContext();
|
||
return canvas.draw(context, !res.isPreview).then((v) => {
|
||
if (!res.dataUrl)
|
||
res.dataUrl = v;
|
||
res.tempFilePath = v;
|
||
if (!res.isPreview || jobInfo.withImageData) {
|
||
return canvas.getImageData().then((data) => {
|
||
res.imageData = data;
|
||
return res;
|
||
});
|
||
}
|
||
else {
|
||
return res;
|
||
}
|
||
});
|
||
}
|
||
else if (canvas && canvas === this.mOptions.canvas) {
|
||
l.info(`---- 获取新版在屏Canvas对应的预览图片!`, this.mOptions);
|
||
// 新版的在屏 canvas 适配;
|
||
if (this.mOptions.isAlipay && res.isPreview && !res.dataUrl) {
|
||
const aliCanvas = canvas;
|
||
const funcType = typeof aliCanvas.toTempFilePath;
|
||
l.info(`【Request】canvas.toTempFilePath: canvas.toTempFilePath = ${funcType}`);
|
||
if (funcType === "function") {
|
||
// const aliCanvas: Record<string, any> = this.mContext.canvas;
|
||
return new Promise((resolve) => {
|
||
const timer = setTimeout(() => {
|
||
resolve(res);
|
||
}, 3000);
|
||
aliCanvas.toTempFilePath({
|
||
x: 0,
|
||
y: 0,
|
||
width: aliCanvas.width,
|
||
height: aliCanvas.height,
|
||
success: (result) => {
|
||
l.info(`【Response.success】canvas.toTempFilePath: `, result);
|
||
res.dataUrl = result.tempFilePath;
|
||
clearTimeout(timer);
|
||
resolve(res);
|
||
},
|
||
fail: (err) => {
|
||
l.warn(`【Response.fail】canvas.toTempFilePath: `, err);
|
||
clearTimeout(timer);
|
||
resolve(res);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
}
|
||
}
|
||
//
|
||
return res;
|
||
});
|
||
}
|
||
}
|
||
|
||
class BleAdapter {
|
||
static getInstance() {
|
||
return this._instance || (this._instance = new BleAdapter());
|
||
}
|
||
constructor(options) {
|
||
this.mConnectionMap = new Map();
|
||
this.mCharacteristicMap = new Map();
|
||
this.mContext = options || {};
|
||
l.log(`==== 【BleAdapter】constructor(options) ====`, this.mContext);
|
||
// #ifdef APP-PLUS
|
||
this.mContext.isAppPlus = true;
|
||
// #endif
|
||
// #ifdef H5
|
||
this.mContext.isH5 = true;
|
||
// #endif
|
||
// #ifdef MP-WEIXIN
|
||
this.mContext.isWeiXin = true;
|
||
// #endif
|
||
// #ifdef MP-ALIPAY
|
||
this.mContext.isAlipay = true;
|
||
// #endif
|
||
//
|
||
if (this.mContext.isAlipay) {
|
||
this.mContext.isDingTalk = UniContext.isDingTalk();
|
||
}
|
||
//
|
||
if (typeof uni.getDeviceInfo === "function") {
|
||
this.mDeviceInfo = uni.getDeviceInfo();
|
||
l.log(`---- deviceInfo:`, this.mDeviceInfo);
|
||
}
|
||
if (typeof uni.getSystemInfo === "function") {
|
||
uni.getSystemInfo({
|
||
success: (res) => {
|
||
this.mSystemInfo = res;
|
||
l.log(`---- mSystemInfo: `, res);
|
||
},
|
||
});
|
||
}
|
||
}
|
||
get isH5() {
|
||
return this.mContext.isH5;
|
||
}
|
||
get Context() {
|
||
return this.mContext;
|
||
}
|
||
get platform() {
|
||
var _a, _b, _c;
|
||
return ((_a = this.mDeviceInfo) === null || _a === void 0 ? void 0 : _a.platform) || ((_b = this.mSystemInfo) === null || _b === void 0 ? void 0 : _b.osName) || ((_c = this.mSystemInfo) === null || _c === void 0 ? void 0 : _c.platform) || "";
|
||
}
|
||
isAndroid() {
|
||
return this.platform.toLowerCase() === "android";
|
||
}
|
||
isHarmonyOS() {
|
||
const osName = this.platform;
|
||
return osName === "ohos" || osName.toLowerCase().indexOf("harmony") >= 0;
|
||
}
|
||
getDeviceInfo() {
|
||
return this.mDeviceInfo;
|
||
}
|
||
androidAPILevel() {
|
||
if (this.isAndroid() && this.mContext.isAppPlus) {
|
||
const apiLevel = this.mSystemInfo ? this.mSystemInfo.osAndroidAPILevel : 0;
|
||
if (typeof apiLevel === "number" && apiLevel > 0) {
|
||
return apiLevel;
|
||
}
|
||
else {
|
||
const Build = plus.android.importClass("android.os.Build");
|
||
const version = Build ? Build.VERSION.SDK_INT : 0;
|
||
return typeof version === "number" ? version : 0;
|
||
}
|
||
}
|
||
else {
|
||
return 0;
|
||
}
|
||
}
|
||
requestPermissions() {
|
||
return new Promise((resolve) => {
|
||
const sdkVersion = this.androidAPILevel();
|
||
if (sdkVersion >= 23) {
|
||
const permissions = [];
|
||
if (sdkVersion >= 31) {
|
||
permissions.push("android.permission.BLUETOOTH_SCAN");
|
||
permissions.push("android.permission.BLUETOOTH_CONNECT");
|
||
}
|
||
if (sdkVersion >= 29) {
|
||
permissions.push("android.permission.ACCESS_FINE_LOCATION");
|
||
}
|
||
else {
|
||
permissions.push("android.permission.ACCESS_COARSE_LOCATION");
|
||
}
|
||
l.log(`#### 【Request】plus.android.requestPermissions, sdkVersion = ${sdkVersion}`);
|
||
plus.android.requestPermissions(permissions, (res) => {
|
||
l.log(res, `#### 【Response.success】plus.android.requestPermissions:`);
|
||
resolve(true);
|
||
}, (res) => {
|
||
l.warn(res, `#### 【Response.error】plus.android.requestPermissions:`);
|
||
resolve(false);
|
||
});
|
||
}
|
||
else {
|
||
resolve(true);
|
||
}
|
||
});
|
||
}
|
||
/**
|
||
* 蓝牙授权认证。
|
||
*/
|
||
authorize(options) {
|
||
l.log(`【BleAdapter】authorize(options)`, options, this.mContext);
|
||
if (this.mContext.isAppPlus) {
|
||
return this.requestPermissions().then((result) => {
|
||
if (result) {
|
||
return Le.success(true, options);
|
||
}
|
||
else {
|
||
return Le.complete(Ee.ERROR_AUTH_FAILED, "蓝牙权限申请失败!", options, undefined);
|
||
}
|
||
});
|
||
}
|
||
else if (this.mContext.isH5) {
|
||
return Promise.resolve(Le.success(true, options));
|
||
}
|
||
else if (this.mContext.isAlipay) {
|
||
// 支付宝小程序不支持 authorize 接口
|
||
return Promise.resolve(Le.success(true, options));
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
try {
|
||
l.info("#### 【Request】authorize ----> getSetting");
|
||
if (typeof uni.getSetting !== "function" || typeof uni.authorize !== "function") {
|
||
Le.success("不支持蓝牙认证相关接口!", options, resolve);
|
||
return;
|
||
}
|
||
uni.getSetting({
|
||
success: (res) => {
|
||
const authSetting = res.authSetting;
|
||
if (authSetting["scope.bluetooth"] || authSetting["bluetooth"]) {
|
||
l.info(`####【Response.success】authorize.getSetting: 蓝牙权限获取成功!`, res);
|
||
Le.success("蓝牙权限已授权", options, resolve);
|
||
}
|
||
else {
|
||
l.info(`####【Response.success】authorize.getSetting: 蓝牙权限未授权!`, res);
|
||
l.info(`【Request】authorize:`);
|
||
uni.authorize({
|
||
scope: "scope.bluetooth",
|
||
success: (res2) => {
|
||
l.info(`#### 【Response.success】authorize: 蓝牙权限授权成功!`, res2);
|
||
Le.success("蓝牙权限授权成功!", options, resolve);
|
||
},
|
||
fail: (res2) => {
|
||
l.warn(`#### 【Response.fail】authorize: 蓝牙权限授权失败!`, res2);
|
||
// 如果用户拒绝了蓝牙授权申请,则需要提示用户去设置中开启蓝牙权限。
|
||
uni.showModal({
|
||
title: "蓝牙权限未授权",
|
||
content: "请前往设置界面开启蓝牙权限",
|
||
confirmText: "去设置",
|
||
cancelText: "取消",
|
||
showCancel: true,
|
||
success: (modalRes) => {
|
||
if (modalRes.confirm) {
|
||
l.info(`#### 【Response.success】用户点击了去设置按钮!`, modalRes);
|
||
uni.openSetting({
|
||
success: (settingRes) => {
|
||
if (settingRes.authSetting["scope.bluetooth"]) {
|
||
l.info(`#### 【Response.success】蓝牙权限已授权!`, settingRes);
|
||
Le.success("蓝牙权限已授权", options, resolve);
|
||
}
|
||
else {
|
||
l.warn(`#### 【Response.success】蓝牙权限仍未授权!`, settingRes);
|
||
Le.complete(Ee.ERROR_AUTH_FAILED, "蓝牙权限仍未授权", options, resolve);
|
||
}
|
||
},
|
||
fail: (settingRes) => {
|
||
l.warn(`#### 【Response.fail】openSetting, 权限设置界面打开失败!`, settingRes);
|
||
Le.complete(Ee.ERROR_AUTH_FAILED, "权限设置界面打开失败", options, resolve);
|
||
},
|
||
});
|
||
}
|
||
else {
|
||
l.warn(`---- 用户点击了取消按钮!`, modalRes);
|
||
Le.complete(Ee.ERROR_AUTH_FAILED, "用户取消了蓝牙权限设置", options, resolve);
|
||
}
|
||
},
|
||
fail: (modalRes) => {
|
||
l.warn(`#### 【Response.fail】showModal:`, modalRes);
|
||
Le.complete(Ee.ERROR_AUTH_FAILED, "蓝牙权限设置弹窗打开失败", options, resolve);
|
||
},
|
||
});
|
||
},
|
||
});
|
||
}
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】蓝牙权限获取失败!`, res);
|
||
Le.complete(Ee.ERROR_AUTH_FAILED, res, options, resolve);
|
||
},
|
||
});
|
||
}
|
||
catch (error) {
|
||
l.warn(`#### 【Response.error】蓝牙权限获取异常!`, error);
|
||
Le.complete(Ee.ERROR_AUTH_FAILED, "获取蓝牙权限异常,请检查网络连接或小程序设置。", options, resolve);
|
||
}
|
||
});
|
||
}
|
||
createAdapterStateChangeAction() {
|
||
if (!this.mAdapterStateChangeAction) {
|
||
this.mAdapterStateChangeAction = (res) => {
|
||
l.info("==== onBluetoothAdapterStateChange: ====");
|
||
l.info(JSON.stringify(res));
|
||
if (typeof res.available === "string") {
|
||
res.available = res.available === "true";
|
||
}
|
||
if (res.available === false && this.mConnectionMap.size > 0) {
|
||
for (const item of this.mConnectionMap.values()) {
|
||
item.connected = false;
|
||
if (typeof item.connectStateChange === "function") {
|
||
item.connectStateChange({ deviceId: item.deviceId, connected: false });
|
||
}
|
||
}
|
||
}
|
||
if (typeof this.mAdapterStateChange === "function") {
|
||
this.mAdapterStateChange(res);
|
||
}
|
||
};
|
||
const adapter = this.Context.bleAdapter;
|
||
if (adapter && typeof adapter.onBluetoothAdapterStateChange === "function") {
|
||
adapter.onBluetoothAdapterStateChange(this.mAdapterStateChangeAction);
|
||
}
|
||
else {
|
||
uni.onBluetoothAdapterStateChange(this.mAdapterStateChangeAction);
|
||
}
|
||
}
|
||
}
|
||
openAdapter(options) {
|
||
const opts = options || {};
|
||
const isOpened = this.mIsAdapterOpened;
|
||
l.log(`【BleAdapter】openAdapter(isAdapterOpened: ${isOpened}, force: ${opts.force})`, options);
|
||
return new Promise((resolve) => {
|
||
if (this.mIsAdapterOpened && !opts.force) {
|
||
l.log(`---- 蓝牙适配器已经打开!`);
|
||
Le.success("蓝牙适配器已打开!", options, resolve);
|
||
}
|
||
else if (this.mContext.isH5) {
|
||
// 在浏览器中调用 uni.openBluetoothAdapter 会抛异常,并且也无法try cache,所以直接返回失败即可。
|
||
Le.complete(Ee.ERROR_UN_SUPPORTED, "H5环境中不支持蓝牙操作!", options, resolve);
|
||
}
|
||
else {
|
||
this.authorize({
|
||
complete: () => {
|
||
try {
|
||
l.info("#### 【Request】openBluetoothAdapter:", options);
|
||
uni.openBluetoothAdapter({
|
||
success: (openRes) => {
|
||
this.mIsAdapterOpened = true;
|
||
l.info(`#### 【Response.success】openBluetoothAdapter!`, openRes);
|
||
//
|
||
if (!this.mAdapterStateChangeAction) {
|
||
this.createAdapterStateChangeAction();
|
||
}
|
||
//
|
||
Le.success(openRes, options, resolve);
|
||
},
|
||
fail: (res) => {
|
||
const errCode = res.errCode || res.code || 0;
|
||
if (errCode <= 0) {
|
||
l.info(`#### 【Response.fail】蓝牙适配器已打开,errCode = ${errCode}`, res);
|
||
Le.success(res, options, resolve);
|
||
}
|
||
else {
|
||
l.warn("#### 【Response.fail】openBluetoothAdapter:", res);
|
||
if (res.errCode === 3 || res.errno === 3) {
|
||
// 如果用户拒绝了蓝牙授权申请,则需要提示用户去设置中开启蓝牙权限。
|
||
Le.complete(Ee.ERROR_OPEN_ADAPTER, "请在系统的应用设置里面找到HBuilder,打开权限管理,检查蓝牙、附近设备等权限是否已打开。如果已经打开,可以尝试先拒绝,然后重新允许。", options, resolve);
|
||
}
|
||
else {
|
||
Le.complete(Ee.ERROR_OPEN_ADAPTER, res, options, resolve);
|
||
}
|
||
}
|
||
},
|
||
});
|
||
}
|
||
catch (error) {
|
||
l.warn("####【Exception】openBluetoothAdapter:", error);
|
||
Le.complete(Ee.ERROR_OPEN_ADAPTER, error, options, resolve);
|
||
}
|
||
},
|
||
fail: (res) => {
|
||
Le.onResult(res, options, resolve);
|
||
},
|
||
});
|
||
}
|
||
});
|
||
}
|
||
resetAllEventListener() {
|
||
if (typeof uni.offBluetoothAdapterStateChange === "function") {
|
||
l.info(`#### uni.offBluetoothAdapterStateChange:`);
|
||
uni.offBluetoothAdapterStateChange();
|
||
//
|
||
if (this.mAdapterStateChangeAction) {
|
||
this.mAdapterStateChangeAction = undefined;
|
||
}
|
||
}
|
||
// 关闭蓝牙适配器前停止特征值监听事件
|
||
this.resetCharacteristicValueChange();
|
||
}
|
||
closeAdapter(options) {
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
l.info("### 【Request】: closeBluetoothAdapter: ", options);
|
||
// 先断开所有已连接设备,在 lpapi中可能关闭的不彻底
|
||
if (this.mConnectionMap.size > 0) {
|
||
for (const item of this.mConnectionMap.values()) {
|
||
yield this.disconnect({ deviceId: item.deviceId });
|
||
}
|
||
this.mConnectionMap.clear();
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
this.resetAllEventListener();
|
||
uni.closeBluetoothAdapter({
|
||
success: (res) => {
|
||
l.info(`#### 【Response.success】closeBluetoothAdapter:`, res);
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】closeBluetoothAdapter:`, res);
|
||
},
|
||
complete: (res) => {
|
||
// 蓝牙适配器关闭后,打印机会断开链接,此时需要通知下LPAPI
|
||
this.mIsAdapterOpened = false;
|
||
resolve({ statusCode: Ee.OK, resultInfo: res });
|
||
},
|
||
});
|
||
});
|
||
});
|
||
}
|
||
resetAdapter(options) {
|
||
const opts = typeof options === "function" ? { callback: options } : options || {};
|
||
return this.closeAdapter().then(() => {
|
||
// 重新打开蓝牙适配器。
|
||
return this.openAdapter().then((res) => {
|
||
return Le.onResult(res, opts);
|
||
});
|
||
});
|
||
}
|
||
startDiscovery(options) {
|
||
const opts = options || {};
|
||
const onSuccessCallback = (result) => {
|
||
if (result.statusCode === Ee.OK) {
|
||
const scanInterval = opts.interval || 200;
|
||
return new Promise((resolve) => {
|
||
l.info("### 【Request】startBluetoothDevicesDiscovery: ", options);
|
||
uni.startBluetoothDevicesDiscovery({
|
||
interval: scanInterval,
|
||
allowDuplicatesKey: true,
|
||
success: (scanRes) => {
|
||
this.mAdapterStateChange = opts.adapterStateChange;
|
||
l.info(`#### 【Response.success】: startBluetoothDevicesDiscovery:`, scanRes);
|
||
if (this.mDeviceGetTimer && this.mDeviceGetTimer > 0) {
|
||
clearInterval(this.mDeviceGetTimer);
|
||
}
|
||
this.mDeviceGetTimer = setInterval(() => {
|
||
uni.getBluetoothDevices({
|
||
success: (res) => {
|
||
const devices = !res.devices && Array.isArray(res) ? res : res.devices || [];
|
||
// 过滤掉没有名称的设备
|
||
const filters = devices.filter((v) => !!(v.name || v.localName));
|
||
if (filters.length > 0) {
|
||
// logger.log(`---- onBluetoothDeviceFound:`, res);
|
||
opts.deviceFound && opts.deviceFound(filters);
|
||
}
|
||
},
|
||
});
|
||
}, scanInterval);
|
||
//
|
||
if (typeof uni.getBluetoothDevices === "function") {
|
||
uni.getBluetoothDevices({
|
||
success: (res) => {
|
||
// logger.log(`#### 【Response.success: getBluetoothDevices:`);
|
||
const devices = !res.devices && Array.isArray(res) ? res : res.devices || [];
|
||
// 过滤掉没有名称的设备
|
||
const filters = devices.filter((v) => !!(v.name || v.localName));
|
||
if (filters.length > 0) {
|
||
opts.deviceFound && opts.deviceFound(filters);
|
||
}
|
||
},
|
||
});
|
||
}
|
||
//
|
||
Le.success(scanRes, options, resolve);
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】: startBluetoothDevicesDiscovery:`, JSON.stringify(res));
|
||
Le.fail(res, options, resolve);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
else {
|
||
l.warn("========== 蓝牙适配器打开失败! ==========");
|
||
return Le.onResult(result, options);
|
||
}
|
||
};
|
||
// 在Uni中重置蓝牙适配器后,倒是可以自动断开设备链接了,但是特征值的监听无法取消,重新监听特征值后,会接收到很多无效的数据。
|
||
// 所以最好还是不要重置适配器了
|
||
if (opts.resetAdapter) {
|
||
return this.resetAdapter().then(onSuccessCallback);
|
||
}
|
||
else {
|
||
return this.openAdapter().then(onSuccessCallback);
|
||
}
|
||
}
|
||
stopDiscovery(options) {
|
||
return new Promise((resolve) => {
|
||
// 停止蓝牙搜索
|
||
l.info(`###【Request】stopBluetoothDevicesDiscovery:`);
|
||
uni.stopBluetoothDevicesDiscovery({
|
||
success: (res) => {
|
||
l.info(`###【Response.success】stopBluetoothDevicesDiscovery:`);
|
||
Le.success(res, options, resolve);
|
||
// 停止设备检测;
|
||
// 在 UniApp中 onBluetoothDeviceFound 是全局的,注册后无法取消,暂时先用 getBluetoothDevices方法试试。
|
||
if (this.mDeviceGetTimer && this.mDeviceGetTimer > 0) {
|
||
clearInterval(this.mDeviceGetTimer);
|
||
this.mDeviceGetTimer = 0;
|
||
}
|
||
// 停止搜索后,支付宝小程序不会触发该回调,所以手动触发下。
|
||
this.mAdapterStateChange && this.mAdapterStateChange({ discovering: false });
|
||
this.mAdapterStateChange = undefined;
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`###【Response.fail】stopBluetoothDevicesDiscovery:`, JSON.stringify(res));
|
||
Le.fail(res, options, resolve);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
getFoundDevices(options) {
|
||
return new Promise((resolve) => {
|
||
l.info("####【Request】getBluetoothDevices:", options);
|
||
uni.getBluetoothDevices({
|
||
success: (res) => {
|
||
l.info("####【Response.success】getBluetoothDevices:", res);
|
||
const devices = !res.devices && Array.isArray(res) ? res : res.devices || [];
|
||
// 过滤掉没有名称的设备
|
||
const filters = devices.filter((v) => !!(v.name || v.localName));
|
||
Le.success(filters, options, resolve);
|
||
},
|
||
fail: (res) => {
|
||
l.warn("####【Response.fail】getBluetoothDevices:", res);
|
||
Le.fail([], options, resolve);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
createConnectionStateChangeAction() {
|
||
if (!this.mConnectionStateChangeAction) {
|
||
this.mConnectionStateChangeAction = (resp) => {
|
||
l.info(`========== onConnectionStateChange ==========`);
|
||
l.info(JSON.stringify(resp));
|
||
for (const item of this.mConnectionMap.values()) {
|
||
if (resp.deviceId === item.deviceId) {
|
||
if (typeof item.connectStateChange === "function") {
|
||
item.connectStateChange(resp);
|
||
}
|
||
item.connected = resp.connected;
|
||
}
|
||
}
|
||
};
|
||
uni.onBLEConnectionStateChange(this.mConnectionStateChangeAction);
|
||
}
|
||
}
|
||
connect(options) {
|
||
const deviceId = options.deviceId || "";
|
||
return new Promise((resolve) => {
|
||
this.openAdapter()
|
||
.then(() => {
|
||
l.info(`####【Request】createConnection:`, options);
|
||
const connectOptions = {
|
||
deviceId: deviceId,
|
||
success: (res) => {
|
||
l.info(`---- 【Response.success】createConnection:`, res);
|
||
this.mCharacteristicMap.clear();
|
||
// 监控打印机连接状态
|
||
if (!this.mConnectionStateChangeAction) {
|
||
this.createConnectionStateChangeAction();
|
||
}
|
||
this.mConnectionMap.set(deviceId, {
|
||
deviceId: deviceId,
|
||
connected: true,
|
||
connectStateChange: options.connectionStateChange,
|
||
});
|
||
// 经测试:在有些环境下,打印机连接成功之后不能立马进行后续操作,否则无效;
|
||
// IOS环境下,DF2需要200毫秒延时,DF4 100毫秒足够了,保险起见,默认统一设置300毫秒
|
||
let awaitTimes = 300;
|
||
if (this.mContext.isAppPlus) {
|
||
l.log("============== APP-PLUS ============");
|
||
if (this.isAndroid()) {
|
||
// 在安卓环境下,打印机链接成功后大概要等待800毫秒才可以进行后续操作,保险起见,此处设置1000毫秒的延时;
|
||
awaitTimes = 1000;
|
||
}
|
||
}
|
||
setTimeout(() => {
|
||
Le.success(res, options, resolve);
|
||
}, awaitTimes);
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`---- 【Response.fail】createConnection:`, JSON.stringify(res));
|
||
let errCode = res.errCode || res.code;
|
||
if (errCode === 10010) {
|
||
errCode = -1;
|
||
}
|
||
// 支付宝小程序中既没有errCode 也没有 code
|
||
if (typeof errCode === "number" && errCode <= 0) {
|
||
// this.mConnected = true;
|
||
// this.mConnectStatusMap.set(deviceId, true);
|
||
if (!this.mConnectionStateChangeAction) {
|
||
this.createConnectionStateChangeAction();
|
||
}
|
||
this.mConnectionMap.set(deviceId, {
|
||
deviceId: deviceId,
|
||
connected: true,
|
||
connectStateChange: options.connectionStateChange,
|
||
});
|
||
Le.success(res, options, resolve);
|
||
}
|
||
else {
|
||
Le.complete(Ee.ERROR_CONNECT_FAILED, res, options, resolve);
|
||
}
|
||
},
|
||
};
|
||
if (!this.mContext.isAlipay && typeof options.timeout === "number") {
|
||
// 支付宝小程序不能配置 timeout,否则可能会出现链接不上的问题。
|
||
connectOptions.timeout = options.timeout;
|
||
}
|
||
//
|
||
if (this.mContext.isAlipay) {
|
||
my.connectBLEDevice(connectOptions);
|
||
}
|
||
else {
|
||
uni.createBLEConnection(connectOptions);
|
||
}
|
||
})
|
||
.catch((error) => {
|
||
l.warn("----【Exception】createConnection:", error);
|
||
Le.complete(Ee.ERROR_CONNECT_FAILED, error, options);
|
||
});
|
||
});
|
||
}
|
||
resetCharacteristicValueChange() {
|
||
l.info(`#### ===== 重置已连接设备的所有特征值变化通知事件 ===== ####`);
|
||
if (this.mCharacteristicValueChangeMap) {
|
||
this.mCharacteristicValueChangeMap.clear();
|
||
//
|
||
if (typeof uni.offBLECharacteristicValueChange === "function") {
|
||
uni.offBLECharacteristicValueChange();
|
||
this.mCharacteristicValueChangeMap = undefined;
|
||
}
|
||
}
|
||
}
|
||
disconnect(options) {
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
const opts = typeof options === "string" ? { deviceId: options } : options || {};
|
||
const deviceId = opts.deviceId || "";
|
||
const connectInfo = deviceId ? this.mConnectionMap.get(deviceId) : undefined;
|
||
//
|
||
if (!deviceId) {
|
||
l.warn(`### 【Request】disconnect: 参数错误,deviceId = ${deviceId}`, options);
|
||
return Promise.resolve(Le.complete(Ee.ERROR_PARAM, "参数错误", options));
|
||
}
|
||
if (!connectInfo) {
|
||
l.info(`#### 设备未连接!`);
|
||
return Le.success("设备未连接", options);
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
const api = uni;
|
||
// 重置连接状态变化通知事件
|
||
if (typeof uni.offBLEConnectionStateChange === "function") {
|
||
// 微信小程序、飞书小程序适配;
|
||
l.info(`---- offBLEConnectionStateChange:`);
|
||
uni.offBLEConnectionStateChange();
|
||
this.mConnectionStateChangeAction = undefined;
|
||
}
|
||
else if (typeof api.offBLEConnectionStateChanged === "function") {
|
||
// 支付宝/钉钉小程序适配;
|
||
l.info(`---- offBLEConnectionStateChanged:`);
|
||
api.offBLEConnectionStateChanged();
|
||
this.mConnectionStateChangeAction = undefined;
|
||
}
|
||
//
|
||
l.info(`#### ===== 重置已连接设备的所有特征值变化通知事件 ===== ####`);
|
||
this.resetCharacteristicValueChange();
|
||
//
|
||
l.info(`####【Request】closeConnection: ${opts.name || deviceId}`, options);
|
||
if (!this.mIsAdapterOpened || !connectInfo.connected) {
|
||
this.mConnectionMap.delete(deviceId);
|
||
l.info(`#### 设备未连接!`, connectInfo);
|
||
Le.success("设备未连接", options, resolve);
|
||
}
|
||
else {
|
||
const closeOptions = {
|
||
deviceId: deviceId,
|
||
success: (res) => {
|
||
l.log(`####【Response.success】closeConnection:`, res);
|
||
connectInfo.connected = false;
|
||
this.mConnectionMap.delete(deviceId);
|
||
this.mCharacteristicMap.clear();
|
||
Le.success(res, options, resolve);
|
||
},
|
||
fail: (res) => {
|
||
connectInfo.connected = false;
|
||
l.warn(`####【Response.fail】closeConnection:`, res);
|
||
Le.fail(res, options, resolve);
|
||
},
|
||
};
|
||
if (this.mContext.isAlipay) {
|
||
my.disconnectBLEDevice(closeOptions).catch((error) => {
|
||
l.warn(`#### 【Response.Exception】closeConnection:`, error);
|
||
return Le.complete(Ee.ERROR_EXCEPTION, error, options);
|
||
});
|
||
}
|
||
else {
|
||
uni.closeBLEConnection(closeOptions);
|
||
}
|
||
// 特殊情况下设备断开连接无响应
|
||
setTimeout(() => {
|
||
if (connectInfo.connected) {
|
||
connectInfo.connected = false;
|
||
l.warn(`####【Response.timeout】closeConnection:`);
|
||
Le.complete(Ee.ERROR_RESPONSE_TIMEOUT, undefined, options, resolve);
|
||
}
|
||
}, 5000);
|
||
}
|
||
}).catch((error) => {
|
||
this.mConnectionMap.delete(deviceId);
|
||
l.warn(`#### 【Response.Exception】closeConnection:`, error);
|
||
return Le.complete(Ee.ERROR_EXCEPTION, error, options);
|
||
});
|
||
});
|
||
}
|
||
getConnectedDevices(options) {
|
||
if (typeof uni.getConnectedBluetoothDevices !== "function") {
|
||
l.warn(`#### 【Request】getConnectedDevices: 当前环境不支持获取已连接设备!`);
|
||
return Promise.resolve(Le.complete(Ee.ERROR_UN_SUPPORTED, [], options));
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
this.openAdapter().then((res) => {
|
||
if (res.statusCode === 0) {
|
||
l.info(`###【Request】getConnectedDevices:`);
|
||
let devices = undefined;
|
||
uni.getConnectedBluetoothDevices({
|
||
services: [],
|
||
success: (res) => {
|
||
l.info(res, `#### 【Response.success】: getConnectedBluetoothDevices`);
|
||
devices = (res === null || res === void 0 ? void 0 : res.devices) || [];
|
||
Le.success(devices, options, resolve);
|
||
},
|
||
fail: (res) => {
|
||
l.info(res, `#### 【Response.fail】: getConnectedBluetoothDevices`);
|
||
devices = [];
|
||
Le.fail([], options, resolve);
|
||
},
|
||
});
|
||
setTimeout(() => {
|
||
if (!devices) {
|
||
Le.fail([], options, resolve);
|
||
}
|
||
}, 100);
|
||
}
|
||
else {
|
||
Le.fail([], options, resolve);
|
||
}
|
||
});
|
||
});
|
||
}
|
||
setBleMtu(options) {
|
||
const deviceId = options.deviceId || "";
|
||
return new Promise((resolve) => {
|
||
const platform = this.platform;
|
||
if (Le.isIOS(platform)) {
|
||
// IOS 系统使用不做处理,使用默认的MTU大小;
|
||
resolve({ status: -1 });
|
||
}
|
||
else {
|
||
const writeWaits = options.waits || 0;
|
||
let delayTime = 0;
|
||
if (this.mContext.isAppPlus) {
|
||
if (options.chipType === "DF5" || options.mtu >= 500) {
|
||
delayTime = 0;
|
||
}
|
||
else {
|
||
delayTime = 5;
|
||
}
|
||
}
|
||
const waits = writeWaits + delayTime;
|
||
let supportMtu = true;
|
||
if (this.mContext.isAlipay) {
|
||
// 支付宝小程序下的钉钉小程序不支持 setBLEMTU 设置。
|
||
supportMtu = my && typeof my.setBLEMTU === "function";
|
||
}
|
||
else {
|
||
supportMtu = typeof uni.setBLEMTU === "function";
|
||
}
|
||
l.info(`####【Request】setBleMTU: { deviceId: ${deviceId}, mtu: ${options.mtu}, platform: ${platform}}, supported: ${supportMtu}`);
|
||
// 在支付宝小程序中,不管是不是DF4芯片,必须要写上下MTU(即便回调失败),后续才可以正常发送数据,否则打印异常。
|
||
// 支付宝小程序虽然协商失败,但是必须要协商;
|
||
// 钉钉小程序不支持MTU协商
|
||
if (supportMtu) {
|
||
let resMtu = 0;
|
||
if (typeof uni.onBLEMTUChange === "function") {
|
||
l.info(`####【Request】onBLEMTUChange:`);
|
||
uni.onBLEMTUChange((res) => {
|
||
l.info(`---- onBleMTUChange: ${res.mtu}`, res);
|
||
resMtu = res.mtu;
|
||
uni.offBLEMTUChange();
|
||
});
|
||
}
|
||
uni.setBLEMTU({
|
||
deviceId: deviceId,
|
||
mtu: 512,
|
||
success: (resp) => {
|
||
l.info(`#### 【Response.success】: setBleMTU`);
|
||
l.info(JSON.stringify(resp));
|
||
const mtu = resp.mtu > 0 ? resp.mtu : resMtu;
|
||
if (mtu > 0) {
|
||
// 小程序中会执行这行代码
|
||
resolve({ status: 0, mtu: mtu > options.mtu ? options.mtu : mtu, waits: waits });
|
||
}
|
||
else {
|
||
// uniapp中不支持 getBLEMTU,小程序中可以通过 onBLEMTUChange 来获取,所以此处暂时直接返回,后期根据实际情况在进行调整。
|
||
// uniapp中不支持 onBLEMTUChange 回调,所以会执行这行代码。
|
||
resolve({ status: 0, waits: waits });
|
||
}
|
||
},
|
||
fail: (resp) => {
|
||
l.warn(`#### 【Response.fail】 setBLEMtu: MTU协商失败,正在尝试读取当前mtu大小`, resp);
|
||
uni.getBLEMTU({
|
||
deviceId: deviceId,
|
||
success: (getRes) => {
|
||
l.info(`#### 【Response.success】: getBleMTU`, getRes);
|
||
if (getRes.mtu && getRes.mtu > options.mtu) {
|
||
resolve({ status: 0, mtu: resp.mtu || options.mtu, waits: waits });
|
||
}
|
||
else if (options.chipType && !options.required) {
|
||
// DF4及之后的蓝牙芯片不需要进行MTU的协商处理;
|
||
resolve({ status: -1, waits: waits });
|
||
}
|
||
else {
|
||
resolve({ status: 2, waits: waits });
|
||
}
|
||
},
|
||
fail: (getRes) => {
|
||
l.warn(`#### 【Response.fail】: getBleMTU`, getRes);
|
||
resolve({ status: 2, waits: waits });
|
||
},
|
||
});
|
||
},
|
||
});
|
||
}
|
||
else {
|
||
if (options.chipType && !options.required) {
|
||
l.info(`####【Response.unsupported】setBleMTU: 当前环境不支持MTU协商!DFType = ${options.chipType}`);
|
||
// DF4及之后的蓝牙芯片不需要进行MTU的协商处理;
|
||
resolve({ status: -1, waits: waits });
|
||
}
|
||
else {
|
||
l.warn(`####【Response.unsupported】setBleMTU: 当前环境不支持MTU协商!DFType = ${options.chipType}`);
|
||
resolve({ status: 1, waits: waits });
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
getGATTServices(options) {
|
||
const deviceId = options.deviceId || "";
|
||
return new Promise((resolve) => {
|
||
l.info(`#### 【Request】getGattService: ${deviceId}`);
|
||
uni.getBLEDeviceServices({
|
||
deviceId: deviceId,
|
||
success: (resp) => {
|
||
l.info(`#### 【Response.success】getGattService: ${deviceId}`);
|
||
// logger.info(JSON.stringify(resp));
|
||
const services = (resp.services || []).map((v) => {
|
||
return Object.assign(v, { uuid: v.uuid || v.serviceId || "" });
|
||
});
|
||
if (services.length <= 0) {
|
||
l.warn(`---- 服务列表为空:${JSON.stringify(resp)}`);
|
||
}
|
||
Le.successResult(services, options, resolve);
|
||
},
|
||
fail: (resp) => {
|
||
l.warn(`#### 【Response.fail】getGattService: ${deviceId}`);
|
||
l.warn(JSON.stringify(resp));
|
||
Le.failResult([], options, resolve);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
getGATTCharacteristics(options) {
|
||
const deviceId = options.deviceId || "";
|
||
const serviceId = options.serviceId || "";
|
||
return new Promise((resolve) => {
|
||
l.info(`#### 【Request】getCharacteristicList(${options.serviceId})`);
|
||
const cacheList = serviceId ? this.mCharacteristicMap.get(serviceId) : undefined;
|
||
if (cacheList) {
|
||
l.info(`#### 【Response.Cache】getCharacteristicList(${options.serviceId})`);
|
||
Le.successResult(cacheList, options, resolve);
|
||
return;
|
||
}
|
||
uni.getBLEDeviceCharacteristics({
|
||
deviceId: deviceId,
|
||
serviceId: serviceId,
|
||
success: (res) => {
|
||
l.info(`#### 【Response.success】getCharacteristicList(${options.serviceId})`);
|
||
// logger.log(JSON.stringify(res));
|
||
const characterList = res.characteristics || [];
|
||
if (characterList.length <= 0) {
|
||
l.warn(`---- 特征值列表为空:${JSON.stringify(res)}`);
|
||
}
|
||
const list = characterList.map((v) => {
|
||
const prop = v.properties || {};
|
||
let propValue = 0;
|
||
if (prop.read)
|
||
propValue |= Qe.READ;
|
||
if (prop.write) {
|
||
if (prop.writeNoResponse)
|
||
propValue |= Qe.WRITE_NO_RESPONSE;
|
||
else
|
||
propValue |= Qe.WRITE;
|
||
}
|
||
if (prop.notify)
|
||
propValue |= Qe.NOTIFY;
|
||
if (prop.indicate)
|
||
propValue |= Qe.INDICATE;
|
||
return Object.assign(v, {
|
||
serviceId: options.serviceId,
|
||
uuid: v.uuid || v.characteristicId || "",
|
||
properties: propValue,
|
||
});
|
||
});
|
||
if (list.length > 0) {
|
||
this.mCharacteristicMap.set(serviceId, list);
|
||
}
|
||
Le.successResult(list, options, resolve);
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】getCharacteristicList(${options.serviceId})`, res);
|
||
Le.failResult([], options, resolve);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
onBLECharacteristicValueChange(characterId, callback) {
|
||
// 如果不支持关闭ble特征值变化通知的功能,则统一注册,并且只注册一次后,根据实际需要进行分发处理。
|
||
l.log(`#### 【Register】CharacterValueChanged[${Le.getShortUUID(characterId)}]`);
|
||
if (!this.mCharacteristicValueChangeMap) {
|
||
l.info(`#### ===== 开始监视已连接设备的所有特征值变化通知事件 ===== ####`);
|
||
this.mCharacteristicValueChangeMap = new Map();
|
||
const action = (resp) => {
|
||
if (this.mContext.isDingTalk) {
|
||
// 钉钉小程序信用流控返回相关数据的时候,特征值 UUID 是错误的,需要特殊处理下。
|
||
const map = this.mCharacteristicValueChangeMap;
|
||
const keyList = map ? Array.from(map.keys()) : [];
|
||
let respId = keyList.find((v) => Le.isMatchedUUID(v, resp.characteristicId));
|
||
const data = typeof resp.value === "string"
|
||
? Le.hex16ToArrayBuffer(resp.value)
|
||
: new Uint8Array(resp.value);
|
||
if ((data[0] === 1 && data.length === 2) || (data[0] === 2 && data.length === 3)) {
|
||
const fcId = keyList.find((v) => Le.isMatchedUUID("FF03", v));
|
||
if (fcId)
|
||
respId = fcId;
|
||
}
|
||
const callback = respId && map ? map.get(respId) : undefined;
|
||
if (typeof callback === "function") {
|
||
callback(resp);
|
||
}
|
||
}
|
||
else if (this.mCharacteristicValueChangeMap) {
|
||
for (const item of this.mCharacteristicValueChangeMap) {
|
||
if (Le.isMatchedUUID(item[0], resp.characteristicId)) {
|
||
item[1](resp);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
};
|
||
//
|
||
const adapter = this.Context.bleAdapter;
|
||
if (adapter && typeof adapter.onBLECharacteristicValueChange === "function") {
|
||
adapter.onBLECharacteristicValueChange(action);
|
||
}
|
||
else {
|
||
uni.onBLECharacteristicValueChange(action);
|
||
}
|
||
}
|
||
//
|
||
this.mCharacteristicValueChangeMap.set(characterId, callback);
|
||
}
|
||
offBLECharacteristicValueChange(cid) {
|
||
const map = this.mCharacteristicValueChangeMap;
|
||
if (!cid || !map)
|
||
return;
|
||
//
|
||
const shortId = Le.getShortUUID(cid);
|
||
const remainIds = Array.from(map.keys()).map((v) => Le.getShortUUID(v));
|
||
map.delete(cid);
|
||
l.log(`#### 【Unregister】CharacteristicValueChange: [${shortId}], remainCharacteristics: [${remainIds}]`);
|
||
// 备注:此处不用取消特征值的侦听操作,在断开打印机的时候统一取消;
|
||
}
|
||
read(options) {
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
const deviceId = options.deviceId || "";
|
||
const cid = options.characteristicId || "";
|
||
const shortId = Le.getShortUUID(cid);
|
||
const connectInfo = deviceId ? this.mConnectionMap.get(deviceId) : undefined;
|
||
//
|
||
if (!deviceId || !options.serviceId || !cid) {
|
||
l.warn(`#### 【Request】readCharacteristic, 参数错误:`, options);
|
||
return Le.complete(Ee.ERROR_PARAM, "参数错误", options);
|
||
}
|
||
if (!(connectInfo === null || connectInfo === void 0 ? void 0 : connectInfo.connected)) {
|
||
l.warn(`#### 【Request】readCharacteristic, 设备连接已断开:`, options);
|
||
return Le.complete(Ee.ERROR_DISCONNECTED, "设备连接已断开", options);
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
l.info(`#### 【Request】readCharacteristic(uuid: ${shortId})`);
|
||
// 监控特征值变化
|
||
let resolved = false;
|
||
if (this.mContext.isAppPlus || this.mContext.isWeiXin) {
|
||
this.onBLECharacteristicValueChange(cid, (res) => {
|
||
const value = typeof res.value === "string"
|
||
? Le.hex16ToArrayBuffer(res.value)
|
||
: new Uint8Array(res.value);
|
||
const hexStr = typeof res.value === "string" ? res.value : Le.arrayBufferToHex16(value);
|
||
l.info(`#### 【Response】onReadCharacteristicValueChange[${shortId}]: [${hexStr}]`);
|
||
// 执行回调。
|
||
if (res.characteristicId == cid) {
|
||
resolved = true;
|
||
Le.success(value, options, resolve);
|
||
// 取消特征值侦听
|
||
this.offBLECharacteristicValueChange(cid);
|
||
}
|
||
});
|
||
}
|
||
//
|
||
uni.readBLECharacteristicValue({
|
||
deviceId: deviceId,
|
||
serviceId: options.serviceId,
|
||
characteristicId: cid,
|
||
success: (res) => {
|
||
l.info(`#### 【Response.success】readBLECharacteristicValue: [${shortId}]:`, res);
|
||
l.log(JSON.stringify(res));
|
||
if (!(this.mContext.isAppPlus || this.mContext.isWeiXin)) {
|
||
// 支付宝、钉钉、飞书等小程序直接返回;
|
||
const result = res.characteristic || {};
|
||
Le.success(result.value || "", options, resolve);
|
||
}
|
||
else {
|
||
// AppPlus 或者 微信小程序需等待 onBLECharacteristicValueChange 来处理。
|
||
const timeout = 1500;
|
||
setTimeout(() => {
|
||
if (!resolved) {
|
||
l.warn(`#### 【Response.timeout】readBLECharacteristicValue: 响应超时, timeout: ${timeout}!`);
|
||
Le.complete(Ee.ERROR_RESPONSE_TIMEOUT, "", options, resolve);
|
||
}
|
||
}, timeout);
|
||
}
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】readBLECharacteristicValue: [${shortId}]:`, res);
|
||
Le.complete(Ee.ERROR_READ_CHARACTERISTIC, "", options, resolve);
|
||
},
|
||
});
|
||
});
|
||
});
|
||
}
|
||
notify(options) {
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
const deviceId = options.deviceId || "";
|
||
const characteristicId = options.characteristicId || "";
|
||
const shortId = Le.getShortUUID(characteristicId);
|
||
const connectInfo = deviceId ? this.mConnectionMap.get(deviceId) : undefined;
|
||
if (!deviceId || !options.serviceId || !characteristicId) {
|
||
l.warn(`#### 【Request】notifyCharacteristic, 参数错误:`, options);
|
||
return Le.complete(Ee.ERROR_PARAM, "参数错误", options);
|
||
}
|
||
if (!(connectInfo === null || connectInfo === void 0 ? void 0 : connectInfo.connected)) {
|
||
l.warn(`#### 【Request】notifyCharacteristic, 设备连接已断开:`, options);
|
||
return Le.complete(Ee.ERROR_DISCONNECTED, "设备连接已断开", options);
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
const state = typeof options.state === "boolean" ? options.state : true;
|
||
// 取消数据监听回调,避免二次链接的时候造成的数据干扰。
|
||
if (state) {
|
||
l.info(`#### 【Request.start】 - notifyCharacteristic[${shortId}]:`);
|
||
}
|
||
else {
|
||
this.offBLECharacteristicValueChange(characteristicId);
|
||
l.info(`#### 【Request.stop 】 - notifyCharacteristic[${shortId}]:`);
|
||
}
|
||
// 为了避免遗漏数据,监听之前先注册回调;
|
||
if (state) {
|
||
l.info(`####【Request】onBLECharacteristicValueChange`);
|
||
this.onBLECharacteristicValueChange(characteristicId, (result) => {
|
||
const respVal = typeof result.value === "string"
|
||
? Le.hex16ToArrayBuffer(result.value)
|
||
: new Uint8Array(result.value);
|
||
// const respId = LPAUtils.getShortUUID(result.characteristicId || "");
|
||
// const hexStr = LPAUtils.arrayBufferToHex16(respVal);
|
||
// logger.log(`#### 【Response】onNotifyCharacteristicValueChange[${respId}]: [${hexStr}]`, result);
|
||
if (result.characteristicId === characteristicId) {
|
||
options.dataReceived && options.dataReceived(respVal);
|
||
}
|
||
});
|
||
}
|
||
const res = uni.notifyBLECharacteristicValueChange({
|
||
deviceId: deviceId,
|
||
serviceId: options.serviceId,
|
||
characteristicId: characteristicId,
|
||
state: state,
|
||
success: (res) => {
|
||
l.info(`####【Response.success】: notifyCharacteristic[${shortId}], S[${state}]:`, res);
|
||
if (state) {
|
||
// 备注:在多次同时侦听流控特征值与数据特征值的时候,偶尔会接收不到数据。
|
||
// 所以需要在特征值侦听成功后,多等待一端时间后,在执行数据的写入操作。
|
||
setTimeout(() => {
|
||
Le.success(res, options, resolve);
|
||
}, 10);
|
||
}
|
||
else {
|
||
Le.success(res, options, resolve);
|
||
}
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】: notifyCharacteristic, S[${state}]:`, res);
|
||
if (state) {
|
||
Le.complete(Ee.ERROR_NOTIFY_CHARACTERISTIC, res, options, resolve);
|
||
}
|
||
else {
|
||
Le.success(res, options, resolve);
|
||
}
|
||
},
|
||
});
|
||
// 钉钉小程序返回值是个 Promise,并且可能会抛异常,此处做下处理
|
||
Promise.resolve(res).catch((error) => {
|
||
l.warn(`#### 【Response.Exception】: notifyBLECharacteristicValueChange: `, error);
|
||
return Le.complete(Ee.ERROR_EXCEPTION, error, options);
|
||
});
|
||
});
|
||
});
|
||
}
|
||
write(options) {
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
const deviceId = options.deviceId || "";
|
||
const serviceId = options.serviceId || "";
|
||
const characteristicId = options.characteristicId || "";
|
||
const data = options.value || options.data;
|
||
const writeValue = this.mContext.isAlipay ? Le.arrayBufferToHex16(data, "") : data.buffer;
|
||
const pkgName = `[P ${options.pkgIndex} - SUP ${options.subPkgIndex}]`;
|
||
//
|
||
if (!deviceId || !serviceId || !characteristicId || !data) {
|
||
l.warn(`【Request】writeCharacteristic: ${pkgName}-参数错误`, options);
|
||
return Le.complete(Ee.ERROR_PARAM, "参数错误", options);
|
||
}
|
||
//
|
||
const connectInfo = this.mConnectionMap.get(deviceId);
|
||
if (!connectInfo || !connectInfo.connected) {
|
||
l.warn(`####【Request】writeCharacteristic: ${pkgName}-设备连接已断开, info: `, connectInfo);
|
||
return Le.complete(Ee.ERROR_DISCONNECTED, "设备连接已断开", options);
|
||
}
|
||
//
|
||
return new Promise((resolve) => {
|
||
if (this.mShowWriteLog) {
|
||
l.log(`#### 【Request】writeBLECharacteristicValue: ${pkgName}`);
|
||
}
|
||
uni.writeBLECharacteristicValue({
|
||
deviceId: deviceId,
|
||
serviceId: serviceId,
|
||
characteristicId: characteristicId,
|
||
value: writeValue,
|
||
// 备注:在HarmonyOS版的微信小程序中,必须要配置 writeType。
|
||
// writeType: "writeNoResponse",
|
||
writeType: options.withResponse ? "write" : "writeNoResponse",
|
||
success: (res) => {
|
||
if (this.mShowWriteLog) {
|
||
l.log(`#### 【Response.success】writeBLECharacteristicValue: ${pkgName}`, res);
|
||
}
|
||
Le.success(res, options, resolve);
|
||
// 关闭写入日志
|
||
this.mShowWriteLog = false;
|
||
},
|
||
fail: (res) => {
|
||
l.warn(`#### 【Response.fail】writeBLECharacteristicValue: ${pkgName}, writeWaits: ${options.writeWaits}`, res);
|
||
Le.complete(Ee.ERROR_WRITE_CHARACTERISTIC, res, options, resolve);
|
||
// 如果数据写入失败,则打开写入日志信息,供参考;
|
||
this.mShowWriteLog = true;
|
||
},
|
||
});
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
class LPAPIFactory {
|
||
/**
|
||
* 获取LPAPI接口实例。
|
||
*/
|
||
static getInstance(options) {
|
||
if (!LPAPIFactory.api) {
|
||
LPAPIFactory.api = LPAPIFactory.createInstance(options);
|
||
}
|
||
else if (options) {
|
||
const prevContext = LPAPIFactory.api.drawContext;
|
||
const context = UniContext.createInstance(options, prevContext);
|
||
if (context && context !== prevContext) {
|
||
LPAPIFactory.api.setDrawContext(context);
|
||
}
|
||
LPAPIFactory.api.setOptions(options);
|
||
}
|
||
//
|
||
return LPAPIFactory.api;
|
||
}
|
||
static initApi(options) {
|
||
return __awaiter(this, void 0, void 0, function* () {
|
||
const opts = (typeof Option === "function" ? { callback: options } : options || {});
|
||
const api = this.getInstance(options);
|
||
//
|
||
const res = yield api.openAdapter({ force: true });
|
||
if (typeof opts.callback === "function") {
|
||
opts.callback(api, res);
|
||
}
|
||
//
|
||
return api;
|
||
});
|
||
}
|
||
static resetApi(options) {
|
||
if (LPAPIFactory.api) {
|
||
return LPAPIFactory.api.resetAdapter(options).then((_resp) => {
|
||
return LPAPIFactory.getInstance(options);
|
||
});
|
||
}
|
||
else {
|
||
return Promise.resolve(this.getInstance(options));
|
||
}
|
||
}
|
||
// /**
|
||
// * 销毁蓝牙实例,同时关闭蓝牙适配器,释放所有已连接的资源。
|
||
// */
|
||
// public static quitApi() {
|
||
// if (LPAPIFactory.api) {
|
||
// LPAPIFactory.api.quit();
|
||
// // 相关的 onDeviceFound 和 onCharacteristicValueChange 在UniApp中没有对应off相关事件,
|
||
// // 如果采用多实例模式的话,相关的回调函数还是在 第一个实例中,其他实例估计无法获取回调信息。
|
||
// // LPAPIFactory.api = undefined;
|
||
// }
|
||
// }
|
||
static createInstance(options) {
|
||
const opts = options || {};
|
||
//
|
||
Ri.setLogLevel(typeof opts.logLevel === "number" ? opts.logLevel : opts.showLog);
|
||
l.info(`======== LPAPIFactory.createInstance() ========`, options);
|
||
//
|
||
const adapter = new BleAdapter(options);
|
||
const context = adapter.isH5 ? undefined : UniContext.createInstance(opts);
|
||
l.info(`---- context: `, context);
|
||
return Ri.create(Object.assign(Object.assign({}, opts), { adapter: adapter, context: context, createContext: (args) => {
|
||
return adapter.isH5 ? undefined : new UniContext(args);
|
||
}, onQuit: () => {
|
||
LPAPIFactory.api = undefined;
|
||
} }));
|
||
}
|
||
}
|
||
class UniPreview extends Te {
|
||
constructor(options) {
|
||
super(options);
|
||
}
|
||
createDrawContext(options) {
|
||
return new UniContext(Object.assign(Object.assign({}, options), { apiMode: false }));
|
||
}
|
||
attachTo(options) {
|
||
if (!this.drawContext) {
|
||
this.drawContext = this.createDrawContext(options);
|
||
}
|
||
// 如果未指定目标容器,则只是根据给定的容器大小来计算canvas的大小,并渲染 canvas 内容即可。
|
||
const viewWidth = options.viewWidth || 0;
|
||
const viewHeight = options.viewHeight || 0;
|
||
return this.raiseViewChanged(viewWidth, viewHeight);
|
||
}
|
||
}
|
||
function definePrintConfig(options) {
|
||
return options;
|
||
}
|
||
function definePageConfig(page) {
|
||
return page;
|
||
}
|
||
function defineDrawConfig(options) {
|
||
return options;
|
||
}
|
||
|
||
export { a as Alignment, h as AntiColorMode, y as Barcode, Mt as Barcode1DEncoder, Re as Barcode2DEncoder, Pe as Barcode2DType, s as BarcodeTextPos, b as BarcodeType, C as BitMatrix, hi as BleConnection, c as BorderAlign, Qe as CharacteristicProperty, Ie as DegreeContent, ai as DeviceConnection, ui as DeviceManager, xe as DrawContext, ve as DrawType, p as DzCanvas, R as DzChar, P as DzCharCodes, Ge as DzCommand, be as DzImageData, Ue as DzPackage, mi as DzPrinter, Se as DzTextDecoder, I as DzTextEncoder, e as DzUtil, qe as EDataSendMode, Ze as EPrintStatus, Bt as EccLevel, me as FinderPattern, r as FontStyle, Me as GBKUtils, i as LOG_LEVEL, Ne as LPAEmitter, Ri as LPAPI, LPAPIFactory, Le as LPAUtils, Xe as LPA_DeviceConnectType, ze as LPA_DeviceType, we as LPA_GapType, Ye as LPA_GattProperty, ii as LPA_JobAction, Ae as LPA_JobName, Oe as LPA_PrintDarkness, _e as LPA_PrintSpeed, De as LPA_Printable, Ee as LPA_Result, Te as LabelContext, g as LineSpaceParser, Fe as PackageBuffer, $e as PackageBufferList, Ke as PrintPackage, Ce as QRCode, Nt as QRUtils, si as RequestMessage, o as RotateMode, f as ScaleCanvas, u as ScaleUnit, fi as SupportPrinterMatcher, n as TextDecoration, UniPreview, ti as ValueType, Pi as WdfxParser, d as WrapMode, defineDrawConfig, definePageConfig, definePrintConfig, l as logger };
|