import { watch, inject, markRaw, ref, computed, provide } from "vue";
import useAlarmStore from "@/stores/useAlarmStore";
import hexToRgb from "@/util/hexToRgb";
import useSystemShowData from "@/hooks/useSystemShowData";
import useForgeHeatmap from "./useForgeHeatmap";
import useForgeFloor from "./useForgeFloor";

export default function useForgeSprite() {
  const { subscribeData } = inject("system_deviceList");
  const { getCurrentInfoModalData, clearSelectedDeviceInfo, selected_dbid } =
    inject("system_selectedDevice");
  const forgeViewer = ref(null);
  const dataVizExtn = ref(null);
  let lastClickedDbId = null;

  const { createHeatMap, updateViewExtension } = useForgeHeatmap();
  const { updateViewerFloor } = useForgeFloor();

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

    // 設定攝影機的新位置與焦點
    forgeViewer.value.navigation.setView(newPosition, newTarget);

    // 確保 Home 視角
    forgeViewer.value.autocam.setCurrentViewAsHome(true); 
  };

  const updateDataVisualization = async (viewer) => {
    if (!forgeViewer.value) {
      forgeViewer.value = markRaw(viewer);
    }

    const dataVisualization = await viewer.loadExtension(
      "Autodesk.DataVisualization"
    );
    dataVizExtn.value = markRaw(dataVisualization);
    updateViewExtension(markRaw(viewer), markRaw(dataVisualization));
    updateViewerFloor(markRaw(viewer), markRaw(dataVisualization));
  };

  function onSpriteClicked(event) {
    event.hasStopped = true;

    if (event.type === Autodesk.DataVisualization.Core.MOUSE_CLICK_OUT) return;

    const data = subscribeData.value.find(
      (d) =>
        d.spriteDbId === event.dbId || d.forge_dbid === event.dbIdArray?.[0]
    );
    console.log("onSpriteClicked", event.target);
    console.log("onSpriteClicked", data);
    // modalContent.value = data;
    // debugger;
    if (data) {
      getCurrentInfoModalData(
        event,
        { left: event.target.startX, top: event.target.startY },
        data
      );
    }
  }

  const { flatSubData } = useSystemShowData();

  // 創建 sprites
  const createSprites = async () => {
    if (dataVizExtn.value) {
      dataVizExtn.value.removeAllViewables();
      const DataVizCore = Autodesk.DataVisualization.Core;
      const viewableType = DataVizCore.ViewableType.SPRITE;
      let spriteColor = new THREE.Color(0xffffff);
      const BASEURL = import.meta.env.VITE_FORGE_BASEURL;
      const spriteIconUrl = `${BASEURL}/hotspot.svg`;
      const style = new DataVizCore.ViewableStyle(
        viewableType,
        spriteColor,
        spriteIconUrl
      );
      const viewableData = new DataVizCore.ViewableData();
      viewableData.spriteSize = 24; // Sprites as points of size 24 x 24 pixels
      flatSubData.value?.forEach((d, index) => {
        if (d.device_coordinate_3d) {
          const position = d.device_coordinate_3d;
          style.color = new THREE.Color(hexToRgb(d.device_normal_color));
          const viewable = new DataVizCore.SpriteViewable(
            position,
            style,
            d.spriteDbId
          );
          viewableData.addViewable(viewable);
        }
      });
      // await viewableData.finish();
      // dataVizExtn.value.addViewables(viewableData);
      // console.log(dataVizExtn.value);
      viewableData.finish().then(
        () => {
          dataVizExtn.value.addViewables(viewableData);
          createHeatMap();
        },
        (error) => {
          console.log(error);
        }
      );
    }
  };

  watch(
    () => flatSubData,
    () => {
      if (forgeViewer.value?.isLoadDone()) {
        createSprites();
        showSubSystemObjects();
      }
    },
    {
      deep: true,
    }
  );

  watch(
    () => selected_dbid,
    () => {
      if (forgeViewer.value?.isLoadDone()) {
        cardfitToView(selected_dbid.value);
      }
    },
    {
      immediate: true,
      deep: true,
    }
  );

  const forgeClickListener = () => {
    console.log("監聽forge");

    forgeViewer.value.addEventListener(
      Autodesk.DataVisualization.Core.MOUSE_CLICK,
      onSpriteClicked
    );
    forgeViewer.value.addEventListener(
      Autodesk.DataVisualization.Core.MOUSE_CLICK_OUT,
      onSpriteClicked
    );
  };

  const cardfitToView = async ([forge_dbid, spriteDbId]) => {
    try {
      // 相機調整
      const nav = forgeViewer.value.navigation;
      const camera = nav.getCamera();
      forgeViewer.value.fitToView([forge_dbid], null, true);
      const direction = new THREE.Vector3();
      camera.getWorldDirection(direction);
      const distanceBack = 30;
      camera.position.add(direction.multiplyScalar(-distanceBack));
      const target = nav.getTarget();
      const fov = nav.getVerticalFov();
      nav.setRequestTransition(true, camera.position, target, fov);

      if (lastClickedDbId !== null && lastClickedDbId !== spriteDbId) {
        dataVizExtn.value.invalidateViewables([lastClickedDbId], (viewable) => {
          return {
            scale: 1.0, // 恢復為 scale 1
          };
        });
      }

      dataVizExtn.value.invalidateViewables([spriteDbId], (viewable) => {
        return {
          scale: 2.0, // 設置為 scale 2
        };
      });

      lastClickedDbId = spriteDbId;
    } catch (error) {
      console.error("Error in cardfitToView:", error);
    }
  };

  const hideAllObjects = () => {
    const tree = forgeViewer.value.model.getInstanceTree();
    const allDbIdsStr = Object.keys(tree.nodeAccess.dbIdToIndex);
    for (var i = 0; i < allDbIdsStr.length; i++) {
      forgeViewer.value.hide(parseInt(allDbIdsStr[i]));
    }
  };

  const showSubSystemObjects = () => {
    hideAllObjects();
    flatSubData.value.forEach((value, index) => {
      forgeViewer.value.show(value.forge_dbid);
    });

    forgeViewer.value.impl.invalidate(true);
  };

  const clear = () => {
    forgeViewer.value.removeEventListener(
      Autodesk.DataVisualization.Core.MOUSE_CLICK,
      onSpriteClicked
    );
    forgeViewer.value.removeEventListener(
      Autodesk.DataVisualization.Core.MOUSE_CLICK_OUT,
      onSpriteClicked
    );
    forgeViewer.value.tearDown();
  };

  return {
    createSprites,
    setCameraPosition,
    updateDataVisualization,
    showSubSystemObjects,
    forgeClickListener,
    clear,
    cardfitToView,
  };
}
