import config from "@/api/config.js";
import * as KMap from "@/utils/ol-map/KMap";
import * as util from "@/common/ol_common.js";
import Point from "ol/geom/Point.js";
import Feature from "ol/Feature";
import VectorLayer from "ol/layer/Vector.js";
import WKT from "ol/format/WKT.js";
import ScaleLine from "ol/control/ScaleLine";
import { useRouter } from "vue-router";
import {unByKey} from "ol/Observable";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import {Cluster, Vector as VectorSource} from "ol/source";
import {newPoint} from "../zhgl/map";

/**
 * @description 地图层对象
 */
class SamplePointLayer {
  constructor(map, farm, region) {
    let that = this;
    this.farmId = farm.id
    this.regionId = region.id
    let vectorStyle = new KMap.VectorStyle();
    this.vectorStyle = vectorStyle;
    this.clusterSource = new Cluster({
      distance: 15,
      minDistance: 60,
    });

    this.treeClusterLayer = new KMap.VectorLayer("tree-cluster",999,{
      minZoom:15,
      source:this.clusterSource,
      style:(f)=> this.getStyle(f)})
    map.addLayer(this.treeClusterLayer.layer)
    this.initData(this.farmId, this.regionId)
  }
  getIconStyle(feature){
    let style = new Style({
      image: new Icon({
        src: feature.get('icon'),
        scale:1,
      })
    });
    return style
  }
  //多点的过滤方法
  manyFeatureFilter(features){
    let res = features[0]
    if(features.length == 1){
      return res
    }
    for(let item of features){
      res = res.get('status') > item.get('status') ? res : item
    }
    return res;
  }
  //得到点样式
  getStyle(feature){
    feature = this.manyFeatureFilter(feature.get('features'))
    return this.getIconStyle(feature)
  }

  initData(farmId, regionId){
    let that = this
    VE_API.sample.list({farmId,regionId}).then(({data})=>{
      let features = []
      for(let item of data){
        that.getIcon(item)
        let point = newPoint(item);
        features.push(point)
      }
      const source = new VectorSource({
        features: features,
      });
      that.clusterSource.setSource(source)
    })
  }

  getIcon(item){
    let imgSrc = require('@/assets/status/status_xfdw.png')
    if(item.status == 1){
      imgSrc = require('@/assets/status/status_dfh.png')
    }
    if(item.status == 2){
      imgSrc = require('@/assets/status/status_szyc.png')
    }
    if(item.status == 3){
      imgSrc = require('@/assets/status/status_bcyc.png')
    }
    item["icon"] = imgSrc
  }

  reset(farm, region){
    this.clearCluster()
    this.initData(farm.id, region.id)
  }

  // 清除聚合图层，解除绑定
  clearCluster() {
    if (this.treeClusterLayer) {
      this.treeClusterLayer.layer.getSource().getSource().clear()
    }
  }
}

export default SamplePointLayer;
