import Taro, { Component } from '@tarojs/taro'
import './index.scss'
import { updatePhoto } from '@/services/card'
import { connect } from '@tarojs/redux'

@connect(
  ({ user }) => ({ ...user })
)

export default class Panorama extends Component {
  state = {
    avatarImg: ''
  }

  // 选择图片
  bindAlbumClick(e) {

    e.stopPropagation()

    Taro.showLoading({
      title: '加载中',
    })
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        uploadFiles(res.tempFilePaths).then(data => {
          this.setState({
            avatarImg: data[0]
          })
        })
      },
      complete: res => {
        Taro.hideLoading()
      }
    })
  }
  saveBtn() {
    const { avatarImg } = this.state
    const photoUrl = this.$router.params.photoUrl || avatarImg
    const { userInfo: { person: { personId } } } = this.props
    updatePhoto({ photoUrl }).then(res => {
      Taro.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        Taro.redirectTo({ url: `/pages/card/index?id=${personId}&loadInfo=need` })
      }, 800)

    })
  }

  render() {

    const { avatarImg } = this.state
    const photoUrl = this.$router.params.photoUrl || avatarImg

    return (
      <View className="avatar-pop">
        <Image src={photoUrl} className='avatar-img' onClick={this.bindAlbumClick} mode="aspectFill"></Image>
        <Button className="save-btn" onClick={this.saveBtn}>保存</Button>
      </View>

    )
  }
}
