<route lang="json">
{ "style": { "navigationBarTitleText": "个人码", "navigationBarBackgroundColor": "#fff" } }
</route>
<script setup lang="ts">
import UQRCode from 'uqrcodejs'
import { getPointsOrder, storeAndPunchIn } from '../../../../core/libs/requests'
import { qrCodeString2Object, toQrCodeString } from '../../../../core/utils/common'
import { QrCodeBusinessType } from '../../../../core/libs/enums'
import { useUserStore } from '../../../../store'
import { storeToRefs } from 'pinia'
import { useRouter } from '@/core/utils/router'

const id = ref()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const router = useRouter()
const qrCodeCanvas = ref()
const { data, run: setData } = useRequest(() => getPointsOrder(id.value), { initialData: {} })

const a = async (canvasContext: UniApp.CanvasContext) => {
  const qr = new UQRCode()
  // 设置二维码内容
  // qr.data = data.value.orderNo
  //   qr.data = toQrCodeString('', {
  //     no: '',
  //   })
  //   qr.data = '12324'
  qr.data = toQrCodeString(QrCodeBusinessType.PagePath, {
    path: `/pages/mine/homepage/index?id=${userInfo.value?.userId}`,
  })
  // 设置二维码大小，必须与canvas设置的宽高一致
  qr.size = 200
  qr.foregroundImageSrc = userInfo.value?.avatar
  // console.log(userInfo.value?.avatar)
  // 调用制作二维码方法
  qr.make()
  qr.canvasContext = canvasContext
  // 调用绘制方法将二维码图案绘制到canvas上
  await qr.drawCanvas()
}
const generateCode = async () => {
  const currentInstance = getCurrentInstance()
  await nextTick(async () => {
    const canvasContext = uni.createCanvasContext('qrcode', currentInstance) // 如果是组件，this必须传入
    a(canvasContext)
  })
}
const generateCodeMp = async () => {
  const currentInstance = getCurrentInstance()
  await nextTick(() => {
    uni
      .createSelectorQuery()
      .in(currentInstance)
      .select('#qrcode')
      .fields({ node: true, size: true }, () => {})
      .exec((res) => {
        const canvas = res[0].node
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        const ctx = canvas.getContext('2d')
        ctx.scale(dpr, dpr)
        UQRCode.prototype.loadImage = (src: string) =>
          new Promise((resolve, reject) => {
            const img = canvas.createImage()
            img.src = src
            img.onload = () => {
              resolve(img)
            }
            img.onerror = (err) => {
              // reject返回错误信息
              reject(err)
            }
          })
        a(ctx)
        qrCodeCanvas.value = canvas
      })
  })
}

const handleClickScan = async () => {
  const { result } = await uni.scanCode({})
  console.log(result)
  // const a = qrCodeString2Object('WIFI:S:KM;T:WPA;P:km666888;H:false;;')
  // console.log(a)
  // console.log(toQrCodeString('到店', { a: 1, orderId: 2222 }))
  // console.log(qrCodeString2Object(toQrCodeString('到店', { a: 1, orderId: 2222 })))
  const { type, options } = qrCodeString2Object(result)
  // if (type === QrCodeBusinessType.InStoreClockIn) {
  //   if (!features.value.checkInAtStoreTask) return router.push('/pages/mine/authentication/index')
  //   try {
  //     await storeAndPunchIn({ id: options.id })
  //     // await storeAndPunchIn({ id: 24 })
  //     router.push(`/pages/mine/scan/result/index?result=${result}`)
  //   } catch (e) {
  //     if (e.code === 1000) {
  //       router.push(
  //         `/pages/mine/scan/result/index?result=${toQrCodeString(type, { name: options.name, desc: e.msg })}`,
  //       )
  //     } else {
  //       uni.showToast({ title: e.msg, icon: 'none' })
  //     }
  //   }
  //   return
  // }
  if (type === QrCodeBusinessType.PagePath) {
    await router.push(options.path)
    return
  }
  await router.push(`/pages/mine/scan/result/index?result=${result}`)
}
const saveQrcode = async () => {
  try {
    console.log(qrCodeCanvas.value)
    const option = {
      // #ifdef H5
      canvasId: 'qrcode',
      // #endif
      // #ifdef MP-WEIXIN
      canvas: toRaw(qrCodeCanvas.value),
      // #endif
    }
    console.log(option)
    const { tempFilePath } = await wx.canvasToTempFilePath(option)
    console.log(tempFilePath)
    await uni.saveImageToPhotosAlbum({
      filePath: tempFilePath,
    })
    await uni.showToast({ title: '保存成功' })
  } catch (e) {
    await uni.showToast({ title: '保存失败', icon: 'none' })
  }
}
onLoad(async (query: { id: string }) => {
  id.value = query.id
  // #ifdef MP-WEIXIN
  await generateCodeMp()
  // #endif
  // #ifdef H5
  await generateCode()
  // #endif
})
onReady(() => {})
</script>
<template>
  <div class="flex-grow flex flex-col items-center bg-white">
    <div class="flex-grow flex flex-col justify-center">
      <div>
        <!-- #ifdef MP-WEIXIN -->
        <canvas
          type="2d"
          id="qrcode"
          canvas-id="qrcode"
          style="width: 200px; height: 200px"
        ></canvas>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <canvas id="qrcode" canvas-id="qrcode" style="width: 200px; height: 200px"></canvas>
        <!-- #endif-->
      </div>
      <div
        class="text-center text-black/40 text-xs font-normal font-['PingFang_SC'] leading-normal my-3.5"
      >
        扫一扫上面的二维码，可查看我的主页
      </div>
    </div>
    <div class="w-full flex items-center justify-around my-10">
      <div
        @click="handleClickScan"
        class="text-center text-[#3f588f] text-base font-normal font-['PingFang_SC'] leading-normal"
      >
        扫一扫
      </div>
      <div
        class="text-center text-black/40 text-xs font-normal font-['PingFang_SC'] leading-normal"
      >
        |
      </div>
      <div
        class="text-center text-[#3f588f] text-base font-normal font-['PingFang_SC'] leading-normal"
        @click="saveQrcode"
      >
        保存图片
      </div>
    </div>
  </div>
</template>
