<template>
  <div style="position: relative">

    <div class="div_map"
         id="map"
         ref="map">
      <!-- <div id="map"
             class="map"></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 { defaults as defaultInteractions, 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 { mapGetters } from "vuex";
import { Loading } from 'element-ui'; //引入Loading服务
import { requestPost } from "@/js/dai/request";



let loading;//加载动画

let map;
let mapView;
let gaodeMapLayer;//背景地图图层
let polygonLayer;//区域标注图层
let iconLayer; // icon标注图层
let iconSource; // icon
let polygonSource;//标注多边形
let select;//选中标注


//url图标

let iconUrlArray = [
  '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'
];
let textColorArray = [
  'rgba(236, 69, 4, 0.66)',
  'rgba(0, 146, 238, 0.75)',
  'rgba(238, 151, 0, 0.8)'
];
let polygonColorArray = [
  'rgba(210, 2, 2, 0.24)',
  'rgba(43, 231, 253, 0.25)',
  'rgba(183, 185, 0, 0.16)'
];
//变电站标注的文字样式
var createTextStyle = function (feature) {
  return new Text({
    textAlign: undefined,
    font: "18px Arial",
    //fontFamily: "Courier New, monospace",
    // fontWeight: "bold",
    text: feature.values_.name,
    backgroundFill: new Fill({
      // color: 'rgba(0, 146, 238, 0.75)'
      color: textColorArray[feature.values_.index - 1]
    }),
    padding: [4, 10, 4, 10],
    //text: "变电站名称",
    fill: new Fill({ color: "#ffffff" }),
    // stroke: new Stroke({ color: "#ffffff", width: 3 }),
    offsetY: -30,
    offsetX: -50,
    overflow: true,
  });
};

//变电站标注样式

var polygonStyleFunction = (function () {
  return function (feature) {
    return new Style({
      fill: new Fill({
        // color: [255, 255, 255, 0.3]
        color: polygonColorArray[feature.values_.index - 1]
      }),
      stroke: new Stroke({
        color: polygonColorArray[feature.values_.index - 1],
        width: 3
      }),

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

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

      orgData: {},//当前组织对象
      orgId: '',
      orgLevel: '',

      subAgencyArray: [],//下拉框数据
      iconCoordinators: [],
      currentCoordinate: null,
      overlay: null,


    }
  },
  async mounted () {
    //加载组织数据
    await this.loadOrgData()

    //初始化地图
    this.initMap()

    //添加标注图层
    this.addPolygonLayer()

    //添加icontuceng
    this.addIconLayer()

    //加载当前园区的标注
    this.loadPolygon(this.subAgencyArray)



  },
  methods: {

    //刷新地图
    async refreshMap (isRefreshView) {

      //加载组织数据
      await this.loadOrgData()

      //加载当前园区的标注
      await this.loadPolygon(this.subAgencyArray)

      //重置地图中心点
      if (isRefreshView) {
        this.setMapLocation()
        mapView.setCenter(this.centerPoint);
        mapView.setZoom(this.zoom);
      }


    },


    //加载组织数据
    async loadOrgData () {

      const url = "/gov/org/agency/maporg"
      let params = {
        orgId: this.orgId,
        level: this.orgLevel
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {

        this.orgData = data
        this.orgId = this.orgData.id
        this.orgLevel = this.orgData.level

        if (data.children && data.children.length > 0) {
          this.subAgencyArray = data.children
        } else {
          this.subAgencyArray = []
        }

      } else {
        this.$message.error(msg)
      }

    },

    //加载当前园区的标注
    loadPolygon (subAgencyArray) {
      polygonSource.clear()//清空多边形标注
      iconSource.clear()//清空多边形标注

      let featureData = []//标注数据
      if (subAgencyArray && subAgencyArray.length > 0) {//判断是否存在下级标注
        let oneData = {}

        subAgencyArray.forEach(agencyItem => {

          if (agencyItem.coordinates && agencyItem.coordinates !== '') {//如果有坐标
            let urlNum = this.getRndBetween(1, 3)

            oneData = {
              type: 'Feature',
              id: agencyItem.id,
              properties: {
                id: agencyItem.id,
                level: agencyItem.level,
                name: agencyItem.name,
                index: urlNum//颜色随机的索引
              },
              geometry: {
                type: 'Polygon',
                coordinates: [],
              },
            }
            let coorArray = agencyItem.coordinates.split(',')//坐标数组

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

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

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

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

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

        polygonSource.addFeatures(feature)

        let iconFeatures = [];
        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 oneArray = [x, y]
          this.iconCoordinators.push(oneArray)
          // debugger

          let oneCctv = new Feature({
            geometry: new Point([x, y]),
            id: oneIcon.id_,
            properties: {
              type: "icon",
              id: oneIcon.id_
            }
          });

          let iconStyle = new Style({
            image: new Icon({
              // anchor: [0.5, 0.5],
              // imgSize: [32, 32],
              scale: 0.5,
              src: iconUrlArray[oneIcon.values_.index - 1]
            })
          });

          oneCctv.setStyle(iconStyle);
          iconFeatures.push(oneCctv);

        });

        iconSource.addFeatures(iconFeatures);
      }

      // this.addGif()

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

      if (this.orgData.longitude && this.orgData.latitude) {
        this.centerPoint.push(this.orgData.longitude)
        this.centerPoint.push(this.orgData.latitude)
      }

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

    //根据组织层级设置缩放级别
    setZoom (agencyLevel) {
      if (agencyLevel === 'district') {
        this.zoom = 14
      } else if (agencyLevel === 'street') {
        this.zoom = 15
      } else if (agencyLevel === 'community') {
        this.zoom = 16
      }

    },

    initMap () {
      this.setMapLocation()

      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中
      })

      map.on('singleclick', function (e) {
        // console.log(e.coordinate)
        // console.log(transform(e.coordinate, 'EPSG:3857', 'EPSG:4326'));
      })

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

    },

    //添加变电站标注图层
    addPolygonLayer () {
      polygonSource = new VectorSource({
        //features: (new GeoJSON()).readFeatures(geojsonObject)
      });

      polygonLayer = new VectorLayer({
        source: polygonSource,
        style: polygonStyleFunction,
        zIndex: 50
      });

      //选中多边形后的样式
      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);



    },

    addIconLayer () {
      iconSource = new VectorSource({
        //features: (new GeoJSON()).readFeatures(geojsonObject)
      });

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

      map.addLayer(iconLayer);

    },

    //取随机数
    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
    },

    //是否显示标注
    showIconLayer: {
      type: Boolean,
      default: false
    }

  },
  computed: {

    mapHeight () {

      return this.clientHeight - 120;

    },
    // zoom: {
    //   get () {
    //     //根据不同屏幕分辨率，控制zoom大小
    //     if (this.clientHeight < 900) {
    //       return 2.3
    //     } else {
    //       return 2.8
    //     }
    //   },
    //   set (value) {
    //   }
    // },
    ...mapGetters(["clientHeight"])

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

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

<style lang="scss" >
.div_content {
  .ol-viewport {
    border-radius: 5px;
  }
}
.ol-overlaycontainer-stopevent {
  display: none;
}

.el-scrollbar__wrap {
  overflow-x: hidden !important;
}
</style>   