import config from "@/api/config.js";
import * as KMap from "@/utils/ol-map/KMap";
import * as util from "@/common/ol_common.js";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import VectorLayer from "ol/layer/Vector.js";
import WKT from "ol/format/WKT.js";
import { reactive } from "vue";
import Point from "ol/geom/Point.js";
import Feature from "ol/Feature";
import { newPoint } from "@/utils/map.js";
import { Fill, Text } from "ol/style";
import { getArea } from "ol/sphere.js";
import * as proj from "ol/proj";
import proj4 from "proj4";
import { register } from "ol/proj/proj4";
import GeometryCollection from 'ol/geom/GeometryCollection.js';
proj4.defs(
  "EPSG:38572",
  "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs"
);
register(proj4);
export let mapData = reactive({
  isEdit: false,
  isEditArea: false,
  curPointData: {},
  point: null,
  selectPointArr: [],
  isPointHide: null,
});

function resetMapData(){
  mapData.isEdit= false
  mapData.isEditArea= false
  mapData.curPointData= {}
  mapData.point= null
  mapData.selectPointArr= []
  mapData.isPointHide= null
}

/**
 * @description 地图层对象
 */
class AuthenticMap {
  constructor() {
    let that = this;
    let vectorStyle = new KMap.VectorStyle();
    this.vectorStyle = vectorStyle;
    // 位置图标
    this.clickPointLayer = new KMap.VectorLayer("clickPointLayer", 9999, {
      style: (f) => {
        const style1 = new Style({
          image: new Icon({
            src: require(`@/assets/images/map/${f.get("icon")}-icon.png`),
            scale: 0.45,
          }),
        });
        const style2 = new Style({
          text: new Text({
            font: "16px sans-serif",
            text: f.get("masterName"),
            offsetY: -40,
            padding: [4, 3, 2, 106],
            fill: new Fill({ color: "#fff" }), // 字体颜色
          }),
        });
        const style3 = new Style({
          image: new Icon({
            src: require(`@/assets/images/map/${f.get("iconBg")}.png`),
            scale: 0.45,
            displacement: [0, 90],
          }),
        });
        return [style1, style2, style3];
      },
    });

    this.locationLayer = new KMap.VectorLayer("locationLayer", 9999, {
      style: () => {
        return new Style({
          image: new Icon({
            src: require("@/assets/images/map/location.png"),
            scale: 0.45,
          }),
        });
      },
    });

    // 存储绘制的地块特征
    // this.drawnFeatures = [];
  }

  initMap(location, target) {
    let level = 16;
    let coordinate = util.wktCastGeom(location).getFirstCoordinate();
    this.kmap = new KMap.Map(
      target,
      level,
      coordinate[0],
      coordinate[1],
      null,
      6,
      22
    );
    this.kmap.initDraw((e) => {
      if (e.type === "drawend") {
        mapData.isEdit = true;
        mapData.point = e.feature;
      }
    });
    this.kmap.modifyDraw((e) => {
      mapData.isEditArea = false;
      mapData.isEditArea = true;
    });
    this.kmap.addLayer(this.clickPointLayer.layer);
    this.kmap.addLayer(this.locationLayer.layer);
    this.addMapSingerClick();
  }



  fit(geometriesWkt){
    let geometries = []
    let f = new WKT();
    for(let wkt of geometriesWkt){
      geometries.push(f.readGeometry(wkt))
    }
    let extent = new GeometryCollection(geometries).getExtent()
    this.kmap.fit(extent)
  }

  undoLastDraw() {
    const features = this.kmap.getLayerFeatures();
    features.forEach((feature) => {
      console.log("feature", feature, mapData.point);
      const coord = feature.getGeometry().getCoordinates()[0];
    });
    // this.kmap.setFeatureCursor("move")
    // const lastFeature = this.drawnFeatures.pop();
    // if (lastFeature) {
    //   // const features = this.kmap.getLayerFeatures();
    //   console.log("this", this.kmap.polygonLayer.source);
    //   this.kmap.polygonLayer.source.removeFeature(lastFeature);
    //   // this.kmap.getLayers().getArray()[1].getSource().removeFeature(lastFeature);
    // }
  }

