<template>
  <view>
    <view class="scan-tip">将CODE_128类型的条码放入框内，即可自动扫描</view>
    <view class="scan-box" ref="scanBox"></view>
  </view>
</template>

<script>
export default {
  onLoad() {
    this.initScan();
  },
  methods: {
    initScan() {
      // 获取扫码框位置信息
      var scanBoxRect = uni.createSelectorQuery().in(this).select(".scan-box").boundingClientRect((data) => {
        // 调用uni.scanCode方法进行扫码，并设置扫码框的位置和大小
        uni.scanCode({
          scanType: ['barCode'], // 只识别CODE_128类型的码
          success: (res) => {
            if (res.scanType === 'CODE_128') {
              console.log(res.result);
              // 处理扫描结果
            } else {
              uni.showToast({
                title: '请扫描CODE_128类型的码',
                icon: 'none'
              });
              this.resetScanBox(data); // 重新扫码
            }
          },
          fail: (res) => {
            console.log(res.errMsg);
          },
          complete: () => {
            // 扫码完成后重置扫描框位置和大小
            this.resetScanBox(data);
          }
        });
      }).exec();
    },
    resetScanBox(data) {
      // 重置扫描框位置和大小
      this.$refs.scanBox.style.width = data.width + "px";
      this.$refs.scanBox.style.height = data.height + "px";
      this.$refs.scanBox.style.top = data.top + "px";
      this.$refs.scanBox.style.left = data.left + "px";
    }
  }
}
</script>

<style>
.scan-tip {
  margin-top: 20px;
  text-align: center;
}

.scan-box {
  position: fixed;
  width: 200px;
  height: 200px;
  margin: 0 auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 2px solid #fff;
  box-shadow: 0px 0px 10px #000;
}
</style>
