import { Map, View } from "ol";
import { TileType, baseTileLayer, geoTileLayer, setBaseTileType } from "./tile";
import {
  HotData,
  addHots,
  delHots,
  hotLayer,
  dynamicHots,
  clearHots,
} from "./hot";
import { Emitter } from "mitt";
import { boundingExtent } from "ol/extent";

const createMap = (container?: HTMLDivElement) => {
  const view = new View({
    center: [113.59562585879772, 22.367660742553472],
    projection: "EPSG:4326",
    zoom: 18,
  });

  return new Map({
    layers: [baseTileLayer, geoTileLayer, hotLayer],
    view,
    target: container,
    controls: [],
  });
};

export class Manage {
  map: Map;
  hotsBus: Emitter<{
    active: any;
    click: any;
  }>;

  moundDOM: HTMLDivElement;
  constructor(container?: HTMLDivElement) {
    this.moundDOM = document.createElement("div");
    this.moundDOM.style.width = "300px";
    this.moundDOM.style.height = "300px";

    this.map = createMap(this.moundDOM);
    this.hotsBus = dynamicHots(this.map);
    if (container) {
      this.mount(container);
    }
  }

  setTileType(type: TileType) {
    setBaseTileType(type);
    this.map.render();
  }

  addHots(items: HotData[]) {
    addHots(items);
    this.map.render();
  }

  clearHots() {
    clearHots();
    this.map.render();
  }

  setCenter(center: number[]) {
    this.map.getView().setCenter(center);
    console.log(center);
  }

  delHots(ids: HotData["id"][]) {
    delHots(ids);
    this.map.render();
  }

  getBound() {
    return this.map.getView().calculateExtent(this.map.getSize());
  }
  setBound(bound: number[]) {
    const extent = boundingExtent([
      [bound[0], bound[1]],
      [bound[2], bound[3]],
    ]);
    this.map.getView().fit(extent, {
      size: this.map.getSize(),
      padding: [0, 0, 0, 0], // 根据需要调整边距
    });
  }
  flyUserCenter(defaultCenter: number[]) {
    this.setCenter(defaultCenter);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        console.log("获取中心位置成功", pos);
        this.setCenter([pos.coords.longitude, pos.coords.latitude]);
      },
      (e) => {
        console.error(e);
        console.error("获取中心位置失败");
      },
      {
        enableHighAccuracy: false,
        timeout: 50000,
        maximumAge: 0,
      }
    );
  }

  render() {
    this.map.render();
  }

  mount(dom: HTMLDivElement) {
    dom.appendChild(this.moundDOM);
    this.moundDOM.style.width = "100%";
    this.moundDOM.style.height = "100%";
  }
}
