import React, { useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { isPc, myData, otherUrl } from '@/utils/http'
import { VisitHotDataType } from '@/types'
import Hot1 from '../A2visit/PanoVideo/Hot1'
import Hot2 from '../A2visit/PanoVideo/Hot2'
import history from '@/utils/history'
import BtnRight from '@/components/BtnRight'

const obj = {
  1: {
    pc: 'unity/HeNanMuseum-pc/MainScene/index.html',
    mo: 'unity/HeNanMuseum-mobile/MainScene/index.html'
  },
  2: {
    pc: 'unity/HeNanMuseum-pc/RoomScene/index.html',
    mo: 'unity/HeNanMuseum-mobile/RoomScene/index.html'
  }
}

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

  const [urlId, setUrlId] = useState('')

  // 1:室外 2：室内
  const [url, setUrl] = useState('')

  useEffect(() => {
    setUrlId(urlObj.id)

    const temp = Reflect.get(obj, urlObj.id)

    const res = Reflect.get(temp, isPc ? 'pc' : 'mo')

    setUrl(otherUrl + res)

    // 注册
    window.unityOpenHot = (index: number) => {
      // 打开热点
      setInd(Number(index))
    }

    window.unityBack = () => {
      // 退出
      history.go(-1)
    }
  }, [urlObj.id])

  // 打开热点的索引
  const [ind, setInd] = useState(-1)

  const data = useMemo(() => {
    let arr: VisitHotDataType = []

    if (ind !== -1) {
      const data1 = myData.visit.hot[ind].data
      const data2 = myData.banquet.hot[ind].data

      arr = urlId === '1' ? data1 : data2
    }

    return arr
  }, [ind, urlId])

  useEffect(() => {
    if (url) {
      // 待完善
      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])

  return (
    <div className={styles.C1unity}>
      {/* {url ? <iframe frameBorder='none' title='漫游' src={url}></iframe> : null} */}

      {/* 返回按钮 */}
      <BtnRight imgName='back' clickSon={() => history.go(-1)} title='返回' />

      {ind === -1 ? null : ind === 0 && urlId === '1' ? (
        <Hot1 data={data} closeFu={() => setInd(-1)} />
      ) : (
        <Hot2
          data={data}
          closeFu={() => setInd(-1)}
          name={myData[urlId === '1' ? 'visit' : 'banquet'].hot[ind].name}
        />
      )}
    </div>
  )
}

const MemoC1unity = React.memo(C1unity)

export default MemoC1unity
