import useSelectedFloor from "@/hooks/useSelectedFloor";
import { watch, ref, inject } from "vue";
import { useRoute } from "vue-router";
import useSystemShowData from "@/hooks/useSystemShowData";

function useForgeFloor() {
  const route = useRoute();
  const levelList = ref([]);
  const { selectedFloor } = useSelectedFloor();
  const { subscribeData } = inject("system_deviceList");

  const forgeViewer = ref(null);
  const dataVizExtn = ref(null);
  const updateViewerFloor = (viewer, dataVisualization) => {
    forgeViewer.value = viewer;
    dataVizExtn.value = dataVisualization;
  };

  const findLevels = () => {
    forgeViewer.value.model.search(
      "layer",
      (nodeIds) => {
        let levels = [];
        const tree = forgeViewer.value.model.getInstanceTree();
        for (let i = 0; i < nodeIds.length; i++) {
          const dbId = nodeIds[i];
          const name = tree.getNodeName(dbId);
          if (!name || name.includes("<沒有層級>")) continue;
          levels.push({
            guid: dbId,
            name,
            dbId,
            extension: {
              buildingStory: true,
              structure: false,
              computationHeight: 0,
              groundPlane: false,
              hasAssociatedViewPlans: false,
            },
          });
        }
        levels = levels.sort((a, b) => b.elevation - a.elevation);
        console.log(levels);
        levelList.value = levels;
      },
      (e) => {
        console.log(e);
      }
    );
  };

  watch(forgeViewer, () => {
    findLevels();
  });

  const hideDbIdFn = () => {
    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 { flatSubData } = useSystemShowData();
  const showDbIdFn = () => {
    hideDbIdFn();
    flatSubData.value.forEach((value, index) => {
      forgeViewer.value.show(value.forge_dbid);
    });

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

  const showLevels = () => {
    if (forgeViewer.value) {
      const currentFloorName =
        selectedFloor.value?.title?.replaceAll(/U/gi, "") || "";

      const level = levelList.value.find(({ name }) =>
        name.includes(currentFloorName)
      );
      console.log(currentFloorName, level);

      if (!level) {
        forgeViewer.value?.impl.toggleGhosting(true);
        forgeViewer.value?.fitToView([forgeViewer.value.model.getRootId()]);
        showDbIdFn();
      } else {
        showDbIdFn();
        // forgeViewer.value.clearSelection();
        // forgeViewer.value.model.setAllVisibility(0);
        forgeViewer.value.impl.toggleGhosting(false);
        // forgeViewer.value.impl.toggleGroundShadow(false);
        forgeViewer.value.show(level.dbId);
        forgeViewer.value.impl.invalidate(true);
        forgeViewer.value.fitToView([level.dbId]);
      }
    }
  };

  watch(
    () => route,
    (newValue) => {
      console.log(newValue);
      newValue && showLevels();
    },
    {
      deep: true,
    }
  );

  return { findLevels, showLevels, updateViewerFloor };
}

export default useForgeFloor;
