emis-frontend/src/utils/TanexPrinterSdk.js
2024-08-18 11:38:53 +08:00

681 lines
18 KiB
JavaScript

'use strict'
import { download } from '@/utils/request'
/*
TanexPrinterSdk
getPrinterList: 获取打印机列表
getPrintTplList: 获取打印模版列表
batchPrint:发送打印
batchGetPDF:PDF预览和下载
getPrinterVer:获取打印组件版本信息
printerIsRead:打印机已经OK的信号
updatePrintStatus: 打印状态更新
*/
import { getToken } from '@/utils/auth'
class TanexPrinterSdk {
VERSION="1.0.0"
MAX_SENT_RETRY_COUNT = 9;
XD_PRINTER_HOST = process.env.VUE_APP_PRINTER_HOST;
// WS_URL = 'ws://'+this.XD_PRINTER_HOST+'/ws';
// HTTP_GET_PDF = 'http://'+this.XD_PRINTER_HOST+'/api/downPdfFile';
// HTTP_GET_PDF = "http://192.168.88.100:17080/api/downPdfFile";
AUTH_TOKEN=null;
WS_INIT = 0;
WS_OPEN = 1;
WS_CLOSING = 2;
WS_CLOSE = 3;
// 和服务端连接的socket对象
ws = null;
// WS 回调函数
onOpenCallback =[];
onCloseCallback=[];
onErrorCallback =[];
// onMessageCallback =[];
onGetPrinterCallback =[];
onGetPrintTplCallback =[];
onBatchGetPDFCallback = null;
// 自定义 回调函数
callbacks ={}
// 打印机列表
printerList = []
// 打印模版列表
printTplList = []
// PDF文件缓存
recievePdfFileList = []
sendPdfFileListCount = 0
pdfFileReceiveMap = new Map();
recievePdfFileTimer = null;
// 默认打印机
defaultPrinter = null;
defaultTplCode = null;
isSendSetToken=false;
isSendGetTpl=false;
isSendGetPrinter=false;
// 标识:是否连接成功 , 记录重试的次数,重新连接尝试的次数
connected = false;
printerIsRead = false;
sendRetryCount = 0;
connectRetryCount = 0;
static instance = null;
constructor() {
this.instance = null
}
static getInstance() {
if (!this.instance) {
this.instance = new TanexPrinterSdk()
}
return this.instance
}
// 外部方法----------------------------------------------------------------
init(onOpen,onClose,onError,onGetPrinter,onGetPrintTpl,OnGetPrintTpl){
// 初始化参数建立连接
this.token=getToken();
this.connect();
this.start();
}
getPrinterHost(){
return this.XD_PRINTER_HOST;
}
restPrinterHost(host){
this.XD_PRINTER_HOST=host;
if (this.ws && this.getWSReadyState() != this.WS_CLOSING && this.getWSReadyState() != this.WS_CLOSE) {
this.ws.close();
this.ws=null;
}else{
this.ws=null;
}
this.connect();
this.start();
}
setOnOpen(callback){
this.onOpenCallback.push(callback);
if(this.connected){
if(callback!=null){
callback();
}
}
}
setOnClose(callback){
this.onCloseCallback.push(callback);
if(!this.connected){
if(callback!=null){
callback();
}
}
}
setOnError(callback){
this.onErrorCallback.push(callback);
}
setOnGetPrinter(callback){
this.onGetPrinterCallback.push(callback);
if(this.connected){
if(callback!=null){
callback();
}
}
}
setOnGetPrintTpl(callback){
this.onGetPrintTplCallback.push(callback);
if(this.connected){
if(callback!=null){
callback();
}
}
}
// 只支持一个事件响应
setOnBatchGetPDF(callback){
this.onBatchGetPDFCallback = callback;
}
// 获取打印机列表
getPrinterTplList(){
return this.printerList;
}
// 获取打印模版列表
getPrintTplList(){
return this.printTplList;
}
// 获取默认打印机
getDefaultPrinter(){
return this.defaultPrinter;
}
// 批量获取PDF文件
batchGetPDF(tplCode,printerName,orderList,printManCode,callback){
if(tplCode&&printerName&&orderList&&orderList.length>0){
this.setOnBatchGetPDF(callback);
// 超时计算
let that = this;
this.sendBatchGetPDFCMD(tplCode,printerName,orderList,printManCode);
// this.recievePdfFileTimer = setTimeout(function(){
// if(that.onBatchGetPDFCallback!=null){
// that.onBatchGetPDFCallback([],false,"打印超时");
// }
// clearTimeout(that.recievePdfFileTimer);
// }, 6000)
}
}
batchGetPDFAdv(printDataList,billCount,printManCode,callback){
if(printDataList&&printDataList.length>0){
if(callback){
this.setOnBatchGetPDF(callback);
}
let that=this;
this.sendBatchGetPDFAdvCMD(printDataList,billCount,printManCode);
// this.recievePdfFileTimer = setTimeout(function(){
// if(that.onBatchGetPDFCallback!=null){
// that.onBatchGetPDFCallback(500,"打印超时");
// }
// clearTimeout(that.recievePdfFileTimer);
// }, 6000)
}
}
// 批量打印
batchPrint(tplCode,printerName,orderList,printManCode){
if(tplCode&&printerName&&orderList&&orderList.length>0){
this.sendBatchPrintCMD(tplCode,printerName,orderList,printManCode);
}
}
// 高级打印接口,多个模版
batchPrintAdv(printDataList,printManCode){
if(printDataList&&printDataList.length>0){
this.sendBatchPrintAdvCMD(printDataList,printManCode);
}
}
refreshPrintTpl(){
this.sendRefreshPrintTplListCMD();
}
getRequestId() {
let requestId = 'req' + new Date().getTime().toString(36) + Math.random().toString(36).substring(2, 9);
return requestId;
}
//--内部方法--------------------------------------------------------------
sendSetTokenCMD(){
// if(this.isSendSetToken){
// return;
// }
// {"CMD":"setToken","status":"1","Data":"token"}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="setToken";
printCmd['Status']="1";
printCmd['Data']=getToken();
// console.log(JSON.stringify(printCmd));
this.send(JSON.stringify(printCmd),null);
}
sendBatchPrintAdvCMD(printDataList,printManCode){
// {"CMD":"batchPrint","status":"1","Data":["DT20210901001","DT20210901002"]}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="batchPrint";
printCmd['Status']="1";
if(printDataList && printDataList.length>0){
printDataList.forEach(item=>{
item["printManCode"]=printManCode;
});
printCmd['Data']=printDataList
this.send(JSON.stringify(printCmd),null);
}
/*
[
{
"tplCode":tplCode,
"printerName":printerName,
"orderList":orderList.toString()
}
]
*/
// if(orderList!=null && orderList.length>0){
// let printData=[{
// "tplCode":tplCode,
// "printerName":printerName,
// "orderList":orderList.toString()
// }]
// printCmd['Data']=printData
// // console.log(JSON.stringify(printCmd));
// this.send(JSON.stringify(printCmd),null);
// }
}
sendBatchGetPDFAdvCMD(printDataList,billCount,printManCode){
// {"CMD":"batchGetPDF","status":"1","Data":["DT20210901001","DT20210901002"]}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="batchGetPDF";
printCmd['Status']="1";
if(printDataList && printDataList.length>0){
printDataList.forEach(item=>{
item["printManCode"]=printManCode;
});
printCmd['Data']=printDataList
this.recievePdfFileList = [];
this.pdfFileReceiveMap=new Map();
this.sendPdfFileListCount = billCount;
this.send(JSON.stringify(printCmd),null);
}
}
sendBatchPrintCMD(tplCode,printerName,orderList,printManCode){
// {"CMD":"batchPrint","status":"1","Data":["DT20210901001","DT20210901002"]}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="batchPrint";
printCmd['Status']="1";
if(orderList!=null && orderList.length>0){
let printData=[{
"tplCode":tplCode,
"printerName":printerName,
"printManCode":printManCode,
"orderList":orderList.toString()
}]
printCmd['Data']=printData
// console.log(JSON.stringify(printCmd));
this.send(JSON.stringify(printCmd),null);
}
}
sendBatchGetPDFCMD(tplCode,printerName,orderList,printManCode){
// {"CMD":"batchGetPDF","status":"1","Data":["DT20210901001","DT20210901002"]}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="batchGetPDF";
printCmd['Status']="1";
if(orderList!=null && orderList.length>0){
let printData=[{
"tplCode":tplCode,
"printerName":printerName,
"printManCode":printManCode,
"orderList":orderList.toString()
}]
this.recievePdfFileList = [];
this.pdfFileReceiveMap=new Map();
this.sendPdfFileListCount = orderList.length;
printCmd['Data']=printData
// console.log(JSON.stringify(printCmd));
this.send(JSON.stringify(printCmd),null);
}
}
sendGetPrinterListCMD(){
// {"CMD":"getPrinterList","status":"1","Data":""}
// if(this.isSendGetPrinter){
// return;
// }
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="getPrinterList";
printCmd['Status']="1";
printCmd['Data']="";
// console.log(JSON.stringify(printCmd));
this.send(JSON.stringify(printCmd),null);
}
sendGetPrintTplListCMD(){
// if(this.isSendGetTpl){
// return;
// }
// {"CMD":"getPrintTplList","status":"1","Data":""}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="getPrintTplList";
printCmd['Status']="1";
printCmd['Data']="";
// console.log(JSON.stringify(printCmd));
this.send(JSON.stringify(printCmd),null);
}
sendRefreshPrintTplListCMD(){
// {"CMD":"getPrintTplList","status":"1","Data":"reInit"}
var printCmd={};
printCmd['RequestId']=this.getRequestId();
printCmd['CMD']="getPrintTplList";
printCmd['Status']="1";
printCmd['Data']="reInit";
// console.log(JSON.stringify(printCmd));
this.send(JSON.stringify(printCmd),null);
}
// 连接服务器的方法
connect() {
// 连接服务器
if (!window.WebSocket) {
console.log('您的浏览器不支持WebSocket');
return null;
}
if (!this.ws || this.getWSReadyState() === this.WS_CLOSING || this.getWSReadyState() === this.WS_CLOSE) {
try {
let wsUrl = 'ws://'+this.XD_PRINTER_HOST+'/ws';
this.ws = new WebSocket(wsUrl);
this.ws.onerror = () => {
// console.log("ws onerror!");
if(this.onErrorCallback.length>0){
this.onErrorCallback.forEach(callback=>{
if(callback!=null){
callback();
}
})
}
}
this.ws.onopen = () => {
// console.log("ws onopen!");
this.connected = true
this.connectRetryCount = 0
if(this.onOpenCallback.length>0){
this.onOpenCallback.forEach(callback=>{
if(callback!=null){
callback();
}
})
}
this.sendSetTokenCMD();
this.sendGetPrinterListCMD();
this.sendGetPrintTplListCMD();
};
this.ws.onpong = () => {
// console.log("ws onpong!");
}
this.ws.onclose = () => {
// console.log("ws onclose!");
this.connected = false;
this.connectRetryCount++;
if(this.connectRetryCount>120){
this.connectRetryCount=0;
}
if(this.onCloseCallback.length>0){
this.onCloseCallback.forEach(callback=>{
if(callback!=null){
callback();
}
})
}
// * this.connectRetryCount
setTimeout(() => {
this.connect()
}, 1000 )
};
this.ws.onmessage = e => {
console.log('ws onmessage:' + e.data)
if (e.data.charAt(0) === "{") {
var msg = this.jsonToObj(e.data);
if(msg["CMD"]=='printerIsRead'){
printerIsRead=true;
}
else{
if(msg["CMD"]=='getPrinterList'){
this.innerGetPrinterList(msg)
if(this.onGetPrinterCallback.length>0){
this.onGetPrinterCallback.forEach(callback=>{
if(callback!=null){
callback();
}
})
}
}
else if(msg["CMD"]=='getPrintTplList'){
this.innerGetPrintTplList(msg)
if(this.onGetPrintTplCallback.length>0){
this.onGetPrintTplCallback.forEach(callback=>{
if(callback!=null){
callback();
}
})
}
}
else if(msg["CMD"]=='batchGetPDF'){
this.innerBatchGetPDF(msg)
}
// 通知其他客户端
// if (this.callbacks[msg["CMD"]]) {
// this.callbacks[msg["CMD"]](msg);
// }
}
} else {
// console.log("数据格式非法:" + e.data);
}
};
} catch (ex) {
// if (console && // console.log) {
// // console.log(ex);
// }
setTimeout(() => {
this.connect()
}, 1000 )
}
}
return this.ws;
}
innerGetPrinterList(msg){
// console.log("innerGetPrinterList")
this.isSendGetPrinter=true;
if(msg){
this.printerList=[];
// console.log(msg);
msg.Data.printerList.forEach(item=>{
let optionItem={
label:item,
value:item
}
this.printerList.push(optionItem);
this.defaultPrinter=msg.Data.defaultPrinter;
})
}
}
innerGetPrintTplList(msg){
// console.log("innerGetPrintTplList",msg)
this.isSendGetTpl=false;
if(msg){
this.printTplList=[];
msg.Data.tplList.forEach(item=>{
this.printTplList.push(item);
this.defaultTplCode=this.printTplList[0].tplCode;
})
}
}
async innerBatchGetPDF(msg){
// console.log("innerBatchGetPDF")
// 有出错,停止接收数据
if(msg.Status!='2'){
clearTimeout(this.recievePdfFileTimer);
if(this.onBatchGetPDFCallback){
await this.onBatchGetPDFCallback(500,msg.Data)
}
return;
}
if(this.recievePdfFileList.length<this.sendPdfFileListCount){
if(msg){
let ydSn=msg.Data.ydSn;
let tplCode=msg.Data.tplCode;
let key=ydSn+"-"+tplCode;
if(key in this.pdfFileReceiveMap){
// 文件已存在则返回
console.log(key+"-PDF文件已存在");
return;
}
this.recievePdfFileList.push(msg.Data);
this.pdfFileReceiveMap[key]=1;
if(this.onBatchGetPDFCallback!=null){
await this.onBatchGetPDFCallback(200,"获取成功",msg.Data);
}
}
}
console.log("===>this.recievePdfFileList.length==>",this.recievePdfFileList.length);
// console.log("===>this.sendPdfFileListCount==>",this.sendPdfFileListCount);
// 如果已相等则表示文件已接收完成
if(this.recievePdfFileList.length >= this.sendPdfFileListCount){
if(this.onBatchGetPDFCallback!=null){
// clearTimeout(this.recievePdfFileTimer);
// 把PDF文件传给终端处理
console.log("===>this.sendPdfFileListCount==>",this.sendPdfFileListCount);
this.onBatchGetPDFCallback(800,"获取成功");
// await this.onBatchGetPDFCallback(800,"获取成功",this.recievePdfFileList);
}
// 发送完成后数据清空
this.recievePdfFileList=[];
this.pdfFileReceiveMap=new Map()
// console.log("文件已接收完成");
return;
}
}
jsonToObj(json){
return JSON.parse(json)
}
objToJson(obj){
return JSON.stringify(obj)
}
/**
* readyState->0:尚未建立连接;1:已经建立连接;2:正在关闭;3:已经关闭或不可用
* @param thisWs
* @returns {*}
*/
getWSReadyState() {
if (this.ws.readyState !== undefined) {
return this.ws.readyState;
}
return this.WS_INIT;
};
// 发送数据的方法
send(data) {
console.log("send:"+data)
if (this.getWSReadyState() === this.WS_OPEN ) {
this.sendRetryCount = 0
this.ws.send(data)
return 1;
} else {
console.log("Ws is abnormal,send faild!!")
return -1
}
}
// 关闭socket连接
close() {
if (this.ws) {
this.ws.close();
this.connected = false; // 更新连接状态
// clearInterval(this.heartbeatInterval); // 清除心跳检测定时器
}
}
// 开启心跳检测
start() {
// this.heartbeatInterval = setInterval(() => {
// if (this.getWSReadyState() === this.WS_OPEN ) {
// // this.ws.ping();
// this.ws.send(0x9);
// }
// }, 1000);
}
}
export default TanexPrinterSdk;