<template>
  <div class="div_content_map">
    <!-- <div>
      <el-input v-model="input_lat"></el-input>
      <el-input v-model="input_lon"></el-input>
      <el-button @click="showPosition"></el-button>
    </div> -->

    <!-- <div id="mouse-position"
         style="
        color: #fff;
        position: absolute;
        bottom:10px;
        right:10px;
        z-index: 10000000;
        width: 200px;
        line-height: 30px;
        background: rgba(0,0,0,0.5);
    "> 

  </div>-->

    <div class="div_map"
         id="map"
         ref="map">
    </div>
    <div id="popup"
         style="display: none;"
         class="ol-popup">
      <a href="#"
         id="popup-closer"
         class="ol-popup-closer"></a>
      <div id="popup-content"
           class="popup-content"></div>
    </div>
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile.js';
import XYZ from 'ol/source/XYZ.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Point from "ol/geom/Point.js";
import Feature from "ol/Feature.js";
import Overlay from 'ol/Overlay';
import { Select, DoubleClickZoom } from 'ol/interaction.js';
import { getCenter, boundingExtent } from 'ol/extent.js';
import { Circle as CircleStyle, Icon, Fill, Stroke, Style, Text } from 'ol/style.js';
import { altKeyOnly, click, pointerMove } from 'ol/events/condition';
import { getDistance } from 'ol/sphere';

import MousePosition from 'ol/control/MousePosition';
import { createStringXY } from 'ol/coordinate';
import { defaults as defaultControls } from 'ol/control';
import { mapGetters } from "vuex";
import { Loading } from 'element-ui'; //引入Loading服务

import { requestPost } from "@/js/dai/request";
var centerPointGlobal = [120.38945519, 36.0722275]


let loading;//加载动画

let map;
let mapView;
let gaodeMapLayer;//背景地图图层
let polygonLayer;//区域多边形标注图层
let polygonSource;//标注多边形

let polIconLayer; // 区域icon标注图层
let polIconSource; // icon

let iconLayer; // icon图层
let iconSource; // icon

let select;//选中标注

let iconTextsStyle = {
  textAlign: undefined,
  font: "18px Arial",
  //fontFamily: "Courier New, monospace",
  // fontWeight: "bold",
  text: '',
  backgroundFill: new Fill({
    color: 'rgba(0, 146, 238, 0.75)'
    // color: textColorArray[feature.values_.colorIndex]
  }),
  padding: [4, 10, 4, 10],
  //text: "变电站名称",
  fill: new Fill({ color: "#ffffff" }),
  // stroke: new Stroke({ color: "#ffffff", width: 3 }),
  offsetY: -30,
  offsetX: -50,
  overflow: true,
}

let polygonColorArray = [
  'rgba(210, 2, 2, 0.24)',
  'rgba(43, 231, 253, 0.25)',
  'rgba(183, 185, 0, 0.16)'
];

 //icon文字样式
let createTextStyle = function (feature) {
  
  if (iconTextsStyle) {
    let iconTextsStyles = { ...iconTextsStyle }
    iconTextsStyles.text = feature.values_ && feature.values_.name || feature.name
    return new Text({ ...iconTextsStyles })
  } else {
    return null
  }


}
//多边形标注样式
var polygonStyleFunction = (function () {
  return function (feature) {
    return new Style({
      fill: new Fill({
        // color: [255, 255, 255, 0.3]
        color: feature.values_.fillColor
      }),
      stroke: new Stroke({
        color: feature.values_.color,
        width: 2
      }),

      // text: createTextStyle(feature)
    });;
  };
})()



