<script setup>
import { ref, onMounted, onUnmounted } from "vue";

const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const forgeDom = ref(null);
let viewer = null;

// 初始化 Forge Viewer
const initViewer = (container) => {
  return new Promise(function (resolve, reject) {
    Autodesk.Viewing.Initializer(
      {
        env: "Local",
        language: "en",
      },
      function () {
        const config = {
          extensions: [
            "Autodesk.DataVisualization",
            "Autodesk.DocumentBrowser",
          ],
        };
        viewer = new Autodesk.Viewing.GuiViewer3D(container, config);
        Autodesk.Viewing.Private.InitParametersSetting.alpha = true;
        viewer.start();
        viewer.setGroundShadow(false);
        viewer.impl.renderer().setClearAlpha(0);
        viewer.impl.glrenderer().setClearColor(0xffffff, 0);
        viewer.impl.invalidate(true);
        resolve(viewer);
      }
    );
  });
};

// 設置攝影機位置
const setCameraPosition = (position, target) => {
  const nav = viewer.navigation;
  // 使用 THREE.Vector3 定義位置與焦點
  const newPosition = new THREE.Vector3(position.x, position.y, position.z);
  const newTarget = new THREE.Vector3(target.x, target.y, target.z);

  // 設定攝影機的新位置與焦點
  nav.setView(newPosition, newTarget);
  console.log("攝影機定位完成:");
  console.log("新位置:", newPosition);
  console.log("新焦點:", newTarget);
};

// 使用本地 .svf 文件加載模型
const loadModel = (filePath) => {
  return new Promise((resolve, reject) => {
    viewer.loadModel(
      filePath,
      {},
      (model) => {
        viewer.impl.invalidate(true);
        viewer.fitToView();
        // 設置攝影機位置
        setTimeout(() => {
          setCameraPosition(
            {
              x: -212.33421531428007,
              y: 299.3895400707608,
              z: 157.48711907404862,
            }, // 攝影機的新位置
            {
              x: 151.61159898775077,
              y: -196.55136189609067,
              z: -136.47282256290345,
            } // 攝影機的焦點
          );
        }, 500);
        resolve(model);
        console.log("模型加載完成");
      },
      reject
    );
  });
};

onMounted(async () => {
  console.log("Forge 加載");
  await initViewer(forgeDom.value);
  const filePath = `${FILE_BASEURL}/upload/forge/0.svf`;
  loadModel(filePath);
});

onUnmounted(() => {
  console.log("Forge 銷毀");
  if (viewer) {
    viewer.tearDown();
    viewer.finish();
    viewer = null;
  }
});
</script>

<template>
  <div
    id="forge-preview"
    ref="forgeDom"
    class="relative w-full h-full min-h-full"
  ></div>
</template>

<style lang="css">
.adsk-viewing-viewer {
  background-color: transparent !important;
}

#guiviewer3d-toolbar {
  display: none;
  bottom: 200px;
}
</style>
