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

export default (props) => {
  const {
    consultant,
    router,
    page,
    onCancel = (x => x),
  } = props;

  const [loading, setLoading] = useState(false)
  const { updatePhoneNumber } = useAuth(consultant, router, page)

  const handlePhoneNumber = (detail) => {
    const { errMsg, ...data } = detail || {}
    if (errMsg === 'getPhoneNumber:ok') {
      setLoading(true)
      updatePhoneNumber(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='getPhoneNumber'
      loading={loading}
      onGetPhoneNumber={handlePhoneNumber}
      onCancel={onCancel}
    >
      <View>请确认授权手机号，以便为您提供更优质的服务内容。</View>
    </AuthBox>
  )
}
