import {
  closeToast,
  Image,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
  showToast
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import content1 from './images/content1.png'
import content2 from './images/content2.png'
import qrcode from './images/qrcode.jpg'
import html2canvas from 'html2canvas'
import { promisefiyPostMessage, postMessage } from '@/helpers/native-message'

export default defineComponent({
  name: 'follow-account',
  setup() {
    const imgs = reactive({
      saveLoading: false,
      image: null as any,
      shareLoading: false
    })
    const onSaveImg = async () => {
      // 判断是否在保存中...
      if (imgs.saveLoading) {
        return
      }
      imgs.saveLoading = true
      // 判断是否已经生成图片
      if (imgs.image) {
        saveImg()
      } else {
        const container: any = document.getElementById(`preview-container`)
        html2canvas(container, {
          allowTaint: true,
          useCORS: true,
          backgroundColor: null
        })
          .then(async (canvas) => {
            const url = canvas.toDataURL('image/png')
            imgs.image = url
            saveImg()
          })
          .catch(() => {
            closeToast()
            imgs.saveLoading = false
          })
      }
    }

    const saveImg = async () => {
      showLoadingToast({ message: '图片生成中...', forbidClick: true })
      setTimeout(() => {
        imgs.saveLoading = false
      }, 100)
      const res = await promisefiyPostMessage({
        api: 'savePicture',
        content: {
          base64: imgs.image
        }
      })
      if (res?.content?.status === 'success') {
        showSuccessToast('保存成功')
      } else {
        showFailToast('保存失败')
      }
    }

    onMounted(() => {
      postMessage({ api: 'setBarStatus', content: { status: 0 } })
    })
    return () => (
      <div class={styles.followAccount}>
        <Image src={content1} class={styles.content1} />
        <Image src={content2} class={styles.content2} />

        <div class={styles.saveQrcode} onClick={onSaveImg}></div>

        <div id="preview-container" class={styles.followQrcode}>
          <Image src={qrcode} />
        </div>
      </div>
    )
  }
})
