<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);
      }
    );
  });
};

// 使用本地 .svf 文件加載模型
const loadModel = (filePath) => {
  return new Promise((resolve, reject) => {
    viewer.loadModel(
      filePath,
      {},
      (model) => {
        viewer.impl.invalidate(true);
        viewer.fitToView();
        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>
