<template>
  <nut-signature @confirm="confirm" @clear="clear"></nut-signature>
  <image mode="widthFix" v-if="imgData" :src="imgData" style="width: 100%"></image>
</template>
<script setup lang="ts">
import { useDailyStore } from '@/store/daily'
const store = useDailyStore()
import Taro, { useLoad } from '@tarojs/taro'
import { ref, computed } from 'vue'
const base64_1 = computed(() => store.get_base64_1)
const base64_2 = computed(() => store.get_base64_2)

const _index = ref(0)
useLoad((options) => {
  console.log(options)
  _index.value = Number(options.index)
  if (_index.value === 1) {
    imgData.value = base64_1.value
  } else {
    imgData.value = base64_2.value
  }
})
const imgData = ref('')
const convertToBase64 = (imgUrl: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    const fs = Taro.getFileSystemManager()
    fs.readFile({
      filePath: imgUrl, // 本地路径
      encoding: 'base64',
      success(res) {
        // resolve({})
        resolve('data:image/png;base64,' + res.data) // 前缀加上 image 类型，适应 img 标签
      },
      fail(err) {
        reject(err)
      },
    })
  })
}
const confirm = async (canvas: any, data: string) => {
  if (data) {
    console.log('imgData', canvas, data)
    try {
      const base64Image = await convertToBase64(data)
      if (_index.value === 1) {
        // imgData.value = base64Image
        store.change_base64_1(base64Image)
        Taro.navigateBack({ delta: 1 })
      } else {
        // imgData.value = base64Image
        store.change_base64_2(base64Image)
        Taro.navigateBack({ delta: 1 })
      }
      // console.log('Base64 Image:', base64Image)
    } catch (error) {
      console.error('Failed to convert image to Base64:', error)
    }
  }
}
const clear = () => {
  imgData.value = ''
  console.log('clear')
}
</script>
