import React, { useState } from 'react'
import Taro from '@tarojs/taro'
import { View, OpenData } from '@tarojs/components'
import AuthBox from './AuthBox'
import useAuth from './useAuth'
import './style.scss'

export default (props) => {
  const { onCancel = (x => x) } = props;

  const [loading, setLoading] = useState(false)
  const { updateUserInfo } = useAuth()

  const handleUserProfile = (detail) => {
    const { errMsg, ...data } = detail || {}
    if (errMsg === 'getUserProfile:ok') {
      setLoading(true)
      updateUserInfo(data).then(() => {
        setLoading(false)
      }).catch((err) => {
        console.error(err)
        setLoading(false)
      })
    } else {
      console.error(errMsg);
      Taro.showToast({
        title: '授权头像失败',
        icon: 'none',
        duration: 2000
      })
    }
  }

  return (
    <AuthBox
      title='授权头像'
      openType='getUserInfo'
      loading={loading}
      onGetUserInfo={handleUserProfile}
      onCancel={onCancel}
    >
      <View className='auth-avatar'>
        <OpenData type='userAvatarUrl' />
      </View>
      <View className='auth-nickname'>
        <OpenData type='userNickName' />
      </View>
    </AuthBox>
  )
}
