
<template>
  <span class="sc-scanner" style="display:inline-flex;align-items:center;gap:4px;vertical-align:middle;">
    <!-- 扫码枪(蓝牙/USB HID):聚焦后扫码即输入,回车触发。平板蓝牙枪、PC USB枪都走这里 -->
    <el-input
      ref="gunInput"
      v-model="gunValue"
      :placeholder="placeholder"
      clearable
      :style="{ width: gunWidth }"
      @keydown.enter.prevent="onGunScan"
    />
    <!-- 套壳App原生扫码(摄像头/激光):仅在检测到 window.Android 时显示,保留 gx 现有能力 -->
    <el-button v-if="hasAndroid" type="primary" @click="scanCode">{{ labeltext }}</el-button>
  </span>
</template>

<script>
export default {
  props: {
    labeltext: { type: String, default: "扫码" },
    placeholder: { type: String, default: "扫码枪扫描" },
    gunWidth: { type: String, default: "180px" },
  },
  data() {
    return {
      scannedResult: null, // 存储扫描到的二维码数据
      gunValue: "", // 扫码枪输入缓冲
      hasAndroid: !!window.Android, // 是否套壳App环境(有原生扫码)
    };
  },
  mounted() {
    window.onScanResult = this.onScanResult;
  },
  methods: {
    // 套壳App原生扫码(摄像头/激光)
    scanCode() {
      if (window.Android) {
        window.Android.openScanner();
      } else {
        alert("当前环境不支持原生扫码");
      }
    },
    // 扫码枪(键盘输入)扫描完成:枪扫完通常自动回车
    onGunScan() {
      let v = (this.gunValue || "").trim();
      this.gunValue = "";
      if (!v) return;
      if (/[一-龥]/.test(v)) {
        this.$message
          ? this.$message.error("扫码内容含中文,请切换英文输入法后重试")
          : alert("扫码内容含中文,请切换英文输入法后重试");
        return;
      }
      this.$emit("scanResult", v);
    },
    // 原生扫码回调(window.onScanResult)
    onScanResult(data) {
      this.scannedResult = data;
      this.$emit("scanResult", data);
      return data;
    },
  },
};
</script>
<style></style>
