<script lang='ts' setup>
import { toastController } from "@ionic/vue";

const router = useRouter();
const scanner = useTemplateRef<InstanceType<typeof QrScanner>>("scanner");

async function handleSuccess(value: string) {
  const toast = await toastController.create({
    message: "扫描成功",
    duration: 1000,
    position: "bottom",
    color: "success",
  });
  await toast.present();

  if (value.startsWith("/transfer_to_user/")) {
    // 完整路径
    router.replace(value);
  }
}

function handleError(error: Error) {
  toastController.create({
    message: `扫描失败: ${error.message}`,
    duration: 2000,
    position: "bottom",
    color: "danger",
  }).then(toast => toast.present());
}

function handleClose() {
  if (window.history.length > 1) {
    router.back();
  }
  else {
    router.replace("/");
  }
}

onMounted(() => {
  scanner.value?.start();
});

onBeforeRouteLeave(() => {
  scanner.value?.stop();
});
</script>

<template>
  <ion-page>
    <QrScanner ref="scanner" @success="handleSuccess" @error="handleError" @close="handleClose" />
  </ion-page>
</template>

<style lang='css' scoped></style>
