<template>
  <div id="three-box"></div>
</template>
<script>
import CameraControls from 'camera-controls';
import { TilesRenderer } from '3d-tiles-renderer';
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
var instructions, renderer, cameraControls, scene, camera, renderTarget, tilesRenderer;
var animateId,
  singleFrameTime = 1 / 30,
  frameCount = 0;
var needsRerender = false;
var [fpsClock, timeStamp] = (function* (v) {
  while (true) yield v;
})(0);
export default {
  name: 'FlTiles',
  data() {
    return {};
  },
  created() {
    CameraControls.install({ THREE: this.THREE });
    fpsClock = new this.THREE.Clock();
    renderTarget = new this.THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, {
      minFilter: this.THREE.LinearFilter,
      magFilter: this.THREE.LinearFilter,
      format: this.THREE.RGBAFormat,
      stencilBuffer: true,
    });
  },
  mounted() {
    instructions = document.getElementById('three-box');
    this.initRender();
    this.initScene();
    this.initCamera();
    this.initControl();
    this.initLight();
    this.init3tiles();
    cameraControls.addEventListener('wake', () => {
      console.log(cameraControls._camera.position);
    });
    this.animate();
  },
  methods: {
    initRender() {
      renderer = new this.THREE.WebGLRenderer({
        antialias: true,
        logarithmicDepthBuffer: true,
      });
      renderer.setPixelRatio(window.devicePixelRatio * 2);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.domElement.id = 'three-model';
      renderer.shadowMap.enabled = true;
      instructions.appendChild(renderer.domElement);
    },
    initScene() {
      scene = new this.THREE.Scene();
      scene.background = new this.THREE.Color(0xffffff);
    },
    initCamera() {
      camera = new this.THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        10000000
      );
      camera.position.set(0, 10, 105.524230957031);
    },
    initControl() {
      // 初始化控件
      cameraControls = new CameraControls(camera, renderer.domElement);
      cameraControls.dollyToCursor = true;
      cameraControls.smoothTime = 0.1;
      cameraControls.draggingSmoothTime = 0.05;
      cameraControls.truckSpeed = 2.0;
      cameraControls.infinityDolly = true;
      cameraControls.minDistance = 4;
    },
    // 初始化光源
    initLight() {
      const pmremGenerator = new this.THREE.PMREMGenerator(renderer);
      scene.environment = pmremGenerator.fromScene(new RoomEnvironment(), 0.04).texture;
    },
    init3tiles() {
      // 这个文件需要放到public文件夹下 Tile_+003_+003/Tile_+003_+003
      tilesRenderer = new TilesRenderer('/tiles/tileset.json');
      tilesRenderer.setCamera(camera);
      tilesRenderer.setResolutionFromRenderer(camera, renderer);
      scene.add(tilesRenderer.group);

      setTimeout(() => (needsRerender = true), 1000);
    },
    // 添加一个标志，等待一帧让TilesRenderer初步解析JSON
    debugTileset() {
      if (tilesRenderer.root && frameCount++ < 10) {
        // 检查前几帧
        console.log('[调试] TilesRenderer根节点:', tilesRenderer.root);

        // 1. 尝试获取根节点的包围盒 (通常很大，是整个世界范围)
        if (tilesRenderer.root.boundingVolume) {
          console.log('[调试] 根节点包围盒:', tilesRenderer.root.boundingVolume);
          // 如果是BOX类型，可以获取其中心
          if (tilesRenderer.root.boundingVolume.box) {
            const box = tilesRenderer.root.boundingVolume.box;
            // box: [中心x, 中心y, 中心z, x轴半长, y轴半长, z轴半长]
            console.log(`[调试] 根节点包围盒中心: [${box[0]}, ${box[1]}, ${box[2]}]`);
          }
        }

        // 2. 检查第一个子节点（中间节点）
        if (tilesRenderer.root.children && tilesRenderer.root.children[0]) {
          const firstChild = tilesRenderer.root.children[0];
          console.log('[调试] 第一个子节点:', firstChild);
          if (firstChild.boundingVolume) {
            console.log('[调试] 第一个子节点包围盒:', firstChild.boundingVolume);
          }
        }

        // 3. 如果中间节点还有children，继续往下找
        if (
          tilesRenderer.root.children &&
          tilesRenderer.root.children[0] &&
          tilesRenderer.root.children[0].children &&
          tilesRenderer.root.children[0].children[0]
        ) {
          const deepestChild = tilesRenderer.root.children[0].children[0];
          console.log('[调试] 更深层的子节点:', deepestChild);
          if (deepestChild.content) {
            console.log('[调试] 首个Content URI:', deepestChild.content.uri);
          }
        }
      }
    },
    animate() {
      //         const delta = fpsClock.getDelta();
      // timeStamp += delta;
      // requestAnimationFrame(this.animate)
      //   if (needsRerender) {

      //   needsRerender = false;
      //   let box = new this.THREE.Box3()

      //   if (tilesRenderer.getBoundingBox(box)) {

      //     box.getCenter(tilesRenderer.group.position);

      //     tilesRenderer.group.position.multiplyScalar(-1);

      //   }

      //   tilesRenderer.update();

      //   }
      //   cameraControls.update(timeStamp)
      //    tilesRenderer.update();
      //   renderer.render(scene, camera);
      const delta = fpsClock.getDelta();
      timeStamp += delta;
      animateId = requestAnimationFrame(this.animate);
      if (timeStamp > singleFrameTime) {
        if (needsRerender) {
          needsRerender = false;
          let box = new this.THREE.Box3();
          if (tilesRenderer.getBoundingBox(box)) {
            box.getCenter(tilesRenderer.group.position);
            tilesRenderer.group.position.multiplyScalar(-1);
          }
        }
        cameraControls.update(timeStamp);
        // this.debugTileset();
        tilesRenderer.update();
        renderer.render(scene, camera);
        timeStamp = timeStamp % singleFrameTime;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
#three-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
