import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'

import * as THREE from 'three'

import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js'
import { USDZLoader } from 'three/addons/loaders/USDZLoader.js'

function A1home() {
  const camera = useRef(
    new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100)
  )

  const scene = useRef(new THREE.Scene())

  const renderer = useRef(new THREE.WebGLRenderer({ antialias: true }))

  function animate() {
    renderer.current.render(scene.current, camera.current)
  }

  const onWindowResize = useCallback(() => {
    camera.current.aspect = window.innerWidth / window.innerHeight
    camera.current.updateProjectionMatrix()

    renderer.current.setSize(window.innerWidth, window.innerHeight)
  }, [])

  const init = useCallback(async () => {
    // 获取地址栏参数
    const fileName = window.location.href.split('?m=')[1]

    camera.current.position.set(0, 0.75, -3.5)

    const rgbeLoader = new RGBELoader().setPath('./modelFile/')

    const usdzLoader = new USDZLoader().setPath('./modelFile/')

    const [texture, model] = await Promise.all([
      rgbeLoader.loadAsync(`saeukkang.hdr`),
      usdzLoader.loadAsync(`${fileName}.usdz`)
    ])

    // environment

    texture.mapping = THREE.EquirectangularReflectionMapping

    scene.current.background = texture
    scene.current.backgroundBlurriness = 0.5
    scene.current.environment = texture

    // model

    model.position.y = 0.25
    model.position.z = -0.25
    scene.current.add(model)

    // renderer

    renderer.current.setPixelRatio(window.devicePixelRatio)
    renderer.current.setSize(window.innerWidth, window.innerHeight)
    renderer.current.setAnimationLoop(animate)
    renderer.current.toneMapping = THREE.ACESFilmicToneMapping
    renderer.current.toneMappingExposure = 2.0
    document.querySelector('#A1home')!.appendChild(renderer.current.domElement)

    const controls = new OrbitControls(camera.current, renderer.current.domElement)
    controls.minDistance = 1
    controls.maxDistance = 8
    // controls.target.y = 15;
    // controls.update();

    window.addEventListener('resize', onWindowResize, true)
  }, [onWindowResize])

  useEffect(() => {
    init()
  }, [init])

  return <div className={styles.A1home} id='A1home'></div>
}

const MemoA1home = React.memo(A1home)

export default MemoA1home
