<template>
  <view class="w-body">
    <w-navbar left-back fixed :title="title"></w-navbar>
    <view style="display: flex; align-items: center; flex-direction: column; padding:2rem">
      <image style="width: 4rem; height: 4rem; margin-bottom: .5rem;" :src="$w.url('/logo.png')"/>
      <view style="margin-bottom: 2rem; width: 80vw;word-wrap:anywhere;">{{ $w.url('/logo.png') }}</view>
      <w-qr-code ref="qrCodeRef" style="--font-size: 20px;--color:var(--w-main)" size="512" :logo="$w.url('/logo.png')" level="H" color="#861a20" bg-color="#FFF" :text="text" @end="endHandler"/>
      <view style="margin: .5rem;">{{ text }}</view>
      <u-button @click="handleRepaint">重新生成二维码</u-button>
      <view style="height: .5rem;"></view>
      <!--#ifdef H5-->
      <u-button @click="handleSave">保存二维码</u-button>
      <!--#endif-->
      <!--#ifndef H5-->
      <u-button @click="handleSaveToPhotosAlbum">保存到相册</u-button>
      <!--#endif-->
    </view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance();

const title = ref("二维码");
const text = ref(`${Math.round(Math.random()*100000000)}${Math.round(Math.random()*100000000)}`);
const url = ref("");
const handleRepaint = ()=>{
  text.value = `${Math.round(Math.random()*100000000)}${Math.round(Math.random()*100000000)}`;
  proxy.$refs.qrCodeRef.repaint();
}
const endHandler = (imageUrl)=>{
  url.value=imageUrl
}

const handleSaveToPhotosAlbum = ()=>{
  uni.saveImageToPhotosAlbum({
    filePath:url.value,
    success(res){
      uni.$w.msg(res.path);
    },
    fail(){
      uni.$w.err('保存失败');
    }
  })
}

const handleSave = ()=>{
  var link = document.createElement('a');
  link.href = url.value;
  link.download = '二维码.png';
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

onLoad(e => {
  if (e.title) {
    title.value = e.title;
  }
  if (e.text) {
    text.value = e.text;
  }
})

const onPainted=()=>{
  ok.value=true;
}
const onMakeImged = ()=>{
  
}
</script>

<style lang="scss" scoped>
.w-body {
  --navbar-height: 44px
}
</style>
