import { TileType, createMap } from "./openlayer";
import { computed, ref, watch, watchEffect } from "vue";
import { createBoard } from "drawing-board";
import { Scene, ScenePoint, boardData, relicsId, scenes } from "@/store/scene";
import { router } from "@/router";
import { addOrUpdateDrawingFetch } from "@/request/drawing";

// ---------map---------

export const tileOptions: TileType[] = ["影像底图", "矢量底图"];
export const tileType = ref<TileType>(tileOptions[0]);
export const defaultCenter = [116.412611, 39.908866];

export const mapManage = createMap();
mapManage.setCenter(defaultCenter);
watchEffect(() => mapManage.setTileType(tileType.value));

export const noValidPoint = (pos: ScenePoint) =>
  !pos.pos || pos.pos.length === 0 || pos.pos.some((i) => !i);
export const validScene = (scene: Scene) => !scene.scenePos.every(noValidPoint);

export const flyScene = (scene: Scene) => {
  const totalPos = [0, 0];
  let numCalc = 0;
  for (let i = 0; i < scene.scenePos.length; i++) {
    const coord = scene.scenePos[i].pos as number[];
    if (!noValidPoint(scene.scenePos[i])) {
      totalPos[0] += coord[0];
      totalPos[1] += coord[1];
      numCalc++;
    }
  }
  console.log(scene);
  totalPos[0] /= numCalc;
  totalPos[1] /= numCalc;
  mapManage.map.getView().setCenter(totalPos);
};

export const gotoPointPage = (point: ScenePoint) => {
  router.push({
    name: queryMode.value ? "query-pano" : "pano",
    params: { pid: point.id },
  });
};

export const autoInitPos = () => {
  const scene = scenes.value.find(validScene);
  if (scene) {
    flyScene(scene);
    return true;
  } else {
    return false;
  }
};

watch(
  () => scenes.value.find(validScene)?.sceneCode,
  (code) => {
    code && autoInitPos();
  },
  { immediate: true }
);

// -------board------
export const board = createBoard({ map: mapManage.map });
watch(
  boardData,
  (data) => {
    data && board.setData(data);
  },
  {
    immediate: true,
    flush: "pre",
  }
);

export const boardDataChange = (dataChange?: () => void) => {
  dataChange && dataChange();
  return addOrUpdateDrawingFetch({
    relicsId: relicsId.value.toString(),
    data: boardData.value,
  });
};

watch(
  tileType,
  (type) => {
    if (type === "影像底图") {
      board.scale.setColor("#fff");
    } else {
      board.scale.setColor("#000");
    }
  },
  { flush: "post", immediate: true }
);

// -----------status----------

export const queryMode = computed(
  () =>
    router.currentRoute.value.name &&
    router.currentRoute.value.name.toString().includes("query")
);
