import {
  closeToast,
  Icon,
  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'
import OHeader from '@/components/o-header'
import { browser } from '@/helpers/utils'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'follow-account',
  setup() {
    const router = useRouter()
    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('保存失败')
      }
    }

    const onBack = () => {
      if (browser().isApp) {
        postMessage({ api: 'goBack' })
      } else {
        router.back()
      }
    }

    return () => (
      <>
        <div class={styles.followAccount}>
          <OHeader
            background="transparent"
            style="position: fixed; width: 100%;z-index: 999;top: 0;left: 0;"
          >
            {{
              content: () => (
                <div class={styles.btnHeader} onClick={onBack}>
                  <Icon name="arrow-left" class={styles.iconBack} />
                </div>
              )
            }}
          </OHeader>
          <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>
      </>
    )
  }
})
