import React, { useState, useEffect } from 'react'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { useSelector } from 'react-redux'
import { View } from '@tarojs/components'
import Overlay from '@/components/Overlay'
import Loading from '@/components/Loading'
import AuthAvatar from '@/components/Auth/AuthAvatar'
import AuthPhone from '@/components/Auth/AuthPhone'
import AuthPage from '@/components/Auth/AuthPage'
import Spin from '@/components/Spin/Spin2'
import FixedConsultant from '@/components/FixedConsultant'
import ShareToCircle from '@/components/ShareToCircle'
import { report as reportCustomer } from '@/utils/customer'
import { ROLE_CODE } from '@/constants/user'
import useAuth from './useAuth'
import useFixedRouter from './useFixedRouter'
import { routes } from '../routes'

import './style.scss'

export default (ChildComponent) => (props) => {
  const mode = Taro.getStorageSync('mode')
  const isSinglePage = mode === 'singlePage'

  const consultant = useSelector(s => s.system.consultant)
  const city = useSelector(s => s.city.curCity)
  const { spinning, userInfo } = useSelector(s => s.user)
  const { person, ...extInfo } = userInfo || {}
  const router = useFixedRouter()
  const page = routes.filter((r) => (router.path.indexOf(r.page) > -1))[0]
  const [loading, setLoading] = useState(false)
  const [authPhone, authAvatar, authPage] = useAuth(person, page)
  const [shareTimelineVisible, setShareTimelineVisible] = useState(false)

  const { id, scene, qrInited } = router.params

  const showConsultant = page.shortcut && page.shortcut.consultant

  // 页面分享
  const [shareContent, setShareContent] = useState({})
  // 页面埋点
  const [trackData, setTrackData] = useState({})

  // 分享朋友圈提示
  const showShareTimeline = (visible) => setShareTimelineVisible(visible)

  // 设置当前页标题
  const setNavigationBarTitle = title => {
    if (!title) return;

    Taro.nextTick(() => {
      Taro.setNavigationBarTitle({ title })
    })
  }

  // 报备客户
  useEffect(() => {
    if (isSinglePage) return;

    reportCustomer(person, consultant, false).catch(() => {})
  }, [person, consultant, isSinglePage])

  // 请求埋点设置
  useEffect(() => {
    if (isSinglePage) return;

    if (id) {
      setShareContent({})
    }
  } ,[id, page.type, isSinglePage])

  // 埋点数据
  useEffect(() => {
    if (isSinglePage) return;

    const consultantId = person?.personType === ROLE_CODE.CONSULTANT ? person.personId : undefined

    setTrackData({
      eventType: page.type,
      propertyName: page.name,
      consultantId,
      sharePersonId: person?.personId,
      targetId: id,
    })
  }, [person, page, id, isSinglePage])

  // 主要用于埋点
  useEffect(() => {
    Taro.setStorage({ key: 'page', data: page })
  }, [page])

  useEffect(() => {
    setLoading((!person || !person.personId) || (scene && !qrInited))
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [person, scene, qrInited])

  return (
    <>
      {/* 菊花转 */}
      <Overlay visible={loading} style={{background: '#fff'}}>
        <Loading />
      </Overlay>

      {/* 授权手机 */}
      <Overlay visible={authPhone && !isSinglePage} aligin='bottom'>
        <View className='auth-wrapper'>
          <AuthPhone consultant={consultant} router={router} page={page} />
        </View>
      </Overlay>

      {/* 授权头像 */}
      <Overlay visible={!authPhone && authAvatar && !isSinglePage} aligin='bottom'>
        <View className='auth-wrapper'>
          <AuthAvatar />
        </View>
      </Overlay>

      {/* 授权头像-全屏 */}
      { authPage && !isSinglePage && <AuthPage consultant={consultant} router={router} page={page} /> }

      {/* 显示分享朋友圈 */}
      <ShareToCircle visible={shareTimelineVisible && !isSinglePage} onClose={() => setShareTimelineVisible(false)} />

      {/* 页面内容 */}
      <Spin size={32} spinning={spinning} />
      {
        person && !!person.personId && (
          <ChildComponent
            person={person}
            router={router}
            consultant={consultant}
            page={page}
            city={city}
            mode={mode}
            shareContent={shareContent}
            trackData={trackData}
            showShareTimeline={showShareTimeline}
            setNavigationBarTitle={setNavigationBarTitle}
            {...props}
            {...extInfo}
          />
        )
      }

      {/* 当前置业顾问 */}
      {
        !!showConsultant && (<FixedConsultant consultant={consultant} />)
      }

    </>
  )
}
