import React, { useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Image, Button } from '@tarojs/components'
import Spin2 from '@/components/Spin/Spin2'
import { save2Album } from '@/utils/image'
import Poster from './Poster'
import './style.scss'

export default (props) => {
  const {
    show,
    dataSource,
    onClose,
    onSuccess,
    title = '保存后分享图片',
    btnText = '保存海报至相册',
  } = props

  const [img, setImg] = useState()
  const [processing, setProcessing] = useState(false)
  const [loading, setLoading] = useState(false)
  const sdkRef = useRef()

  const handlePoster = (url, sdk) => {
    setImg(url)
    setProcessing(false)
    sdkRef.current = sdk
  }

  const handleSave = () => {
    if (!img) {
      Taro.showToast({
        title: '海报未生成, 请稍后',
        icon: 'none',
      })
      return
    }

    // 保存到相册
    setLoading(true)
    sdkRef.current.download().then((tempPath) => {
      save2Album(tempPath).then(() => {
        setLoading(false)
        onSuccess()
        Taro.showToast({ title: '保存成功', icon: 'none' })
      }, () => setLoading(false))
    }).catch((err) => {
      setLoading(false)
      console.error(err)
      const message = err.errMsg || err.message || err
      Taro.showToast({
        title: message,
        icon: 'none',
      })
    })
  }

  const handleImage = (e) => {
    Taro.previewImage({ current: img, urls: [img], showmenu: true })
  }

  return (
    // <Modal title={title} visible={show} onClose={onClose}>
    // eslint-disable-next-line react/jsx-no-undef
    <page-modal show={show} position='bottom' onClose={onClose} height='70vh'>
      <View className='modal-poster'>
        <View className='modal-poster-img-box'>
          <view>
            {
              !processing
                ? <Image src={img} mode='scaleToFill' className='centerLabel' onClick={handleImage} />
                : <Spin2 className='centerLabel' spinning={processing} size={32} />
            }
          </view>
        </View>
        <Button className='modal-poster-action' onClick={handleSave} disabled={!img} loading={loading}>
          {btnText}
        </Button>
      </View>
      <Poster dataSource={dataSource} onStart={() => setProcessing(true)} onEnd={handlePoster} />
    </page-modal>
  )
}