  //      取消地块
  cancelDraw() {
    this.kmap.polygonLayer.source.removeFeature(mapData.point);
  }

  //   添加点位
  addPoint(points) {
    const arrPoints = [];
    if (points && points.length > 0) {
      points.forEach((item) => {
        let f = newPoint({ ...item, icon: "point", iconBg: "name-bg" }, "point");
        arrPoints.push(f);
      });
      this.clickPointLayer.source.addFeatures(arrPoints);
    }
  }

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

  // 开始勾画
  startDraw() {
    this.kmap.setDefaultCursor("crosshair");
    this.kmap.startDraw();
  }
  //结束勾画
  endDraw() {
    this.kmap.endDraw();
    this.kmap.endModify();
  }

  // 开始编辑
  startModify() {
    this.kmap.startModify();
    mapData.point.set("icon", "point-act");
  }
  //结束编辑
  endModify() {
    this.kmap.endModify();
  }

  // 清空单个数据
  clearMapData(name, val, id) {
    name && (mapData[name] = val);
    resetMapData()
    this.clickPointLayer.source.forEachFeature((feature) => {
      if (feature.get("id") === id) {
        feature.set("icon", "point");
        feature.set("iconBg", "name-bg");
      }
    });
    const points = this.kmap.getLayerFeatures();
    points.forEach((feature) => {
      if (feature.get("id") === id) {
        feature.set("icon", "point");
        this.kmap.polygonStyle(feature);
        mapData.isPointHide = feature;
      }
    });
    mapData.selectPointArr = [];
  }
  //全选
  allSelect(ids){
    let arr = []
    this.clickPointLayer.source.forEachFeature((feature) => {
      if(!ids || ids.findIndex((id)=> id == feature.get('id')) > -1){
        feature.set("icon", "point-act");
        feature.set("iconBg", "name-act-bg");
      }
    });
    const points = this.kmap.getLayerFeatures();
    points.forEach((feature) => {
      if(!ids || ids.findIndex((id)=> id == feature.get('id')) > -1) {
        feature.set("icon", "point-act");
        this.kmap.polygonStyle(feature);
        mapData.isPointHide = feature;
        arr.push(feature)
      }
    });
    mapData.selectPointArr = arr;
  }
  //no全选
  allUnSelect(){
    this.clickPointLayer.source.forEachFeature((feature) => {
        feature.set("icon", "point");
        feature.set("iconBg", "name-bg");
    });
    const points = this.kmap.getLayerFeatures();
    points.forEach((feature) => {
        feature.set("icon", "point");
        this.kmap.polygonStyle(feature);
        mapData.isPointHide = feature;
    });
    mapData.selectPointArr = [];
  }
  // 地图点击事件
  addMapSingerClick() {
    let that = this;
    that.kmap.on("singleclick", (evt) => {
      let num = 0;
      that.kmap.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
        // 点击的图层是否是VectorLayer
        if (
          layer instanceof VectorLayer &&
          (layer.get("name") === "clickPointLayer" ||
            layer.get("name") === "defaultPolygonLayer")
        ) {
          // 每次点击，只走一遍该方法
          num = num + 1;
          if (num === 1) {
            that.getSelectPointArr(feature.get("id"));
            that.kmap.endDraw();
          }
        }
      });
    });
  }

  setPoint(name) {
    const arr = mapData.selectPointArr.filter(
      (item) => item.values_.icon === "point-act"
    );
    if (arr.length > 0) {
      mapData.point = arr[0];
      mapData.point.set("icon", name);
      mapData.isPointHide.set("icon", name);
      mapData.point.set("iconBg", "name-bg");
    }
    if (arr.length === 1) {
      mapData.selectPointArr = [];
    }
  }

  //添加地块
  setAreaGeometry(geometryArr) {
    let that = this;
    geometryArr.map((item) => {
      item.icon = "point";
      item.iconHide = "false";
      that.kmap.setLayerWkt(item.featureWkt, item);
    });
  }

  // 移除点的功能
  removePoint() {
    // console.log('getDefaultCursor',this.kmap.getDefaultCursor());
    // this.kmap.setDefaultCursor('text')
    // console.log('getDefaultCursor',this.kmap.getDefaultCursor());
    // var source = this.kmap.setDefaultCursor('move');
    // console.log('source',this.kmap);
    // var source = this.kmap.polygonLayer.source
    // console.log('mapData.curPointData',mapData.curPointData);
    // source.removeFeature(mapData.curPointData)
    // source.removeFeature(pointFeature);
    // this.kmap.endDraw1()
  }

  //   获取所有选中点位
  getSelectPointArr(id) {
    const arr = [];
    this.clickPointLayer.source.forEachFeature((feature) => {
      if (feature.get("id") === id) {
        // 修改当前点位高亮
        const icon = feature.get("icon") === "point" ? "point-act" : "point";
        const iconBg =
          feature.get("iconBg") === "name-bg" ? "name-act-bg" : "name-bg";
        feature.set("icon", icon);
        feature.set("iconBg", iconBg);
        mapData.point = feature;
        mapData.curPointData = feature.values_;
      }
      if (feature.get("icon") === "point-act") {
        arr.push(feature);
      }
    });
    const points = this.kmap.getLayerFeatures();
    points.forEach((feature) => {
      if (feature.get("id") === id) {
        const icon = feature.get("icon") === "point" ? "point-act" : "point";
        feature.set("icon", icon);
        this.kmap.polygonStyle(feature);
        mapData.isPointHide = feature;
      }
    });
    mapData.selectPointArr = arr;
  }

  hidePoint() {
    const feature = mapData.isPointHide;
    feature.set("iconHide", "true");
    this.kmap.polygonStyle(feature);
  }

  clearLayer() {
    this.clickPointLayer.source.clear();
    this.kmap.polygonLayer.source.clear();
  }

  addLayer() {
    this.kmap.addLayer(this.kmap.polygonLayer.layer);
    this.kmap.addLayer(this.clickPointLayer.layer);
  }

  //获取地块信息
  getAreaGeometry() {
    const features = this.kmap.getLayerFeatures();
    let geometryArr = [];
    let area = 0;
    // 获取图层上的Polygon，转成geoJson用于回显
    features.forEach((item) => {
      geometryArr.push({ featureWkt: new WKT().writeFeature(item) });
      let geom = item.getGeometry().clone();
      geom.transform(proj.get("EPSG:4326"), proj.get("EPSG:38572"));
      let areaItem = getArea(geom);
      area = (areaItem + areaItem / 2) / 1000;
    });
    return { geometryArr, area: area.toFixed(2) };
  }

  /**
   address
   farmName
   masterName
   masterTel
   speciesTypeName
   ""
   * @param form
   */
  search(form){
    const points = this.kmap.getLayerFeatures();
    let arr = []
    let geomWkt = []
    points.forEach((feature) => {
      let condition = []
      if(form.address != ''){
        condition.push(feature.get("address").includes(form.address))
      }
      if(form.farmName != ''){
        condition.push(feature.get("farmName").includes(form.farmName))
      }
      if(form.masterName != ''){
        const text = feature.get("masterName")
        if(text!==form.masterName) return
        condition.push(feature.get("masterName").includes(form.masterName))
      }
      if(form.masterTel != ''){
        const text = feature.get("masterTel")
        if(text!==form.masterTel) return
        condition.push(feature.get("masterTel").includes(form.masterTel))
      }
      if(form.speciesTypeName != ''){
        const text = feature.get("speciesTypeName")
        if(text!==form.speciesTypeName) return
        condition.push(feature.get("speciesTypeName").includes(form.speciesTypeName))
      }
      let b = false
      for(let item of condition){
        if(item){
          b = true
        }else{
          b = false
          break
        }
      }
      if(b){
        arr.push(feature.get("id"))
        geomWkt.push(new WKT().writeGeometry(feature.getGeometry()))
      }
    });
    this.allUnSelect()
    this.allSelect(arr)
    if(geomWkt.length>0){
      this.fit(geomWkt)
    }
  }
}

export default AuthenticMap;
