<script setup>
import {
  ref,
  onMounted,
  defineProps,
  computed,
  onUnmounted,
  watch,
  provide,
} from "vue";
import { getUrn, getAccessToken } from "@/apis/forge";
import { twMerge } from "tailwind-merge";
import hexToRgb from "@/util/hexToRgb";
import getModalPosition from "@/util/getModalPosition";
import useSystemStatusByBaja from "@/hooks/baja/useSystemStatusByBaja";
import ForgeInfoModal from "../../views/system/components/SystemInfoModal.vue";
import useAlarmStore from "@/stores/useAlarmStore";
import useForgeSprite from "@/hooks/forge/useForgeSprite";
import useHeatmapBarStore from "@/stores/useHeatmapBarStore";

const props = defineProps({
  initialData: Object,
  cubeStyle: {
    type: Object,
    default: {
      right: 0,
      top: 0,
    },
  },
});
const store = useHeatmapBarStore();

const { updateDataVisualization, createSprites, showSubSystemObjects, forgeClickListener, clear, setCameraPosition } = useForgeSprite()

const forgeDom = ref(null);

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

    Autodesk.Viewing.Initializer(
      {
        env: "Local",
        language: "en",
      },
      function () {
        const config = {
          extensions: [
            "Autodesk.DataVisualization",
            "Autodesk.DocumentBrowser",
          ],
        };
        let 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 = (viewer, filePath) => {
  return new Promise((resolve, reject) => {
    viewer.loadModel(
      filePath,
      {},
      (model) => {
        viewer.impl.invalidate(true);
        viewer.fitToView();
        setTimeout(() => {
          setCameraPosition(
            {
              x: 241.40975707867645,
              y: -260.4481491801548,
              z: 129.5719879121458,
            }, // 攝影機的新位置
            {
              x: -183.36302786348594,
              y: 194.05657710941966,
              z: -149.3902249981004,
            } // 攝影機的焦點
          );
        }, 500);
        updateDataVisualization(viewer)
        resolve(model);
        console.log("模型加載完成");
      },
      reject
    );
  });
};

// const loadModel = (viewer) => {
//   return new Promise(function (resolve, reject) {
//     async function onDocumentLoadSuccess(doc) {
//       console.log("模型加載完成");
//       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 documentNode = await viewer.loadDocumentNode(
//         doc,
//         doc.getRoot().getDefaultGeometry()
//       );
//       updateDataVisualization(viewer)
//       resolve(documentNode);
//     }
//     function onDocumentLoadFailure(code, message, errors) {
//       reject({ code, message, errors });
//     }
//     Autodesk.Viewing.Document.load(
//       "urn:" + urn,
//       onDocumentLoadSuccess,
//       onDocumentLoadFailure
//     );
//   });
// };

const initForge = async () => {
  // getUrn().then((res) => {
  //   if (!res.isSuccess) return;

  //   initViewer(forgeDom.value).then((viewer) => {
  //     loadModel(viewer, res.data[0].urn_3D).then(() => {
  //       viewer.addEventListener(
  //         Autodesk.Viewing.GEOMETRY_LOADED_EVENT,
  //         async function () {
  //           console.log(
  //             "Autodesk.Viewing.GEOMETRY_LOADED_EVENT",
  //             viewer.isLoadDone()
  //           );
  //           // updateForgeViewer(viewer);
  //           createSprites()
  //           hideAllObjects();
  //         }
  //       );
  //       viewer.addEventListener(
  //         Autodesk.Viewing.CAMERA_CHANGE_EVENT,
  //         function (e) {
  //           // viewer.isLoadDone() &&
  //           //   updateDbidPosition(this, subscribeData.value);
  //           console.log(
  //             "camera position changed: ",
  //             NOP_VIEWER.navigation.getTarget(),
  //             e.camera.position
  //           );
  //         }
  //       );

  //     });
  //   });
  // });
  const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
  const viewer = await initViewer(forgeDom.value)
  const filePath = `${FILE_BASEURL}/upload/forge/0.svf`;
  await loadModel(viewer, filePath)
  viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT,
    async function () {
      console.log(
        "Autodesk.Viewing.GEOMETRY_LOADED_EVENT",
        viewer.isLoadDone()
      );

      showSubSystemObjects();
      createSprites();
      forgeClickListener();
    })

};

onMounted(() => {
  console.log("Forge 加載");
  initForge();
});

// 傳遞目前點擊資訊
const currentInfoModalData = ref(null);
const isMobile = (pointerType) => {
  return pointerType !== "mouse"; // is desktop
};
const getCurrentInfoModalData = (e, position, value) => {
  const mobile = isMobile(e.pointerType);
  currentInfoModalData.value = {
    initPos: mobile
      ? { left: `50%`, top: `50%` }
      : { left: `${position.left}px`, top: `${position.top}px` },
    value,
    isMobile: mobile,
  };
  forge_info_modal.showModal();
};
onUnmounted(() => {
  console.log("Forge 銷毀");

  clear();
});
</script>

<template>
  <ForgeInfoModal :data="currentInfoModalData" />
  <div id="forge-preview" ref="forgeDom" class="relative w-full h-full min-h-full">
    <div v-show="store.heat_bar_isShow" class="absolute z-10 heatbar">
      <div class="w-40 flex justify-between text-[10px] mb-1">
        <span v-for="value in store.heatmapConfig?.range" class="text-gradient-1">{{ value }} {{
          store.heatmapConfig?.unit }}</span>
      </div>
      <div class="w-40 h-3" :style="{
        background: `linear-gradient(
              to right,
              ${store.heatmapConfig?.color[0]} 0%,
              ${store.heatmapConfig?.color[1]} 100%
            )`
      }"></div>
    </div>
    <!-- label -->
    <!-- https://github.com/augustogoncalves/forge-plant-operation/blob/master/forgeSample/wwwroot/js/iconExtension.js -->
    <!-- https://github.com/dukedhx/viewer-iot-react-feathersjs/blob/master/src/client/iconExtension.js -->

    <label v-for="value in subscribeData" :key="key" :data-dbid="value.forge_dbid" :class="twMerge(
      `after:border-t-[${value.currentColor}]`,
      'flex items-center justify-center h-12 -translate-x-1/2 -translate-y-1/5 absolute z-50 px-5 py-4 text-center rounded-md text-lg border-2 border-white',
      'after:absolute after:border-t-[10px] after:border-x-[12px] after:border-x-transparent after:-bottom-[8px] after:left-1/2 after:-translate-x-1/2 ',
      'before:absolute before:border-t-[12px] before:border-x-[14px] before:border-x-transparent before:-bottom-[12px] before:left-1/2 before:-translate-x-1/2 before:border-white'
    )
      " :style="{
        left: `${Math.floor(value.device_coordinate_3d.x)}px`,
        top: `${Math.floor(value.device_coordinate_3d.y) - 100}px`,
        display: value.is_show,
        backgroundColor: value.currentColor,
      }" @click.prevent="(e) =>
        getCurrentInfoModalData(
          e,
          { left: e.clientX, top: e.clientY },
          value
        )
        ">
      <span class="mr-2">{{ value.full_name }}</span>
      <span v-if="value.alarmMsg">{{ value.alarmMsg }}</span>
      <span v-else>{{ value.show_value }}</span>
    </label>
  </div>

</template>

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

#guiviewer3d-toolbar {
  display: none;
  bottom: 200px;
}

.viewcubeWrapper {
  right: v-bind("`${props.cubeStyle.right}%`") !important;
  top: v-bind("`${props.cubeStyle.top}%`") !important;
}

.homeViewWrapper {
  transform: scale(2) !important;
}

.heatbar {
  /* right: v-bind("`${props.cubeStyle.right + 2}%`") !important; */
  top: 0% !important;
}
</style>
