import { TileType, createMap, Manage } from "./openlayer";
import { ref, watch, watchEffect } from "vue";
import ScaleLine from "ol/control/ScaleLine";

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

const refreshTileType = (mapManage: Manage) => {
  mapManage.setTileType(tileType.value);
};

export const flyUserCenter = (mapManage: Manage) => {
  mapManage.setCenter(defaultCenter);
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      console.log("获取中心位置成功", pos);
      mapManage.setCenter([pos.coords.longitude, pos.coords.latitude]);
    },
    (e) => {
      console.error(e);
      console.error("获取中心位置失败");
    },
    {
      enableHighAccuracy: false,
      timeout: 50000,
      maximumAge: 0,
    }
  );
};

const addScale = (mapManage: Manage) => {
  const scaleLine = new ScaleLine({
    className: "scale-view",
    maxWidth: 150,
    minWidth: 100,
    units: "metric",
  });
  // 加载比例尺
  mapManage.map.addControl(scaleLine);

  watch(
    tileType,
    (type) => {
      const el = (scaleLine as any).element as HTMLDivElement;
      el.classList.add(type === "影像底图" ? "light" : "dark");
      el.classList.remove(type === "影像底图" ? "dark" : "light");
      console.log(el, type);
    },
    { flush: "post", immediate: true }
  );
};

export const mapManageInit = (container: HTMLDivElement) => {
  const mapManage = createMap(container!);
  mapManage.setCenter(defaultCenter);

  watchEffect(() => refreshTileType(mapManage));
  addScale(mapManage);

  return mapManage;
};
