import { useState, useEffect } from 'react'
import { Image } from '@tarojs/components'
import withLayout from '@/layout'
import { fetch } from '@/utils/request'
import { API_QRCODE } from '@/constants/api'
import { getImgURL, save2Album } from '@/utils/image'
import Taro from '@tarojs/taro'
import '@/assets/css/iconfont.css'
import './index.scss'

export default withLayout((props) => {

  const { person, page } = props
  const [QrCodeUrl, setQrCodeUrl] = useState(null)

  useEffect(() => {
    const payload = {
      scene: `id=${person?.personId}&from=${page.type}_share&recommender=${person?.personId}`,
      page: `pages/mine/myRecommendCode/index`
    }
    fetch({ url: API_QRCODE, payload, method: 'post' }).then((res) => {
      setQrCodeUrl(res)
    })
  }, [])

  const Save = () => {
    Taro.downloadFile({
      url: QrCodeUrl,
      success: function(res) {
        save2Album(res.tempFilePath).then(() => {
          Taro.showToast({ title: '保存成功', icon: 'none' })
        })
      },
      fail: function(err) {
        console.error(err)
        Taro.showToast({
          title: '操作失败, 您可以试试预览保存',
          icon: 'none'
        })
      }
    })
  }

  const PreviewImage = () => {
    Taro.previewImage({
      current: QrCodeUrl,
      urls: [QrCodeUrl],
      showmenu: true,
    })
  }

  return (
    <view className='Page myRecommendCode'>
      <view className='CodeContent'>
        <view>
          <view className='flex-h'>
            <view className='Icon'>
              <Image mode='scaleToFill' src={getImgURL(person?.userPhoto || person?.avatarurl)}></Image>
            </view>
            <text>{person?.name}</text>
          </view>
          <Image mode='widthFix' src={QrCodeUrl} onClick={PreviewImage}></Image>
          <text>扫一扫上面的二维码图案,成为我的客户</text>
        </view>
      </view>
      <view className='Btn'>
        <text onClick={Save}>保存到手机</text>
      </view>
    </view>
  )
})
