<template>
  <div class="w-[100vw] relative h-[100vh]">
    <template v-if="show">
      <div
        style="z-index: 1000; justify-content: space-between"
        class="absolute w-full flex h-24 justify-between items-center top-0 pt-12 px-16 left-0"
      >
        <span
          @click="router.back()"
          :class="`iconfont  icon-left text-white `"
          style="font-size: 24px"
        ></span>
        <h1 class="text-white font-semibold text-base">扫描二维码</h1>
        <div></div>
      </div>
      <div id="qr-reader" class="w-full h-full"></div>

      <div class="w-54 absolute bottom-75 left-1/2 -translate-x-1/2">
        <div class="w-54 h-54 rounded-full mb-6 bg-black text-center">
          <span :class="`iconfont  icon-pic text-white `" style="font-size: 32px"></span>
        </div>
        <p @click="stopScan" class="text-[13px] text-white text-center">相册</p>
      </div>
    </template>

    <div v-if="!show">
      <div
        style="z-index: 1000; justify-content: space-between"
        class="absolute w-full flex h-24 justify-between items-center top-0 pt-12 px-16 left-0"
      >
        <span
          @click="router.back()"
          :class="`iconfont  icon-left text-black `"
          style="font-size: 24px"
        ></span>
        <h1 class="text-black font-semibold text-base">扫码结果</h1>
        <div></div>
      </div>
      <ChatEmpty image="search" title="无法识别二维码" />
    </div>

    <!-- <div id="qr-reader-results" class="absolute bottom-75">
      {{ results }}
    </div> -->
  </div>
</template>
<script setup>
import { Html5QrcodeScanner, Html5Qrcode, Html5QrcodeScanType } from 'html5-qrcode'
const router = useRouter()

const show = ref(true)
let results = ref(null)
const state = reactive({
  html5QrCode: null,
  fileList: []
})

definePageMeta({
  layout: false
})

useSeoMeta({
  title: '我的消息'
})

onMounted(() => {
  handleQrcode()
})

const handleQrcode = () => {
  Html5Qrcode.getCameras()
    .then((devices) => {
      if (devices && devices.length) {
        // 当前环境下能识别出摄像头，并且摄像头的数据可能不止一个
        state.html5QrCode = new Html5Qrcode('qr-reader') //  reader  放置扫码功能的元素ID
        // alert('摄像头识别成功')
        state.html5QrCode.start(
          //  environment后置摄像头 user前置摄像头
          {
            facingMode: 'environment'
          },

          {
            fps: 1, // 可选，每n秒帧扫描一次
            qrbox: {
              width: 250,
              height: 250
            }, // 扫描的UI框
            videoConstraints: {
              width: 375,
              aspectRatio: 16 / 9
              // echoCancellation: true,
            }
          },
          (decodedText, decodedResult) => {
            let groupId
            if (decodedText) {
              groupId = decodedText.split('?')[1].split('=')[1].split('&')[0]

              // 扫描结果
              results.value = {
                decodedText,
                decodedResult,
                groupId
              }

              scanQRCode()
            } else {
              // show.value = false
            }
            stopScan()
            // scanQRCode()
            console.log(results.value)
          }
          // (errorMessage) => {
          //   // 错误回调
          //   console.warn(`扫码错误：${errorMessage}`)
          // }
        )
      }
    })
    .catch((err) => {
      // console.error(`启动扫码失败: ${err}`)
      // 摄像头无访问权限
    })
}

const stopScan = () => {
  state.html5QrCode
    .stop()
    .then((a) => {
      console.log('已停止扫码', a)
    })
    .catch((err) => {
      console.log(err)
      showToast('停止失败')
    })
}

// 读码
async function scanQRCode() {
  navigateTo({
    path: '/chat/qr-results',
    query: {
      groupId: results.value.groupId
    },
    replace: true
  })
}
</script>
<style scoped lang="scss">
// /* 使视频全屏适配 */
video {
  width: 100%;
  height: 100vh;
  object-fit: cover; /* 保持宽高比，填充整个屏幕 */
}
</style>
