import * as KMap from "@/utils/ol-map/KMap";
import config from "@/api/config";
import { wktCastGeom, newAreaFeature } from "@/common/ol_common";

/** 与设备选区地图默认中心一致 */
export const DEFAULT_LOCATION = "POINT(113.61448114737868 23.585550924763083)";

/** 右侧权属列表面板宽度，fit 时预留 */
const PANEL_FIT_PADDING = [40, 460, 40, 40];

/**
 * 人员管理页地图
 * 创建方式对齐 device/areaSelectMap：new KMap.Map(...)
 */
export default class PersonnelMap {
  constructor() {
    const vectorStyle = new KMap.VectorStyle();
    this.vectorStyle = vectorStyle;
    this.kmap = null;

    this.blueRegionLayer = new KMap.VectorLayer("blueRegionLayer", 99999, {
      minZoom: 1,
      maxZoom: 22,
      style: () =>
        vectorStyle.getPolygonStyle(
          "rgba(0, 0, 0, 0.45)",
          "rgba(255, 212, 137, 0.85)",
          1.5
        ),
    });
  }

  /**
   * @param {HTMLElement} target
   * @param {string} location WKT
   */
  init(target, location = DEFAULT_LOCATION) {
    this.destroy();

    const level = 16;
    const coordinate = wktCastGeom(location).getFirstCoordinate();

    this.kmap = new KMap.Map(
      target,
      level,
      coordinate[0],
      coordinate[1],
      null,
      8,
      22,
      "vec",
      true,
      true
    );

    this.kmap.addLayer(this.blueRegionLayer.layer);

    const xyz = config.base_img_url + "map/lby/{z}/{x}/{y}.png";
    this.kmap.addXYZLayer(xyz, { minZoom: 8, maxZoom: 22 }, 2);

    setTimeout(() => this.updateSize(), 80);
  }

  /**
   * @param {Array} list 蓝区列表
   */
  setRegions(list = []) {
    if (!this.blueRegionLayer?.source) return;
    this.blueRegionLayer.source.clear();

    for (const item of list) {
      const row = {
        ...item,
        wkt: item.geom || item.wkt,
        id: item.blueZoneCode ?? item.id,
        name:
          item.name ||
          item.regionName ||
          item.blueZoneName ||
          String(item.blueZoneCode ?? item.id),
      };
      if (!row.wkt) continue;

      const feature = newAreaFeature({ ...row, geom: row.wkt });
      feature.set("name", row.name);
      this.blueRegionLayer.addFeature(feature);
    }

    this.fitToRegions();
  }

  fitToRegions(padding = PANEL_FIT_PADDING) {
    const extent = this.blueRegionLayer?.source?.getExtent?.();
    if (!extent || !isFinite(extent[0]) || !this.kmap) return;
    this.kmap.fit(extent, { padding, duration: 300, maxZoom: 18 });
  }

  updateSize() {
    this.kmap?.updateSize?.() || this.kmap?.map?.updateSize?.();
  }

  destroy() {
    if (this.blueRegionLayer?.source) {
      this.blueRegionLayer.source.clear();
    }
    this.kmap?.destroy?.();
    this.kmap = null;
  }
}
