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 } = inject(
    "system_selectedDevice"
  );
  const forgeViewer = ref(null);
  const dataVizExtn = ref(null);

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

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

  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 fitToView = () => {
    const { x, y, z } = JSON.parse(searchParams.value.camera_position);
    const newPosition = new THREE.Vector3(x, y, z); //!<<< 相机的新位置

    const {
      x: x1,
      y: y1,
      z: z1,
    } = JSON.parse(searchParams.value.target_position); //!<<< 计算新焦点位置
    const newTarget = new THREE.Vector3(x1, y1, z1); //!<<< 焦點的新位置

    NOP_VIEWER.navigation.getCamera().setView({
      position: newPosition.clone(),
      target: newTarget.clone(),
    });
    setTimeout(() => {
      updateDbidPosition(NOP_VIEWER, subscribeData.value);
    }, 700);
  };

  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();
    subscribeData.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,
    updateDataVisualization,
    showSubSystemObjects,
    forgeClickListener,
    clear,
  };
}
