import React, { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { useModel } from '@/store'
import Spin from '@/components/Spin'
import GetUserPhone from '@/components/GetUserPhone/index'
import GetUserIcon from '@/components/GetUserIcon/index'
import useMountTrack from '@/utils/hooks/useMountTrack'
import { getPage } from '@/utils'

const pages = require('../pages')

const showError = err => {
  Taro.showModal({
    title: '错误',
    content: err,
    showCancel: false
  })
}

export default function(props) {
  const [showAuthBasic, setShowAuthBasic] = useState(false)
  const [showAuthYeZhu, setShowAuthYeZhu] = useState(false)
  const [showAuthPhone, setShowAuthPhone] = useState(false)
  const { user } = useModel('user')

  const loading = !user || !user.personId
  const isAuthedBasic = user && user.avatarurl && user.nickname
  const isAuthedPhone = user && user.phone
  const isAuthedYeZhu = user

  const page = getPage()
  const needAuthBasic = (page.auth || []).indexOf('avatar') > -1
  const needAuthYeZhu = (page.auth || []).indexOf('yezhu') > -1
  const needAuthPhone = (page.auth || []).indexOf('phone') > -1
  
  // 埋点
  useMountTrack()

  // 授权手机
  useEffect(() => {
    if (!isAuthedPhone && needAuthPhone) {
      setShowAuthPhone(true)
    } else {
      setShowAuthPhone(false)
    }
  }, [isAuthedPhone, needAuthPhone])

  // 认证业主
  useEffect(() => {
    // 如果当前是认证业务页面
    if (page.isYeZhuRenZheng) {
      return
    }

    if (isAuthedPhone && !isAuthedYeZhu) {
      const renZhengPage = pages.filter(x => x.isYeZhuRenZheng)[0]
      if (renZhengPage) {
        // 跳转到业主认证页面
        // to = renZhengPage.page
      }
    }
  }, [needAuthYeZhu, isAuthedPhone, page])

  // 授权头像
  useEffect(() => {
    let needShow = false

    // 授权手机之后才授权头像
    if (isAuthedPhone) {
      // 要求业主认证的
      if (isAuthedYeZhu || !needAuthYeZhu) {
        if (!isAuthedBasic && needAuthBasic) {
          needShow = true
        }
      }
    }

    setShowAuthBasic(needShow)
  }, [isAuthedBasic, needAuthBasic, isAuthedPhone, isAuthedYeZhu, needAuthYeZhu])

  return (
    <Spin loading={loading}>
      <GetUserIcon visible={showAuthBasic} onError={err => showError(`授权头像失败: ${err}`)} />
      <GetUserPhone visible={showAuthPhone} onError={err => showError(`授权手机失败: ${err}`)} />
      { props.children }
    </Spin>
  )
}
