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

/** 与 workDetail/areaMap 默认中心一致 */
const DEFAULT_LOCATION = "POINT(113.61448114737868 23.585550924763083)";

/**
 * 执行区域选择地图
 * 创建方式对齐 workDetail/areaMap：new KMap.Map(...)
 */
export default class AreaSelectMap {
  constructor() {
    const that = this;
    const vectorStyle = new KMap.VectorStyle();
    this.vectorStyle = vectorStyle;
    this.kmap = null;
    this.clickKey = null;

    this.blueRegionLayer = new KMap.VectorLayer("blueRegionLayer", 99999, {
      minZoom: 1,
      maxZoom: 22,
      style: (f) => {
        if (f.get("selected")) {
          return that.vectorStyle.getPolygonStyle(
            "rgba(251, 142, 51, 0.35)",
            "#FB8E33",
            2.5
          );
        }
        return that.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();

    // 与 areaMap.js 一致
    this.kmap = new KMap.Map(
      target,
      level,
      coordinate[0],
      coordinate[1],
      null,
      1,
      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);

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

  addMapSingleClick() {
    const that = this;
    this.clickKey = this.kmap.on("singleclick", (evt) => {
      that.kmap.map.forEachFeatureAtPixel(evt.pixel, (feature, layer) => {
        if (layer === that.blueRegionLayer.layer) {
          feature.set("selected", !feature.get("selected"));
        }
      });
    });
  }

  /**
   * @param {Array} list
   * @param {Array<string|number>} selectedIds
   */
  setRegions(list = [], selectedIds = []) {
    if (!this.blueRegionLayer?.source) return;
    this.blueRegionLayer.source.clear();

    const selectedSet = new Set((selectedIds || []).map((id) => String(id)));

    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;

      // ol_common.newAreaFeature 读 geom 字段
      const feature = newAreaFeature({ ...row, geom: row.wkt });
      feature.set("selected", selectedSet.has(String(row.id)));
      feature.set("name", row.name);
      this.blueRegionLayer.addFeature(feature);
    }

    this.fitToRegions();
  }

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

  getSelected() {
    if (!this.blueRegionLayer?.source) return [];
    return this.blueRegionLayer.source
      .getFeatures()
      .filter((f) => f.get("selected"))
      .map((f) => ({
        id: f.get("id") ?? f.getId(),
        name: f.get("name"),
        raw: f.getProperties(),
      }));
  }

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

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