<template>
  <!-- 小票内容 -->
  <div ref="receipt" id="receipt" style="max-width: 200px">
    <h2>小票标题</h2>
    <p>商品名称: 商品1</p>
    <p>价格: ¥10.00</p>
    <p>数量: 1</p>
    <p>-------------------</p>
    <p>总计: ¥10.00</p>
    <p>-------------------</p>
  </div>
  <!-- <el-button type="priamry" @click="onPrint">打印</el-button> -->
  <el-button type="priamry" @click="printReceipt">打印</el-button>
</template>

<script setup>
import { ElMessage } from "element-plus";
import print from "print-js";
import { ref } from "vue";

const receipt = ref(null);
const onPrint = () => {
  console.log("开始打印", receipt);
  print({
    printable: "receipt",
    type: "html",
    maxWidth: "200",
  });
};

const printReceipt = () => {
  uni.getEnv((res) => {
    if(res.h5) ElMessage.error("请使用APP打印小票");
    else APPprint();
  });
};

const APPprint = () => {
  let str = "";
  str += "********************************\n";
  str += "泸优采-小票\n";
  str += "单号: CG171565043141139102\n";
  str += "测试商品1 * 1 \t 1.00元 \n";
  str += "测试商品2 * 1 \t 1.00元 \n";
  str += "测试商品小黄鸭3 * 1 \t 1.00元 \n";
  str += "\n";
  str += "--------------------------------\n";
  str += "\n";
  uni.postMessage({
    data: {
      type: "print",
      content: str,
    },
  });
};
</script>

<style lang="scss">
#receipt {
  padding: 10px;
  padding-bottom: 20px;
  font-size: 12px;
  border: 1px solid #ccc;
  width: 200px;
}
</style>
