<template>
    <div id="geoMap">
      <div id="map2" ref="myEchart" style="width: 100%;height: 100%;">

      </div>
      <div style="
        position: absolute;
        top: 50px;
        left: 10px;
        color: #2C99F6;
        padding:4px 5px;
        border:1px solid #2C99F6;
        border-radius:5px;
        letter-spacing':1px">
          <div style="display: flex;align-items: center;margin-bottom: 5px;">
            <div>社区分布</div>
            <div style="background-color: #00FFFF;width: 10px;height: 10px;margin-left: 10px;border-radius: 50%;"></div>
          </div>
          <div style="display: flex;align-items: center;">
            <div>设备分布</div>
            <div style="background-color: #F58158;width: 10px;height: 10px;margin-left: 10px;border-radius: 50%;"></div>
          </div>
      </div>
    </div>
</template>

<script>
  import {getAreaFullJson} from "@/api/grid/index.js"
  export default{
    data(){
      return{
        mapJson:'',
        mapCenter:null,
        JsonStr:null,
        geoCoordMap:[],
        geoCoordMap2:[],
        showEffLable:false,
        uploadedDataURL:null, //地区json
        devicesList:[],
        communityList:[],
        parentCode:'',
        mapIndex:0, //默认加1
        firstLoad:true,
        isFinalMap:false
      }
    },
    props:{
      data:{
        type:Array
      },
      orgInfo:{
        type:Object,
        default:{}
      }
    },
    destroyed() {
      this.mapCenter.clear()
      this.mapCenter.dispose()
    },
    watch:{
      data(){
        //设备列表
        var _this = this
        this.geoCoordMap2.length = 0
        this.devicesList = this.data[0]
        this.data[0].map((item)=>{
          let obj = {}
          let pos = item.latitudeLongitude.split(",")
           obj['value'] = pos
          this.geoCoordMap2.push(obj)
        })
        //社区列表
        this.communityList = this.data[1]
        this.geoCoordMap.length = 0;
        if(this.communityList.agencyList.length>0){
          this.communityList.agencyList.map((item,index)=>{
            let obj={};
            let arr=[];
            obj["name"] = item.name
            obj["address"] = item.address;
            arr.push(item.longitude)
            arr.push(item.latitude)
            obj["value"] = arr;
            this.geoCoordMap.push(obj)
          });
        }
        if(this.firstLoad){
          this.getAreaFullJson().then((res)=>{
            this.firstLoad = false
            _this.loadMap();
          })
        }else{
          _this.loadMap();
        }
      }
    },
    mounted() {
      if(this.orgInfo!==JSON.stringify("{}")){
        this.JsonStr = this.orgInfo.orgPosition
        this.mapIndex = this.orgInfo.orgPosition.split("/").length
      }
      // this.getAreaFullJson()
    },
     methods:{
       async getAreaFullJson(org){
         var _this = this
         let params= {}
         if(this.orgInfo!==JSON.stringify("{}")){
           //org删过"/" this.orgInfo.orgPosition需要删"/",并且只取最后的code
           let op = null
           if(this.orgInfo.orgPosition.lastIndexOf("/") == this.orgInfo.orgPosition.length-1){
             op = this.orgInfo.orgPosition.substr(0,this.orgInfo.orgPosition.length-1)
           }else{
             op = this.orgInfo.orgPosition
           }
           let org_id = org || op.substring(op.lastIndexOf("/")+1,this.orgInfo.orgPosition.length)
           // let org_id = org || this.orgInfo.orgPosition.slice(this.orgInfo.orgPosition.lastIndexOf("/")+1,this.orgInfo.orgPosition.length)
           if(_this.JsonStr.split("/").length>3){
             this.isFinalMap = true
             params['url'] = "https://geo.datav.aliyun.com/areas_v2/bound/"+ org_id +".json"
           }else{
             this.isFinalMap = false
             params['url'] = "https://geo.datav.aliyun.com/areas_v2/bound/"+ org_id +"_full.json"
           }
         }
         let res = await getAreaFullJson(params)
         if(res){
           _this.uploadedDataURL = res.data.data
         }
         return res
       },
        loadMap(){
          var _this =this;
          var geoCoordMap = this.geoCoordMap;
          var geoCoordMap2 = this.geoCoordMap2;
          function convertData(data) {
             var res = [];
             // for (var i = 0; i < data.length; i++) {
                 geoCoordMap.map((item,index)=>{
                   // if(item.name==data[i].name){
                     var geoCoord = item.value;
                     // if (geoCoord) {
                         res.push({
                             name: item.name,
                             value: geoCoord.concat(item.value)
                         });
                     // }
                   // }
                 })
             // }
             return res;
          }
          var areaArr = this.geoCoordMap;
                 let datas = [];
                 geoCoordMap.map((item,index)=>{
                   if(index<geoCoordMap.length-1){
                     let obj = {};
                     let coords = [];
                     coords.push(item.value)
                     coords.push(geoCoordMap[geoCoordMap.length-1].value)
                     obj['coords'] = coords
                     datas.push(obj)
                   }
                 });
           if(_this.mapCenter){
             _this.mapCenter.clear()
           }
           _this.mapCenter = this.$echarts.init(document.getElementById('map2'))
          	var name = '银川市';
          	var option;
           var series = [];
             series.push({
          				name: '',
          				type: 'map',
          				// mapType: name,
          				aspectScale: 1,
                  roam: true,
          				zoom: 1.25,
          				label: {
          					normal: {
          						show: true,
          						textStyle: {
          							color: "#fff",
          							fontSize: "12"
          						}
          					},
          					emphasis: {
          						show: false,
          						textStyle: {
          							fontSize: "12"
          						}
          					}
          				},
                 itemStyle: {
                     normal: {
                         areaColor: '#00177B',
                         borderColor: '#0073DA',
                         borderWidth: 1
                     },
                     emphasis: {
                         label: {
                             show: false
                         },
                         areaColor: '#0073DA'
                     }
                 },
                   animation: true,
                   data: areaArr,
                 },{
                   type: 'effectScatter',
                   coordinateSystem: 'geo',
                   name:'社区',
                   data: convertData(areaArr),
                   symbolSize: 15,
                   animation:true,
                   rippleEffect: { //涟漪特效
                       period: 4, //动画时间，值越小速度越快
                       brushType: 'stroke', //波纹绘制方式 stroke, fill
                       scale: 2 //波纹圆环最大限制，值越大波纹越大
                   },
                   // symbol: 'image://http://192.168.0.102:1888/img/grid/location2.png',
                   symbolRotate: 35,
                   label: {
                       normal: {
                           formatter: '{b}',
                           position: 'top',
                           show: _this.showEffLable
                       },
                       emphasis: {
                           show: true
                       }
                   },
                   itemStyle: {
                       normal: {
                             color: '#00FFFF'
                       }
                   }

                 },
                 {
                   type: 'effectScatter',
                   coordinateSystem: 'geo',
                   name:'设备',
                   data: geoCoordMap2,
                   symbolSize: 5,
                   animation:true,
                   rippleEffect: { //涟漪特效
                       period: 4, //动画时间，值越小速度越快
                       brushType: 'stroke', //波纹绘制方式 stroke, fill
                       scale: 2 //波纹圆环最大限制，值越大波纹越大
                   },
                   // symbol: 'image://https://pic.ulecdn.com/item/user_0102/desc20190115/1fb19e0cf39aafef_-1x-1.png',
                   symbolRotate: 35,
                   label: {
                       normal: {
                           formatter: '{b}',
                           position: 'top',
                           show: true
                       },
                       emphasis: {
                           show: true
                       }
                   },
                   itemStyle: {
                       normal: {
                         color: '#F58158'
                       }
                   },
                  silent:true,//不响应点击
                 },
                 );
          	// $.get(uploadedDataURL, function(geoJson) {
          		var initMap = function(){
                $('<div class="back"></div>').appendTo(
                       $('#geoMap')
                 );
                 if(_this.mapIndex>_this.orgInfo.orgPosition.split("/").length){
                   $('.back').css({
                       'position': 'absolute',
                       'left': '10px',
                       'top': '10px',
                       'display':'block',
                       'color': '#2C99F6',
                       'cursor': 'pointer',
                       'z-index': '100',
                       'padding':'4px 5px',
                       'border':'1px solid #2C99F6',
                       'border-radius':'5px',
                       'letter-spacing':'1px'
                   })
                   $('.back').text("返回上一级")
                   _this.showEffLable = true
                 }else{
                   $('.back').css({
                       'display':'none'
                   });
                    _this.showEffLable = false
                 }
                 $('.back').click(function() {
                   _this.mapIndex--
                   _this.JsonStr = _this.JsonStr.slice(0,_this.JsonStr.lastIndexOf("/"))
                   _this.parentCode = _this.JsonStr.slice(_this.JsonStr.lastIndexOf("/")+1,_this.JsonStr.length)
                   _this.getAreaFullJson(_this.parentCode).then((res)=>{
                     _this.$emit("onRequest",_this.JsonStr)
                   })
                 })
                _this.$echarts.registerMap(name, _this.uploadedDataURL);
                _this.mapCenter.setOption(option = {
                	tooltip: { //提示框组件。
                		trigger: '', //数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
                		textStyle: {
                			fontSize: '12',
                		},
                		backgroundColor: 'rgba(50,50,50,0)',
                		padding: 0,
                		enterable: true,
                		position: 'inside',
                		formatter: function(params) {
                			//地图上面展示出来的数据
                			var tipHtml = '';
                			tipHtml =
                				`<div class="mapStyle">
                       <span class="top-left border-span"></span>
                       <span class="top-right border-span"></span>
                       <span class="bottom-left border-span"></span>
                       <span class="bottom-right border-span"></span>
                       <div>${params.name}</div>
                       <div class="firsts"></div>
                				</div>`;
                			return tipHtml;
                		}
                	},
                		geo: [{
                      show: true,
                      map: name, // 地区名字  如 本项目中的 “南京”
                      aspectScale: 1, // 地图倾斜度
                      zoom: 1.25, // 地图放大倍数
                      label: {
                        normal: {
                          color: '#fff',
                          show: true
                        },
                        emphasis: {
                          color: '#fff',
                          show: true,
                        }
                      },
                      roam: true, //地图设置不可拖拽，固定的
                      itemStyle: {
                        normal: {
                          areaColor: '#00177B',
                          borderColor: '#00FEFF',
                          borderWidth:2,
                          shadowBlur:10,
                          shadowColor:'#00177B',
                          shadowOffsetX:5,
                          shadowOffsetY:12,
                        },
                        emphasis: {
                          // show: false
                          borderWidth:3,
                          areaColor: '#00177B',
                         borderColor: '#00FFFF',
                        }
                      }
                    },
                   ],
                	series: series
                },true);

              }
              initMap();
              _this.mapCenter.off("click");
              _this.mapCenter.on('click', function(e) {
                if (e.seriesType === 'effectScatter'&&e.seriesName == '社区') {
                  localStorage.setItem("agencies1",JSON.stringify(_this.communityList.agencyList[e.dataIndex]))
                  // localStorage.setItem("agencies1",JSON.stringify([e.dataIndex]))
                  _this.$router.push({path:'index2'})
                  return
                }
                if(e.seriesType === 'effectScatter'){
                  return
                }
                if(_this.isFinalMap)return
                JSON.parse(_this.uploadedDataURL).features.map((item,index)=>{
                  if(item.properties.name==e.region.name){
                    _this.mapIndex++
                    _this.JsonStr = _this.JsonStr+"/"+item.properties.adcode
                    _this.getAreaFullJson(item.properties.adcode).then((res)=>{
                      _this.$emit("onRequest",_this.JsonStr)
                    })
                  }
                })
              });
          window.addEventListener('resize', function() {
          	_this.mapCenter.resize();// 自适应
          })
        }
     }
  }
</script>

<style lang="less" scoped="scoped">
  #geoMap{
    width: 100%;
    height: 100%;
    position: relative;
    .mapStyle{
      padding: 10px;
      border-radius: 5px;
      position: relative;
      border: 1px solid rgba(255,255,255,.15);
      box-shadow: inset 0 0 50px rgba(255,255,255,.1), 0 0 5px rgba(0,0,0,.3);
      .border-span{
            display: block;
            position: absolute;
            width: 15px;
            height: 15px;
            opacity: .5;
      }
      .top-left{
        top: -2px;
            left: -2px;
            border-top: 2px solid #54dcf2;
            border-left: 2px solid #54dcf2;
      }
      .top-right{
        top: -2px;
            right: -2px;
            border-top: 2px solid #54dcf2;
            border-right: 2px solid #54dcf2;
      }
      .bottom-left{
        bottom: -2px;
            left: -2px;
            border-bottom: 2px solid #54dcf2;
            border-left: 2px solid #54dcf2;
      }
      .bottom-right{
        bottom: -2px;
            right: -2px;
            border-bottom: 2px solid #54dcf2;
            border-right: 2px solid #54dcf2;
      }
    }

  }
</style>
