<template>
  <el-row v-show="getShow" class="login-form" style="margin-right: -10px; margin-left: -10px">
    <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
      <img src="@/assets/imgs/screen/login-top.png" alt="logo" />
    </el-col>
    <el-col :span="24" style="padding-right: 10px; padding-left: 10px; margin-bottom:20px; text-align: center">
    
        <img width="320px" height="320px" :src="imageUrl" alt="Converted Image" v-if="imageUrl" />
    </el-col>
    <el-col :span="24" style="padding-right: 10px; padding-left: 10px; text-align: center">
      <img src="@/assets/imgs/screen/login-bottom.png" alt="logo" />
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import logoImg from '@/assets/imgs/logo.png'
import * as LoginApi from '@/api/login'
import * as authUtil from '@/utils/auth'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'
import router from '@/router'
defineOptions({ name: 'QrCodeForm' })

const imageUrl = ref('');
const uuuid =ref('')

const { t } = useI18n()
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => true)
// 存储定时器 ID，用于后续清除定时器
let intervalId = ref();


const getimg =async ()=>{

  const array = new Uint32Array(4);
  crypto.getRandomValues(array);
  let result = '';
  array.forEach((value) => {
    result += value.toString(16).padStart(8, '0');
  });
  uuuid.value = result;

 var mockBinaryData = await LoginApi.getCodeWebPic({
    scene:uuuid.value,
    path: 'sub/common/waiting',
    checkPath: false
  });
  // 对 Base64 编码的字符串进行解码
  const binaryString = atob(mockBinaryData);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }

  // 将二进制数据转换为Blob对象
  const blob = new Blob([bytes], { type: 'image/png' });
  // 创建临时的URL
  imageUrl.value = URL.createObjectURL(blob);

  //开始刷新扫码信息
  refaulst();
}
// 记录定时器开始的时间
const startTime = Date.now();
// 10 分钟的毫秒数
const tenMinutes =  60 * 1000; 
//定时刷新 判断是否扫码允许
const refaulst  = ()=>{
   // 先清除之前的定时器，避免重复调用
   if (intervalId) {
    clearInterval(intervalId.value);
  }
  // 设置定时器，每 5 秒（可根据实际需求调整）调用一次接口
  intervalId.value = setInterval(async () => {
    try {

      // 检查是否已经过去了 10 分钟
    if (Date.now() - startTime >= tenMinutes) {
      clearInterval(intervalId.value);
      console.log('定时器已停止，已过去 10 分钟。');
      return;
    }

      const res = await LoginApi.qrLoginCode({code:uuuid.value})
     
      if(res){
        clearInterval(intervalId.value);
				 authUtil.setToken(res)
          router.push({ path: '/' })
      }
      
    } catch (error) {
      console.error('获取扫码状态失败:', error);
    }
  }, 5000);
}
onMounted(() => {
  // getCookie()
  getimg()
})
</script>
