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

export default () => {
  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 params = parseQueryString(queryStr) || {}
        
        routerRef.current.params = {
          ...routerRef.current.params || {},
          ...params
        }

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

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

  router.params = params
  return router
}
