<template>
	<div>
		<div style="display: flex;flex-wrap: wrap;justify-content: space-evenly;">
			<button type="primary" @click="openDev" style="width:100px;height:50px;" :disabled="isOpen == true">连接打印机</button>
			<button type="primary" @click="closeConnect" style="width:100px;height:50px;" :disabled="isOpen == false">关闭连接</button>
			<button type="primary" @click="getPrinterStatus" style="width:100px;height:50px;" :disabled="isOpen == false">获取状态</button>
			<button type="primary" @click="printText" style="width:100px;height:50px;" :disabled="isOpen == false">文字打印</button>
			<button type="primary" @click="printBarCode" style="width:100px;height:50px;" :disabled="isOpen == false">打印条码</button>
			<button type="primary" @click="searchGap" style="width:100px;height:50px;" :disabled="isOpen == false">标签对齐</button>
			<button type="primary" @click="printTable" style="width:100px;height:50px;" :disabled="isOpen == false">打印表格</button>
			<button type="primary" @click="setSensitivity" style="width:100px;height:50px;" :disabled="isOpen == false">灵敏度</button>
			<button type="primary" @click="printSelfCheck" style="width:100px;height:50px;" :disabled="isOpen == false">打印自检页</button>
			<button type="primary" @click="setPaperFeed" style="width:100px;height:50px;" :disabled="isOpen == false">走纸</button>
			<button type="primary" @click="setPaperBack" style="width:100px;height:50px;" :disabled="isOpen == false">退纸</button>
			<button type="primary" @click="setDensity" style="width:100px;height:50px;" :disabled="isOpen == false">浓度设置</button>
			<button type="primary" @click="setPaperType(0)" style="width:100px;height:50px;" :disabled="isOpen == false">设置热敏纸</button>
			<button type="primary" @click="setPaperType(1)" style="width:100px;height:50px;" :disabled="isOpen == false">设置标签纸</button>
			<button type="primary" @click="sendBytesData" style="width:100px;height:50px;" :disabled="isOpen == false">发送测试</button>
			<button type="primary" @click="read" style="width:100px;height:50px;" :disabled="isOpen == false">读取测试</button>
			<button type="primary" @click="setFlowMode" style="width:100px;height:50px;" :disabled="isOpen == false">打开流控开关</button>
			<button type="primary"  style="width:100px;height:50px;opacity: 0;">占位</button>
		</div>

		<canvas canvas-id="myCanvas" style="width: 340px;height: 240px;"></canvas>

		<div style="height:50px;width:100px;">
			<button type="primary" @click="printImg" style="width:300px;height:50px;" :disabled="isOpen == false">打印图片</button>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad, onReady } from '@dcloudio/uni-app';
var printSDK = uni.requireNativePlugin("PrintSDK");
import QRCode from '@/static/uqrcode.es.js'; // 确保引入qrcode.js

// 响应式数据
const isOpen = ref(false);

// 画布相关
let canvasContext = null;

// 生命周期钩子 - 组件加载时
onLoad(() => {
  // 调用同步方法初始化程序和uhf
  /* console.log("开始初始化")
  uni.showToast({
    title: "开始初始化",
    icon: "none",
  });
  var ret = printSDK.initUHF()
  var initResult = ret.code == "0"? '初始化成功':'初始化失败';
  uni.showToast({
    title: initResult,
    icon: "none",
  }); */
});

// 生命周期钩子 - 组件DOM已更新
onReady(() => {
  drawCanvas();
});

// 生命周期钩子 - 组件挂载后
onMounted(() => {
  // 注册全局事件监听
  plus.globalEvent.addEventListener('sendMessage', function(e) {
    if (e.tag == "getPrinterStatus") {
      // 打印机状态返回值
      uni.showToast({
        title: "sendMessage收到：" + JSON.stringify(e.msg),
        icon: "none",
      });
    } else if (e.tag == "initPrint") {
      // 连接和关闭打印机时返回的信息
      uni.showToast({
        title: "sendMessage收到：" + JSON.stringify(e.msg),
        icon: "none",
      });
    } else if (e.tag = "read") {
      // read函数返回的读取到的打印机信息的函数
      uni.showToast({
        title: "sendMessage收到：" + JSON.stringify(e.msg),
        icon: "none",
      });
    }
  });
});


// 绘制画布表格+二维码
const drawCanvas = () => {
  canvasContext = uni.createCanvasContext('myCanvas');
  console.log(canvasContext)
  canvasContext.fillStyle = 'white'; // 设置填充颜色为红色
  canvasContext.fillRect(0, 0, 340, 240); // 填充整个画板
  drawTable(canvasContext);
  drawText(canvasContext);
  drawQRCode(canvasContext);
  canvasContext.draw(true); // 异步绘制，false表示绘制完成后不返回绘图结果
};

// 绘制文本
const drawText = (ctx) => {
  ctx.setFontSize(25);
  ctx.fillText('绘制测试页XX公司', 70, 40);
};

