
import { useEffect, useRef, useState } from 'react'
import { useRouter } from '@tarojs/taro'
import { parseQueryString, setRecommender } from '@/utils/tools'
import { getCodeScene } from '@/services/common'

export default (person) => {
  const router = useRouter()
  const routerRef = useRef()
  routerRef.current = router

  const { scene } = router.params

  // 标记是否已经远程读取二维码参数
  const [inited, setInited] = useState(scene ? false : true)

  useEffect(() => {
    if (scene) {
      getCodeScene(scene).then((res) => {
        const queryStr = JSON.parse(res).scene
        const { recommender, ...otherParams } = parseQueryString(queryStr) || {}

        const isSelf = recommender && recommender === person?.personId
        
        routerRef.current.params = {
          ...routerRef.current.params || {},
          ...otherParams,
          ...(isSelf || !recommender ? {} : { recommender }),
        }

        if (!isSelf) {
          setRecommender(recommender)
        }

        setInited(true)
      })
    }
  }, [scene, person])

  const params = {
    ...routerRef.current.params,
    qrInited: inited
  }

  router.params = params
  return router
}
