
import { useMemo } from 'react'
import Taro from '@tarojs/taro'
import { useModel } from '@/store'
import useRouter from '@/utils/hooks/useRouter'
import Loading from './Loading'
import { getPageBy, getIndexPageOf } from '../routes'

export default (Child) => (props) => {
  const { person } = useModel('person')
  const router = useRouter()

  // 确保人员信息到位
  const loading = !person?.personRole;

  // 校验人员角色及页面是否对应
  const jumpPage = useMemo(() => {
    const personRole = person?.personRole;
    if (!personRole) return;

    const isNormalPerson = personRole === 'normal'

    const currentPage = getPageBy(router.path)
    let indexPage = getIndexPageOf(personRole)
    if (!isNormalPerson) {
      indexPage = `${personRole}/${indexPage.page}`

    } else {
      indexPage = `pages/index/index`
    }

    const isMatched = isNormalPerson ?
      // 如果是普通客户, page.root 应该是空的
      !currentPage.root :
      // 其他角色, 应该是对应的
      currentPage.root === personRole


    // 如果对应上, 就不跳转
    return isMatched ? personRole : indexPage

  }, [router.path, person?.personRole])

  if (jumpPage) {
    // 注意此处跳转是没有加上原来的页面参数的
    Taro.reLaunch({
      url: `/${jumpPage}`,
    })
  }

  return loading ? <Loading /> : <Child {...props} person={person} router={router} />
}