// 绘制二维码
const drawQRCode = (ctx) => {
  // 使用uQRCode.js生成二维码
  var qr = new QRCode('myCanvas', {
    width: 70,
    height: 70,
    colorDark: "#000000",
    colorLight: "#ffffff"
  });
  qr.data = "123";
  qr.size = 70;
  qr.make();
  qr.canvasContext = ctx;

  ctx.save();
  // 平移画布到 (245, 115) 位置
  ctx.translate(245, 115);
  // 在平移后的位置绘制二维码
  qr.drawCanvas();
  // 恢复之前保存的画布上下文
  ctx.restore();
};

// 绘制表格
const drawTable = (ctx) => {
  // 绘制表格数据
  ctx.moveTo(10, 1);
  ctx.lineTo(320, 1);
  ctx.moveTo(10, 70);
  ctx.lineTo(320, 70);
  ctx.setFontSize(20);
  ctx.setFillStyle('#000000');
  ctx.fillText('物料编号: 134588788-1', 20, 100);
  ctx.moveTo(10, 110)
  ctx.lineTo(320, 110);
  ctx.fillText('物料名称: 连接杆', 20, 140);
  ctx.moveTo(10, 150)
  ctx.lineTo(240, 150);

  ctx.moveTo(240, 110);
  ctx.lineTo(240, 190);

  ctx.fillText('批次: H28228618', 20, 180);
  ctx.moveTo(10, 190)
  ctx.lineTo(320, 190);
  ctx.fillText('数量(QTY): 1', 20, 220);
  ctx.moveTo(10, 230)
  ctx.lineTo(320, 230);
  ctx.setFontSize(25);
  // ctx.fillText('标记问题件', 100, 275);
  // ctx.moveTo(10, 285)
  // ctx.lineTo(320, 285);

  // 左边外边框
  ctx.moveTo(10, 0)
  ctx.lineTo(10, 230);
  // 右边外边框
  ctx.moveTo(320, 0)
  ctx.lineTo(320, 230);
  ctx.setStrokeStyle('red')
  ctx.stroke()
};

// 流控开关
const setFlowMode = () => {
  let a = printSDK.sendBytesData("1F111F2C371F1F")
  console.log(a)
  uni.showToast({
    title: "流控开关已打开",
    icon: "none",
  });
};

// 连接打印机
const openDev = () => {
  console.log("ret", printSDK);
  var ret = printSDK.connectPrinter()
  var openResult = ret.code == "0" ? '连接成功' : '连接失败';
  if (ret.code == "0") {
    isOpen.value = true
  }
  uni.showToast({
    title: openResult,
    icon: "none",
  });
  var ret = printSDK.initPrint();
  if (ret.code != '0') {
    uni.showToast({
      title: "打印机初始化失败",
      icon: "none",
    });
  }
};

// 下电
const closeConnect = () => {
  var ret = printSDK.closeConnect()
  var closeResult = ret.code == "0" ? '成功' : '失败';
  if (ret.code == "0") {
    isOpen.value = false
  }
  uni.showToast({
    title: closeResult,
    icon: "none",
  });
};

// 打印文字测试
const printText = () => {
  var ret = printSDK.initPrint();
  if (ret.code != '0') {
    uni.showToast({
      title: "打印机初始化失败",
      icon: "none",
    });
  } else {
    printSDK.setFont(0, 1, 1, 0, 0);
    printSDK.setPrinter(2, 1);
    var ret = printSDK.printText("打印文字测试\r\n");
    if (ret.code != '0') {
      uni.showToast({
        title: "函数执行失败",
        icon: "none",
      });
    } else {
      uni.showToast({
        title: "函数执行成功",
        icon: "none",
      });
      printSDK.setFont(0, 0, 0, 0, 0);
      printSDK.setPrinter(2, 0);
      var ret = printSDK.printText("打印文字测试\r\n");
    }
  }
};

const printBarCode = () => {
  var ret = printSDK.initPrint();
  if (ret.code != '0') {
    uni.showToast({
      title: "打印机初始化失败",
      icon: "none",
    });
  } else {
    var type = [73, 4, 6, 5, 72, 3, 102]
    for (var i = 0; i < type.length; i++) {
      printSDK.setPrinter(1, 2);
      if (type[i] == 102) {
        var ret = printSDK.printBarCode(type[i], 2, 3, 6, "123456");
      } else {
        var ret = printSDK.printBarCode(type[i], 2, 162, 2, "0123456789");
      }
      printSDK.setPrinter(1, 3);
      printSDK.setPrinter(2, 0);
      if (ret.code == '0') {
        uni.showToast({
          title: "函数执行失败",
          icon: "none",
        });
      }
    }
  }
};

