import React, { useEffect, useState } from 'react'
import styles from './index.module.scss'
import { isPc, otherUrl } from '@/utils/http'
import { useParams } from 'react-router-dom'
import history from '@/utils/history'

const obj = {
  end: {
    pc: 'unity/HeNanMuseum-pc/ManorScene/index.html',
    app: 'unity/HeNanMuseum-mobile/ManorScene/index.html'
  },
  game1: {
    pc: 'unity/HeNanMuseum-pc/LinkingGame/index.html',
    app: 'unity/HeNanMuseum-mobile/LinkingGame/index.html'
  },
  game2: {
    pc: 'unity/HeNanMuseum-pc/PuzzleGame/index.html',
    app: 'unity/HeNanMuseum-mobile/PuzzleGame/index.html'
  },
  game3: {
    pc: 'unity/HeNanMuseum-pc/ThrowGame/index.html',
    app: 'unity/HeNanMuseum-mobile/ThrowGame/index.html'
  }
}

function C2unityEnd() {
  const urlObj: any = useParams()

  const [url, setUrl] = useState('')

  useEffect(() => {
    const key = urlObj.key

    console.log(123, key)

    const objTemp = Reflect.get(obj, key)
    const res = Reflect.get(objTemp, isPc ? 'pc' : 'app')
    setUrl(`${otherUrl + res}?T=${Date.now()}`)
  }, [urlObj.key])

  useEffect(() => {
    if (url) {
      if (isPc) {
        const body = document.querySelector('body')
        const iframe = document.createElement('iframe')
        iframe.frameBorder = 'none'
        iframe.title = '漫游'
        iframe.id = 'myIframe'
        iframe.src = url
        body?.appendChild(iframe)
      }

      return () => {
        const iframeDom = document.querySelector('#myIframe')

        iframeDom?.remove()
      }
    }
  }, [url])

  useEffect(() => {
    window.unityBack = () => {
      console.log('从unity点击返回')

      // 退出
      if (window.location.href.includes('r=ren')) history.replace('/more?r=ren')
      else if (window.location.href.includes('v=v2')) history.replace('/visit2?v=v2')
      else history.go(-1)
    }
  }, [])

  return (
    <div className={styles.C2unityEnd}>
      {!isPc && url ? (
        <iframe className='C2unity' title='陶庄园' src={url} frameBorder='0'></iframe>
      ) : null}
    </div>
  )
}

const MemoC2unityEnd = React.memo(C2unityEnd)

export default MemoC2unityEnd