const vueGis = {
  name: 'HomeMap',
  data () {
    return {
      centerPoint: [],//中心点位置
      zoom: 14,//缩放范围：区14
      minZoom: 1,//最小缩放
      overlay: null,
      showPopup: false,
      mapInfo: {

      },

      polygonArray: [
        {
          agencyLevel: "grid",
          coordinates: "120.37421528296863,36.085017737014525,120.37551227771064,36.08181339174796,120.38108173804676,36.08303409283569,120.3852397566111,36.08318668276358,120.38539234391965,36.090816077003794,120.37410084117755,36.09096866431234,120.37421528296863,36.085017737014525",
          id: "2a278c0ceb863359d263fda7aabf6752",
          latitude: 36.072227,
          level: "grid",
          longitude: 120.389455,
          name: "第三网格",
        },
        {
          agencyLevel: "grid",
          coordinates: "120.38577111171519,36.095762169637716,120.38544318588274,36.08317796726519,120.39339541546589,36.08080049372144,120.40122467708379,36.08026761565102,120.40188052874869,36.08276805856732,120.39929810296697,36.086990119140545,120.39757648953199,36.08981849070392,120.39901116927089,36.0943274884915,120.3977404524482,36.096418022709926,120.38577111171519,36.095762169637716",
          id: "94227891bc4ad5f40cb95081761592d9",
          latitude: 36.072227,
          level: "grid",
          longitude: 120.389455,
          name: "南宁第二网格",
        },
        {
          agencyLevel: "grid",
          coordinates: "120.3736430792519,36.09505039184175,120.373948253869,36.09119754789451,120.38543049205646,36.09115940106737,120.38577381481036,36.0960803587938,120.3736430792519,36.09505039184175",
          id: "a772a325e022484ef53e4a7d679726f1",
          latitude: 36.072227,
          level: "grid",
          longitude: 120.389455,
          name: "南宁第一网格",
        },
      ],

      iconArrays: [

      ],
      // iconTextStyle: {},

      //policon图标样式
      polIconUrlArray: [
        'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20211116/a219130b6bc74b0b80b5ddb0fce0892a.png',
        'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20211116/a775d15e62374350b80e5cdf1912a4eb.png',
        'https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet/test/20211116/884efcf6d6b44224a7fda599dd1b14cb.png'
      ],
      //icon图标样式
      iconUrlArray: [],
      iconTextColor: '#ffffff',
      distanceMax: null,//显示的坐标距离中心点的范围                                                    

      input_lat: null,
      input_lon: null
    }
  },
  async mounted () {

  },
  methods: {
    showPosition () {
      let array = [this.input_lat, this.input_lon]
      map.getView().setCenter(array)
    },
    //加载地图:地图基本信息，多边形区域信息，多边形icon
    loadMap (mapInfo, polygonArray, polIconUrlArray, iconArrays, iconUrlArray, iconTextStyle, distanceMax) {
      this.mapInfo = mapInfo
      this.polygonArray = polygonArray
      this.polIconUrlArray = polIconUrlArray || []
      this.iconArrays = iconArrays
      this.iconUrlArray = iconUrlArray
      iconTextsStyle = iconTextStyle || iconTextsStyle
      this.distanceMax = distanceMax

      // iconArrays.forEach(item => {
      //   console.log(item.type, item.urlIndex, item.latitude, item.longitude)
      // });
      

      //初始化地图
      this.initMap()
      
      if (this.showPolIconLayer) {
        console.log('showPolIconLayer++++++++++++++++++++++', this.showPolIconLayer)
        //初始化多边形标注图层
        this.initPolIconLayer()
        //加载当前园区的标注
        // this.loadPolIcon()
      }
      if (this.showPolygonLayer) {
        //初始化多边形标注图层
        this.initPolygonLayer()
        //加载当前园区的标注
        this.loadPolygon()
      }
      

      if (this.showIconLayer) {
        //初始化icon图层
        this.initIconLayer()
        this.loadIcon()
      }

      if (this.isAddOpenlay) {
        //初始化icon图层
        this.addOverlay()
      }

      this.addMapClick()

    },

    //刷新地图
    async refreshMap (mapInfo, polygonArray, iconArrays) {
      this.mapInfo = mapInfo
      this.polygonArray  = []
      this.polygonArray = polygonArray
      this.iconArrays = iconArrays
      iconSource.clear()
      polygonSource.clear()
      polIconSource.clear()
      this.initPolIconLayer()
      
      if (this.showPolygonLayer) {
        this.initPolygonLayer()
        //加载当前园区的标注
        this.loadPolygon()
      }
      if (this.showPolIconLayer) {
        this.initIconLayer()
        //加载当前园区的标注
        // this.loadPolIcon()
      }

      if (this.showIconLayer) {

        this.loadIcon()
      }
      this.setMapLocation()
      // gaodeMapLayer.getSource().changed()
      
    },

    //加载区域多边形
    loadPolygon () {
      polygonSource.clear()//清空多边形标注
      // iconSource.clear()
      let featureData = []//多边形数据数据

      if (this.polygonArray && this.polygonArray.length > 0) {//判断是否存在下级标注
        let oneData = {}

        this.polygonArray.forEach(polygonItem => {

          if (polygonItem.coordinates && polygonItem.coordinates !== '') {//如果有坐标

            oneData = {
              type: 'Feature',
        
              properties: { ...polygonItem },
              geometry: {
                type: 'Polygon',
                coordinates: [],
              },
            }
            let coorArray = polygonItem.coordinates.split(',')//坐标数组

            let itemArray = []//单个点位的[lon,lat]，数组
            let tempPolygonArray = []//整个多边形的[[lon,lat],[lon,lat],[lon,lat]]数组

            coorArray.forEach((item, index) => {
              itemArray.push(item)
              if (index % 2 == 0) {//偶

              } else {//奇
                tempPolygonArray.push(itemArray)
                itemArray = []
              }

            });
            oneData.geometry.coordinates.push(tempPolygonArray)
            featureData.push(oneData)
          }
        });
      }

      if (featureData && featureData.length > 0) {
        var geojsonObject = {
          'type': 'FeatureCollection',
          'features': featureData
        };
        let feature = (new GeoJSON()).readFeatures(geojsonObject)

        polygonSource.addFeatures(feature)

        if (this.showPolIconLayer) {
          this.loadPolIcon(feature)
        }
        

      }

    },

    //加载区域多边形的icon
    loadPolIcon (feature) {
      polIconSource.clear()
      let polyIconFeatures = [];
      console.log('feature-----', feature)
      feature.forEach(oneIcon => {

        var extent = boundingExtent(oneIcon.getGeometry().getCoordinates()[0]); //获取一个坐标数组的边界，格式为[minx,miny,maxx,maxy]
        // var center = getCenter(extent);   //获取边界区域的中心位置
        //添加标注
        let x = (parseFloat(extent[0]) + parseFloat(extent[2])) / 2
        let y = (parseFloat(extent[1]) + parseFloat(extent[3])) / 2

        let polyIcon = new Feature({
          geometry: new Point([x, y]),
          id: oneIcon.id_,
          properties: {
            type: "icon",
            id: oneIcon.id_
          }
        });
        // console.log('oneIcon----', oneIcon)
        let polyIconStyle = new Style({
          image: new Icon({
            // anchor: [0.5, 0.5],
            // imgSize: [32, 32],
            scale: this.areaScale,
            src: this.polIconUrlArray[0]
          }),
          text: createTextStyle(oneIcon)
        });

        polyIcon.setStyle(polyIconStyle);
        polyIconFeatures.push(polyIcon);

      });
      polIconSource.addFeatures(polyIconFeatures);
    },

    //加载icon图标
    loadIcon () {
      iconSource.clear()//清空多边形标注
      if (this.iconArrays && this.iconArrays.length > 0) {

        let iconFeatures = [];

        this.iconArrays.forEach((oneIcon, index) => {
          //添加标注

          let iconItem = new Feature({
            geometry: new Point([oneIcon.longitude, oneIcon.latitude]),
            id: oneIcon.id,
            properties: {
              type: "icon",
              info: { ...oneIcon }
            }
          });
          let iconStyle = new Style({
            image: new Icon({
              // anchor: [0.5, 0.5],
              // imgSize: [32, 32],
              // scale: 0.5,
              src: oneIcon.urlIndex && this.iconUrlArray[oneIcon.urlIndex] || this.iconUrlArray[0]
            }),
            // text: createTextStyle(oneIcon)
          });

          iconItem.setStyle(iconStyle);

          if (this.distanceMax) {
            if (this.computedDistance(oneIcon.longitude, oneIcon.latitude, this.distanceMax)) {
              iconFeatures.push(iconItem);
            }
          } else {
            iconFeatures.push(iconItem);
          }




        });

        iconSource.addFeatures(iconFeatures);
      }
    },


    //计算和中心点距离
    computedDistance (lon, lat, max) {
      let c1 = [2]; c1[0] = lon; c1[1] = lat;
      let distance = getDistance(this.centerPoint, c1);
      // console.log(distance)
      return (distance < max || distance === max)

      // debugger
      //   return 
      // var wgs84Sphere = new ol.Sphere(6378137); 
      // wgs84Sphere.haversineDistance([120.21592590991689, 30.210793016606],[120.21670777384473, 30.211168525868086]);
    },

    //初始化地图
    initMap () {
      this.firstCentermap()
      gaodeMapLayer = new TileLayer({
        title: "地图",
        source: new XYZ({
          //指定url瓦片
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          wrapX: true//x方向平铺，也可以选择false
        }),
        zIndex: 20
      });

      mapView = new View({
        //中心点坐标
        center: this.centerPoint,
        // projection: 'EPSG:3857',
        projection: 'EPSG:4326',
        zoom: this.zoom,
        minZoom: this.minZoom
      })

      //初始化map和地图底图
      //创建地图容器
      map = new Map({

        layers: [gaodeMapLayer],
        //加载瓦片图层数据
        view: mapView,
        target: 'map'
        //目标加载到map中
      })

      var mousePositionControl = new MousePosition({
        coordinateFormat: createStringXY(6),//获取位置
        projection: 'EPSG:4326',
        className: 'custom-mouse-position',
        target: document.getElementById('mouse-position'), //将位置数据放到那里
        undefinedHTML: '&nbsp'
      });
      map.addControl(mousePositionControl);


      //去除双击放大效果
      const dblClickInteraction = map
        .getInteractions()
        .getArray()
        .find(interaction => {
          return interaction instanceof DoubleClickZoom;
        });
      map.removeInteraction(dblClickInteraction);

    },
    //设置地图定位的中心点和缩放级别
    setMapLocation () {
      if (!this.zoom) {
        this.setZoom(this.mapInfo.agencyLevel)
      }
      this.centerPoint = []


      //如果存在中心点（返回时赋值）
      if (this.center && this.center.length > 0) {
        this.centerPoint = this.center
        this.centerFlag = 'point'
        this.center = []

      } else if (polygonLayer.getSource().getFeatures()[0]) {//如果是初次进入,存在下级组织
        this.centerFlag = 'flag_polygon'

      } else if (this.mapInfo.longitude && this.mapInfo.latitude) {
        this.centerPoint.push(this.mapInfo.longitude)
        this.centerPoint.push(this.mapInfo.latitude)
        this.centerFlag = 'point'

      } else {
        this.centerPoint = centerPointGlobal
        this.centerFlag = 'point'
      }
      // debugger
      if (this.centerFlag === 'flag_parent') {
        let parentFeatures = parentLayer.getSource().getFeatures()[0]
        let polygon = parentFeatures.getGeometry();
        map.getView().fit(polygon, map.getSize());
        this.zoom = map.getView().getZoom() - 1

      } else if (this.centerFlag === 'flag_polygon') {
        let polygonFeatures = polygonLayer.getSource().getFeatures()[0]
        let polygon = polygonFeatures.getGeometry();
        map.getView().fit(polygon, map.getSize());
        this.zoom = map.getView().getZoom() - 1

      } else {
        mapView.setCenter(this.centerPoint);

      }
      mapView.setZoom(this.zoom);

      
    },
    firstCentermap() {
      if (this.mapInfo.longitude && this.mapInfo.latitude) {
        this.centerPoint = []
        this.centerPoint.push(this.mapInfo.longitude)
        this.centerPoint.push(this.mapInfo.latitude)
      } else {

        this.centerPoint = centerPointGlobal
      }

      this.setZoom(this.mapInfo.agencyLevel)
    },

    //根据组织层级设置缩放级别
    setZoom (level) {
      if (level === 'district') {
        this.zoom = 11
      } else if (level === 'street') {
        this.zoom = 12
      } else if (level === 'community') {
        this.zoom = 13
      }

    },

    //初始化多边形标注图层
    initPolygonLayer () {
      polygonSource = new VectorSource({
        //features: (new GeoJSON()).readFeatures(geojsonObject)
      });

      polygonLayer = new VectorLayer({
        source: polygonSource,
        style: polygonStyleFunction,
        zIndex: 50
      });
      let that = this
      //选中多边形后的样式
      var overlayStyle = (function () {

        return function (feature) {
          var styles = {};
          styles['Polygon'] = [
            new Style({
              stroke: new Stroke({
                color: '#ec9000',
                width: 2
              })
            }),

            new Style({
              fill: new Fill({
                color: 'rgba(0, 0, 255, 0.1)'
              })
            }),
            new Style({
              text: createTextStyle(feature)
            })
          ];
          styles['MultiPolygon'] = styles['Polygon'];
          return styles[feature.getGeometry().getType()];
        };
      })();

      select = new Select({
        style: overlayStyle
      });


      map.addLayer(polygonLayer)
      map.addInteraction(select);


    },

    //初始化多边形icon图层
    initPolIconLayer () {
      polIconSource = new VectorSource({
        //features: (new GeoJSON()).readFeatures(geojsonObject)
      });

      polIconLayer = new VectorLayer({
        source: polIconSource,
        zIndex: 70
      });

      map.addLayer(polIconLayer);

    },

    //初始化icon图层
    initIconLayer () {
      iconSource = new VectorSource({
        //features: (new GeoJSON()).readFeatures(geojsonObject)
      });

      iconLayer = new VectorLayer({
        source: iconSource,
        zIndex: 90
      });

      map.addLayer(iconLayer);
      // select = new Select({ condition: click, });

      // map.addInteraction(select);

      // select.on('select', e => {
      //   this.$emit('clickFeature', e)
      // });
    },

    //添加覆盖层
    addOverlay () {
      // 使用变量存储弹窗所需的 DOM 对象
      var container = document.getElementById("popup");
      var closer = document.getElementById("popup-closer");
      var content = document.getElementById("popup-content");

      // 创建一个弹窗 Overlay 对象
      this.overlay = new Overlay({
        element: container, //绑定 Overlay 对象和 DOM 对象的
        autoPan: true, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
        autoPanAnimation: {
          duration: 250 //自动平移效果的动画时间 9毫秒
        },
        zIndex: 100
      });
      // 将弹窗添加到 map 地图中
      map.addOverlay(this.overlay);
      let _that = this;

      /**
       * 为弹窗添加一个响应关闭的函数
       */
      closer.onclick = function () {
        _that.overlay.setPosition(undefined);
        closer.blur();
        return false;
      };
    },

    //注册地图点击事件
    addMapClick () {
      let _that = this


      map.on("click", function (evt) {
        const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
          return feature;
        });
        if (feature) {

          // console.log(feature)
          if (_that.clickType === 'back') {

            _that.$emit('clickFeature', feature)


          } else if (_that.clickType === 'popup') {
            _that.$emit('clickFeature', feature)

          } else {
            console.log('此处没有标注')
          }

        }

      });
    },

    handleShowPopup (showData, coordinate) {
      console.log(this.overlay.getElement())
      this.overlay.getElement().style.display = 'block'
      this.overlay.getElement().parentNode.style.display = 'block'
      this.overlay.getElement().parentNode.parentNode.style.display = 'block'
      var content = document.getElementById("popup-content");

      content.innerHTML = showData;
      this.overlay.setPosition(coordinate); //把 overlay 显示到指定的 x,y坐标
    },

    //取随机数
    getRndBetween (lowerLimit, upperLimit) {
      return Math.floor(Math.random() * (upperLimit - lowerLimit + 1)) + lowerLimit;
    },

    //开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, //是否锁定
        text: '正在加载……', //加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' //背景颜色
      });

    },

    //结束加载动画
    endLoading () {
      //clearTimeout(timer);
      if (loading) {
        loading.close();
      }
    },
  },
  props: {
    //是否显示多边形图层
    showPolygonLayer: {
      type: Boolean,
      default: false
    },
    //是否显示多边形icon图层
    showPolIconLayer: {
      type: Boolean,
      default: false
    },

    //是否显示标注
    showIconLayer: {
      type: Boolean,
      default: false
    },
    //是否添加弹出框图层
    isAddOpenlay: {
      type: Boolean,
      default: false
    },

    //点击地图事件类型,back:返回，popup:弹出层
    clickType: {
      type: String,
      default: 'back'
    },
    areaScale: {
      type: Number,
      default: 0.5
    }

  },
  computed: {

    mapHeight () {
      return this.clientHeight - 120;

    },

    ...mapGetters(["clientHeight"])

  },
  components: {},
}
export default vueGis;
</script>

<style
  lang="scss"
  src="@/assets/scss/modules/visual/basicInfoMain.scss"
  scoped
></style>

<style lang="scss" >
.div_content_map {
  .ol-viewport {
    border-radius: 5px;
  }
  .div_map {
    box-sizing: border-box;
    width: 100%;
    // padding: 10px 5px 13px;
    // margin-top: 8px;
    height: 100%;
    color: #fff;
  }
}
.ol-overlaycontainer-stopevent {
  display: none;
}
.ol-popup {
  position: absolute;
  background-color: #1257c9;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #1257c9;
  bottom: 12px;
  left: -50px;
  text-align: left;
}
.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: 1257c9;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #1257c9;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}
.popup-content {
  width: 300px;
}
.ol-popup-closer:after {
  content: "✖";
  color: rgba(1, 17, 104, 1);
}
</style>   