import * as KMap from "@/utils/ol-map/KMap";
import * as util from "@/common/ol_common.js";
import VectorLayer from "ol/layer/Vector.js";
import ScaleLine from "ol/control/ScaleLine";
import Overlay from "ol/Overlay";
import eventBus from "@/api/eventBus";
import Style from "ol/style/Style";
/**
 * @description 地图层对象
 */
class HomeMap {
  constructor() {
    let that = this;
    let vectorStyle = new KMap.VectorStyle();
    this.vectorStyle = vectorStyle;
    that.address = "";
  }

  initMap(location, target) {
    let level = 13;
    let coordinate = util.wktCastGeom(location).getFirstCoordinate();
    this.kmap = new KMap.Map(target, level, coordinate[0], coordinate[1], null, 7, 22);
    // this.addMapListen()
    // 添加比例尺控件
    const scaleLine = new ScaleLine({
      units: 'metric' // 可以选择 'imperial' 或 'metric'
    });
    this.kmap.addControl(scaleLine);
  }

  addMapListen() {
    let that = this
    // 监听地图点击事件
    // 创建弹窗图层
    this.popup = new Overlay({
      element: document.getElementById('popup'),
      positioning: 'right-center',
      offset: [10, 10],
    });
    this.kmap.map.addOverlay(this.popup);
    // 点击地图弹窗的关闭-销毁dom
    eventBus.on("map:destroyPopup", () => {
      that.popup.setPosition(undefined)
    })
    that.kmap.on('singleclick', function (event) {
      let hasFeature = false
      let feature = that.kmap.map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
        if (layer instanceof VectorLayer && layer.get("name") === "MockFarmLayer") {
          hasFeature = true
          let fs = feature.get("features");
          fs.length > 0 && eventBus.emit('MockFarmLayer:click', { sampleIdVal: fs[0].get("targetSampleId"), farmIdVal: fs[0].get("mockFarmId") });
        }
        if (layer instanceof VectorLayer && layer.get("name") === "pointLayer") {
          hasFeature = true
          eventBus.emit("chat:showTrackDialog", feature.get("url"))
        }
        return feature;
      });
      if (!hasFeature) {
        const currentLonLat = event.coordinate
        const params = {
          point: `POINT(${currentLonLat[0]} ${currentLonLat[1]})`
        }
        VE_API.mini_farm.weather_warning_land_check(params).then(async (res) => {
          await that.getLocation(currentLonLat)
          if (res.code == 0) {

            // 在这里可以获取feature的属性，并显示在弹窗中
            let content = '<div>' + res.data?.content + '</div>';
            document.getElementById('popup-title').innerHTML = that.address;
            document.getElementById('popup-content').innerHTML = content;
            that.popup.setPosition(event.coordinate); // 设置弹窗位置为点击位置
          } else {
            that.popup.setPosition(undefined)
          }
        })
      } else {
        that.popup.setPosition(undefined); // 如果没有点击到feature，则隐藏弹窗
      }
    })
  }

  //通过经纬度查处对应的地址
  async getLocation(point) {
    const locationParams = {
      key: "CZLBZ-LJICQ-R4A5J-BN62X-YXCRJ-GNBUT",
      location: `${point[1]},${point[0]}`,
    };
    await VE_API.warning.transformLocation(locationParams).then(({ result }) => {
      this.address = result.address_component.province + "-" + result.address_component.city + "-" + result.address_component.district
      console.log('address', this.address);
    });
  }

  //  设置地图中心点位
  setMapCenter(v, isPoint = true) {
    let arrayOfNumbers = [];
    const arrayOfStrings = v.split(",");
    arrayOfNumbers = [arrayOfStrings[1], arrayOfStrings[0]];
    this.kmap.map.getView().setCenter(arrayOfNumbers);
    if (!isPoint) return
    // this.locationLayer.source.clear();
    // let point = new Feature(new Point(arrayOfNumbers));
    // this.locationLayer.addFeature(point);
  }
}

export default HomeMap;