// 保存图片并打印
const saveImage = (picData) => {
  uni.saveImageToPhotosAlbum({
    filePath: picData,
    success(result) {
      uni.showToast({
        title: "开始打印图片",
        icon: "none",
      });
      var destPic = result.file;

      var ret = printSDK.initPrint();
      if (ret.code != '0') {
        uni.showToast({
          title: "打印机初始化失败",
          icon: "none",
        });
      } else {
        printSDK.printText("\n");
        printSDK.setPrinter(1, 1);
        var path = result.path;
        getImageSize(path);
        uni.showToast({
          title: "打印路径：" + path,
          icon: "none",
        });
        console.log(path);
        ret = printSDK.printImage(result.file, 3, 0, false);
        // printSDK.setPaperFeed(50)
        if (ret.code == "0") {
          uni.showToast({
            title: "函数执行成功",
            icon: "none",
          });
          printSDK.searchGap()
        } else {
          uni.showToast({
            title: "函数执行失败",
            icon: "none",
          });
        }
      }
    },
    fail() {
      uni.hideLoading()
      uni.showModal({
        content: '检测到您没打开获取信息功能权限，是否去设置打开？',
        confirmText: "确认",
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            uni.openSetting({
              success: (res) => {
                console.log(res);
                uni.showToast({
                  title: "请重新打印图片",
                  icon: "none"
                });
              }
            })
          } else {
            uni.showToast({
              title: "保存失败，请打开权限功能重试",
              icon: "none"
            });
          }
        }
      })
    }
  })
};

// 获取图片尺寸
const getImageSize = (filePath) => {
  // 使用 uni.getImageInfo 获取图片的元数据，包括尺寸信息
  uni.getImageInfo({
    src: filePath,
    success: (imageInfo) => {
      console.log('图片宽度:', imageInfo.width);
      console.log('图片高度:', imageInfo.height);
    },
    fail: (err) => {
      console.error('获取图片信息失败', err);
    }
  });
};

// 打印图片
const printImg = () => {
  for (let index = 0; index < 5; index++) {
    printSDK.setPaperBack(2)
  }
  // uni.showToast({
  //   title: "函数执行成功",
  //   icon: "none",
  // });
  // canvas保存成临时图片
  uni.canvasToTempFilePath({
    width: 350,
    height: 600,
    canvasId: 'myCanvas',
    success: function(res) {
      console.log(res.tempFilePath)
      var picData = res.tempFilePath
      // 后台直接打印图片
      saveImage(picData);
    }
  })
};

// 打印表格
const printTable = () => {
  var column = "品名;数量;单价;金额";
  var regularExpression = ";";
  var columnWidth = "14,6,6,6"; //逗号分隔字符串，不要调整格式，逗号和数字之间不要加空格！！！！！！！！！！！！！！
  var rows = ["保鲜袋;10.00;1;10.00", "铁丝挂钩;5.00;2;10.00", "雨伞;5.00;3;15.00"];
  var ret = printSDK.printTable(column, regularExpression, columnWidth, rows);
  if (ret.code == "0") {
    uni.showToast({
      title: "函数执行成功!",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  }
};

// 打印自检页
const printSelfCheck = () => {
  var ret = printSDK.printSelfCheck();
  if (ret.code == "0") {
    uni.showToast({
      title: "函数执行成功",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  }
};

// 走纸
const setPaperFeed = () => {
  var ret = printSDK.setPaperFeed(2);
  if (ret.code == "0") {
    uni.showToast({
      title: "函数执行成功",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  }
};

// 退纸
const setPaperBack = () => {
  var ret = printSDK.setPaperBack(2);
  if (ret.code == "0") {
    uni.showToast({
      title: "函数执行成功",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  }
};

// 获取打印机状态
const getPrinterStatus = () => {
  var ret = printSDK.getPrinterStatus();
  if (ret.code == "0") {
    uni.showToast({
      title: "正常",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  } else {
    uni.showToast({
      title: ret.code,
      icon: "none",
    });
  }
};

// 标签对齐
const searchGap = () => {
  var ret = printSDK.searchGap();
  if (ret.code == "0") {
    uni.showToast({
      title: "函数执行成功",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  }
};

// 设置灵敏度
const setSensitivity = () => {
  var ret = printSDK.setSensitivity(10);
  if (ret.code == "0") {
    uni.showToast({
      title: "函数执行成功",
      icon: "none",
    });
  } else if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  }
};

// 设置浓度
const setDensity = () => {
  var ret = printSDK.setDensity(0);
  if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  } else {
    uni.showToast({
      title: ret.code,
      icon: "none",
    });
  }
};

// 设置纸张类型
const setPaperType = (type) => {
  var ret = printSDK.setPaperType(type)
  if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  } else {
    uni.showToast({
      title: ret.code,
      icon: "none",
    });
  }
};

// 发送测试
const sendBytesData = () => {
  var ret = printSDK.sendBytesData("1b3300")
  if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  } else {
    uni.showToast({
      title: ret.code,
      icon: "none",
    });
  }
};

// 读取测试
const read = () => {
  var ret = printSDK.read()
  if (ret.code == "-999") {
    uni.showToast({
      title: "打印机未连接",
      icon: "none",
    });
  } else if (ret.code == "999") {
    uni.showToast({
      title: "打印机未初始化",
      icon: "none",
    });
  } else {
    uni.showToast({
      title: ret.code,
      icon: "none",
    });
  }
};
</script>

<style scoped lang="scss">
  uni-button{
    margin: 0;
    margin-bottom: 30rpx;
  }
	canvas {
		/* border: 1px solid #000; */
	}
</style>