<template>
  <div class="map-layout">
    <div id="map" class="map-container" ref="mapContainer" @click.stop>
      <div class="map-component">
        <el-select
          v-model="tileType"
          placeholder="选择底图"
          style="width: 120px"
          class="tile-type-select"
        >
          <el-option
            v-for="item in tileOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </div>

      <div class="board" ref="boardContainer"></div>
    </div>
    <div class="right-control">
      <MapRight
        @fly-point="flyScenePoint"
        @fly-scene="flyScene"
        @goto-point="gotoPointPage"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import MapRight from "./map-right.vue";
import { router, setDocTitle } from "@/router";
import { Manage } from "./openlayer";
import { ScenePoint, Scene, scenePoints, scenes } from "@/store/scene";
import { initRelics, initSelfRelics, relics } from "@/store/relics";
import { onMounted, ref, watchEffect, watch, onUnmounted } from "vue";
import { createBoard, scenePosTransform } from "./board/";
import { relicsPolyginsFetch } from "@/request";
import {
  mapManageInit,
  boardInit,
  flyUserCenter,
  tileOptions,
  tileType,
} from "./map-flow";

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

const autoInitPos = () => {
  const scene = scenes.value.find(
    (scene) => !scene.scenePos.every((pos) => !pos.pos || pos.pos.length === 0)
  );
  if (scene) {
    flyScene(scene);
    return true;
  } else {
    return false;
  }
};
const flyPos = (pos: number[]) => mapManage.map.getView().setCenter(pos);
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 (coord && coord.length > 0) {
      totalPos[0] += coord[0];
      totalPos[1] += coord[1];
      numCalc++;
    }
  }

  totalPos[0] /= numCalc;
  totalPos[1] /= numCalc;
  flyPos(totalPos);
};

const flyScenePoint = (point: ScenePoint) => {
  flyPos(point.pos);
  board.polygon().activePointId.value = point.id.toString();
};

watch(
  () => [router.currentRoute.value.name, router.currentRoute.value.params?.relicsId],
  ([name, rid], old) => {
    if (["map", "query-map"].includes(name as string) && (!old || old[1] !== rid)) {
      relics.value = undefined;
      const fn = name === "map" ? initSelfRelics : initRelics;
      fn(Number(rid)).finally(() => {
        if (!relics.value) {
          return router.replace({ name: "relics" });
        }
        if (mapManage && !autoInitPos()) {
          flyUserCenter(mapManage);
        }
        const points = scenePosTransform(scenes.value);
        board.setData(
          {
            points,
            lines: [],
            polygons: [],
          },
          router.currentRoute.value.params.relicsId as string
        );
        board.polygon().bus.on("clickPoint", (bpoint) => {
          const point =
            bpoint.id &&
            scenePoints.value.find((point) => point.id.toString() === bpoint.id);
          point && gotoPointPage(point);
        });

        // relicsPolyginsFetch().then((data) => {
        //   relics.value;
        //   board.setData(data, router.currentRoute.value.params.relicsId as string);
        //   board.polygon().bus.on("clickPoint", (bpoint) => {
        //     const point =
        //       bpoint.id &&
        //       scenePoints.value.find((point) => point.id.toString() === bpoint.id);
        //     point && gotoPointPage(point);
        //   });
        // });
      });
    }
  },
  { immediate: true }
);

watch(
  () => {
    const scene = scenes.value.find(
      (scene) => !scene.scenePos.every((pos) => !pos.pos || pos.pos.length === 0)
    );
    return scene?.sceneCode;
  },
  (firstCode) => {
    if (firstCode && mapManage) {
      autoInitPos();
    }
  }
);

watchEffect(() => {
  if (
    ["map", "query-map"].includes(router.currentRoute.value.name as string) &&
    relics.value
  ) {
    setDocTitle(relics.value.name);
  }
});

// ----------流程--------
const mapContainer = ref<HTMLDivElement>();
const boardContainer = ref<HTMLDivElement>();
let mapManage: Manage;
let board: ReturnType<typeof createBoard>;

onMounted(async () => {
  mapManage = mapManageInit(mapContainer.value!);
  board = boardInit(boardContainer.value!, mapManage);
});

onUnmounted(() => {
  mapManage.map.dispose();
  board.destory();
});
</script>

<style lang="scss">
.tooltip {
  pointer-events: none;
}
.map-layout {
  display: flex;
  flex-direction: row;
  height: 100%;
}

.map-container {
  flex: 1;
  position: relative;
}

.right-control {
  flex: none;
  width: 300px;
  padding: 15px;

  border-left: 1px solid var(--border-color);
}

.map-component {
  width: 100%;
  height: 100%;
  position: relative;
}

.active {
  cursor: pointer;
}

.active-point {
  position: absolute;
  pointer-events: none;
}

.map-component {
  pointer-events: none;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 9;
}
.env {
  width: 100%;
  height: 100%;
}

.tile-type-select {
  pointer-events: all;
  position: absolute;
  right: 10px;
  top: 10px;
}

.scale-view {
  --color: #fff;
  position: absolute;
  left: 20px;
  bottom: 20px;
  height: 8px;
  color: var(--color);
  text-align: center;
  border: 1px solid var(--color);
  border-top: none;
  z-index: 1;
  font-size: 14px;
  display: flex;
  align-items: end;
  &.light {
    --color: #fff;
    > div {
      text-shadow: 0 0 2px #000;
    }
  }
  &.dark {
    --color: #000;
    > div {
      text-shadow: 0 0 2px #fff;
    }
  }
}

.board {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}
</style>
