<template>
  <view>
    <uni-easyinput
      class="uni-mt-5"
      @blur="onInput"
      v-model="inputCodeValue"
      placeholder="请扫描或输入车辆编号"
      suffixIcon="scan"
      @iconClick="onScan"
    >
    </uni-easyinput>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { showModelMessage, getUrlParams } from "@/utils/tools.js";

const inputCodeValue = ref("");
const { codeValue } = defineProps(["codeValue"]);
inputCodeValue.value = codeValue;

const emit = defineEmits(["scan-change", "scan-empty"]);
const onScan = () => {
  uni.scanCode({
    onlyFromCamera: true, //只能扫码
    scanType: ["qrCode"],
    success: function (res) {
      const { result } = res;
      console.log("扫码结果", result);

      if (!result || result.indexOf("number") == -1) {
        showModelMessage("无效的车辆二维码");
        inputCodeValue.value = "";
        emit("scan-change", "");
      } else {
        const params = getUrlParams(result);
        inputCodeValue.value = params["number"];
        emit("scan-change", params["number"]);
      }
    },
  });
};
const onInput = (value) => {
  if (value.detail.value == "") return emit("scan-empty");
  inputCodeValue.value = value.detail.value;
  emit("scan-change", value.detail.value);
};

const onSetValue = (value) => {
  inputCodeValue.value = value;
};

const clearValue = () => {
  inputCodeValue.value = "";
};
defineExpose({
  onSetValue,
  clearValue,
});
</script>
<style></style>
