<template>
  <Loader v-if="loading" />
  <div class="w-[1106px] h-[966px] absolute z-10 top-[114px]  bg-cover overflow-hidden"
    :style="{ backgroundImage: `url('${CircleBg}')` }">
    <div id="preview" ref="forgeViewerDOM" class="forge-ellipse translate-y-[15px]  w-[1106px] h-[966px]"></div>

  </div>
  <!-- <button class="absolute z-50 top-5 left-5 bg-white" @click.prevent="onClick">切換視角</button>
  <div class="w-screen h-screen ">
    <div id="preview" ref="forgeViewerDOM"></div>
  </div> -->

</template>

<script setup>
import { defineProps, ref, toRaw, watch } from "vue";
import changeCameraPosition from "@/utils/changeCameraPosition.js";
import CircleBg from "@/assets/light_circle.png";
import getTag from "@/utils/getTag.js";
import Loader from "./Loader.vue";


const MODEL_URN = 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6dWxwbXU4cXhiemxpZ3NncWpvZHFkaTQ3b2V6aGdwcmEwMjYzbHNrOWF2dm16NnloLWRlbW8vJUUzJTgwJTkwUFJPM0NfU21hcnRfRmFjdG9yeSVFMyU4MCU5MTA2MDIubndk'

const props = defineProps({
  forgeIds: {
    type: Object,
    required: true
  }
})

const forgeViewerDOM = ref(null);
const forgeViewer = ref(null);
const tagData = ref([]);

const loading = ref(true);

const getAccessToken = async (callback) => {
  try {
    const resp = await fetch('/forge/api/auth/token');
    if (!resp.ok) {
      throw new Error(await resp.text());
    }
    const { access_token, expires_in } = await resp.json();
    callback(access_token, expires_in);
  } catch (err) {
    alert('Could not obtain access token. See the console for more details.');
    console.error(err);
  }
}

const initViewer = (container) => {
  return new Promise(function (resolve, reject) {
    Autodesk.Viewing.Initializer({ env: 'AutodeskProduction', getAccessToken }, function () {
      const config = {
        extensions: ['Autodesk.DocumentBrowser']
      };
      const viewer = new Autodesk.Viewing.GuiViewer3D(container, config);
      Autodesk.Viewing.Private.InitParametersSetting.alpha = true;

      viewer.start();
      resolve(viewer);
    });
  });
}

function findViewpoints(node, result = []) {
  if (!node) return result;

  const data = node.data;

  // 判斷是否是 view / viewpoint

  // console.log('Node:', data, data.type, data.role, data.camera, data.name, data.isViewpoint);
  if (
    data &&
    (data.type === 'view' && data.role === '3d')

  ) {
    result.push(node);
  }

  if (node.children) {
    node.children.forEach(child => findViewpoints(child, result));
  }

  return result;
}


const Viewpoints = ref([]);
const loadModel = (viewer, urn) => {
  return new Promise(function (resolve, reject) {
    function onDocumentLoadSuccess(doc) {
      viewer.setGroundShadow(false);
      viewer.impl.renderer().setClearAlpha(0); //clear alpha channel
      viewer.impl.glrenderer().setClearColor(0xffffff, 0); //set transparent background, color code does not matter
      viewer.impl.invalidate(true); //trigger rendering

      const root = doc.getRoot();

      const views = findViewpoints(root);

      console.log('Viewpoints:', views);
      Viewpoints.value = views;

      resolve(viewer.loadDocumentNode(doc, doc.getRoot().getDefaultGeometry()));
    }
    function onDocumentLoadFailure(code, message, errors) {
      reject({ code, message, errors });
    }
    viewer.setLightPreset(0);
    Autodesk.Viewing.Document.load('urn:' + urn, onDocumentLoadSuccess, onDocumentLoadFailure);
  });
}


// 記錄相機初始位置
const initialCameraPosition = ref(null);
const initialCameraTarget = ref(null);


watch(forgeViewerDOM, async (newVal) => {
  if (newVal) {
    try {
      const viewer = await initViewer(newVal);

      forgeViewer.value = toRaw(viewer);
      await loadModel(viewer, MODEL_URN);

      // ⭐ 讓模型自動縮放到橢圓框內可見
      viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, async () => {

        // viewer.fitToView();

        // 取得相機原本的位置與 target
        const nav = viewer.navigation;
        const cameraPos = nav.getPosition().clone();
        const cameraTarget = nav.getTarget().clone();

        initialCameraPosition.value = cameraPos
        initialCameraTarget.value = cameraTarget;


        // 根據你的 UI（橢圓框大小）調整
        const scaleFactor = 1; // ⭐ 微調用
        const direction = cameraPos.clone().sub(cameraTarget).normalize();
        const distance = cameraPos.distanceTo(cameraTarget) * scaleFactor;
        const newPos = cameraTarget.clone().add(direction.multiplyScalar(distance));
        viewer.navigation.setView(newPos, cameraTarget); // 再置中



        const tags = await getTag(viewer);
        tagData.value = tags;
        console.log('Tags:', tags);
        loading.value = false;


      });
    } catch (err) {
      alert('Failed to load Forge Viewer. See the console for more details.');
      console.error(err);
    }



  }
})



const onClick = () => {
  if (forgeViewer.value) {
    changeCameraPosition(forgeViewer.value);
  }
}

defineExpose({
  forgeViewer,
  initialCameraPosition,
  initialCameraTarget,
  tagData,
  Viewpoints
})
</script>

<style scoped>
.forge-ellipse {

  /* 橢圓裁切 */
  clip-path: circle(483px at 50% 50%);

}

.adsk-viewing-viewer,
.adsk-viewing-canvas,
.adsk-viewing-overlay,
.adsk-viewing-overlay div {
  background-color: transparent !important;
}
</style>