import OLMap from "ol/Map";
import View from "ol/View";
import * as proj from "ol/proj";
import * as interaction from "ol/interaction";
import "ol/ol.css";
import "./css/KMap.css";
import Common from "./Common";
import VectorLayer from "./VectorLayer";
import WMTSLayer from "./WMTSLayer";
import XYZLayer from "./XYZLayer";
import config from "@/api/config.js";

/**
 * KMap.Map —— 与 feiniao-pc-vue 用法对齐的精简实现
 * new KMap.Map(target, level, lng, lat, projection, minZoom, maxZoom, ...)
 */
class Map {
  static Instance = null;

  constructor(id, zoomLevel, lng, lat, projection, minZoom, maxZoom) {
    this.defaultCursor = "default";
    Map.Instance = this;

    if (projection) {
      projection = proj.get(projection);
    }
    projection = projection || proj.get("EPSG:4326");

    let lnglat = [lng, lat];
    if (projection.getCode() === "EPSG:3857") {
      lnglat = proj.fromLonLat(lnglat);
    }

    Common.checkLngLat(lng, lat);

    this.view = new View({
      center: lnglat,
      zoom: zoomLevel,
      minZoom: minZoom || Common.ShowLevel[0],
      maxZoom: maxZoom || Common.ShowLevel[1],
      projection,
    });

    this.map = new OLMap({
      interactions: interaction.defaults().extend([new interaction.DragRotateAndZoom()]),
      target: id,
      layers: [],
      view: this.view,
      controls: [],
    });

    this.initBaseLayer(projection);
    this.initBusinessLayer();
  }

  /** 与 pc-vue 一致：img_wmts_mkt + cva_wmts_mkt + 默认 XYZ */
  async initBaseLayer(projection) {
    try {
      const getCfg = window.VE_API?.system?.getCfg;
      if (getCfg) {
        const img_wmts = await getCfg({ k: "img_wmts_mkt", resultType: "json" });
        const cva_wmts = await getCfg({ k: "cva_wmts_mkt", resultType: "json" });
        const imgData = typeof img_wmts?.data === "string" ? JSON.parse(img_wmts.data) : img_wmts?.data;
        const cvaData = typeof cva_wmts?.data === "string" ? JSON.parse(cva_wmts.data) : cva_wmts?.data;
        if (imgData?.url) {
          this.tdtImgLayer = new WMTSLayer(imgData, projection, this);
        }
        if (cvaData?.url) {
          this.cva_torLayer = new WMTSLayer(cvaData, projection, this);
        }
      }
    } catch (e) {
      console.warn("[KMap.Map] 底图 WMTS 配置加载失败", e);
    }

    const xyz2 = config.base_img_url3 + "map/lby/{z}/{x}/{y}.png";
    this.addXYZLayer(xyz2, { minZoom: 15, maxZoom: 22 });
  }

  addXYZLayer(url, options) {
    return new XYZLayer(url, options, 3, this);
  }

  initBusinessLayer() {
    const vm = this;
    const map = vm.map;
    vm.markerLayer = new VectorLayer("defaultMarkerLayer", 101);
    vm.polyLineLayer = new VectorLayer("defaultPolylineLayer", 101);
    vm.polygonLayer = new VectorLayer("defaultPolygonLayer", 1000);
    vm.labelLayer = new VectorLayer("defaultLabelLayer", 99);

    map.addLayer(vm.polygonLayer.layer);
    map.once("postrender", () => {
      map.addLayer(vm.markerLayer.layer);
      map.addLayer(vm.polyLineLayer.layer);
      map.addLayer(vm.labelLayer.layer);
    });
  }

  addLayer(layer) {
    this.map.addLayer(layer);
  }

  fit(geometryOrExtent, options) {
    this.view.fit(geometryOrExtent, options);
  }

  on(type, listener) {
    return this.map.on(type, listener);
  }

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

  destroy() {
    if (this.map) {
      this.map.setTarget(null);
      this.map = null;
    }
    if (Map.Instance === this) {
      Map.Instance = null;
    }
  }
}

export default Map;
