<template>
    <div id="map">
      <!-- 社区 -->
        <div v-if="mapIndex==2" id="container"></div>
      <!-- 小区 -->
      <div v-if="mapIndex==3" style="width: 100%;height: 100%;position: relative;overflow: hidden;">
        <div v-if="!userInfo" id="container"></div>
        <img id="imgdom" v-if="userInfo" src="../assets/yuanqu.jpg" class="imgContent" :style="{width: imgSize+'%'}" @mouseenter="imgOutClick" @mouseleave="imgMoveClick"></img>
      </div>
      <div class="mengbang"></div>
    </div>
  </div>
</template>
<script>
  import {getUserInfo} from "../../../util/util.js"
  export default{
    data(){
      return{
        imgSize:100,
        userInfo:false,
        renderWorldCopies: false,
        icon1: {
           // 图标类型，现阶段只支持 image 类型
           type: 'image',
           // 图片 url
           image: require('../../../../public/img/grid/xiaoqu.png'),
           // 图片尺寸
           size: [30, 30],
           // 图片相对 position 的锚点，默认为 bottom-center
           anchor: 'bottom-center'
        },
        textStyle : {
            fontSize: 12,
            fontWeight: 'normal',
            fillColor: 'rgba(3,221,255,0.8)',
            // strokeColor: '#fff',
            // strokeWidth: 2,
            fold: true,
            padding: '0, 0',
        },
        LabelsData:[],
        map:null,
        userInfo:''
      }
    },
    created() {

    },
    props:{
      zoom:{
        type:String,
        default:"16"
      },
      agencies:{
        type:Object
      },
      residentials:{
        type:Array
      },
      mapIndex:{
        type:Number,
        default:3
      },
      mapStyle:{
        type:String,
        default:"amap://styles/blue"
      }
    },
    watch:{
      residentials(){
       this.userInfo = getUserInfo();
       if(this.mapIndex==3&&this.userInfo){
         return false;
       }
        var _this = this;
        _this.residentials.forEach((item,index)=>{
          // let LabelsDataObj = {
          //   name: '',
          //   position: [106.18821,38.471901],
          //   zooms: [10, 20],
          //   opacity: 1,
          //   zIndex: 9999,
          //   fold: true,
          //   icon:_this.icon1,
          //   text: {
          //       // 要展示的文字内容
          //       content: '',
          //       // 文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
          //       direction: 'center',
          //       // 在 direction 基础上的偏移量
          //       offset: [0, -30],
          //       // 文字样式
          //       style: _this.textStyle
          //   }
          // };
          // LabelsDataObj['name'] = item.name;
          // LabelsDataObj['text'].content = item.name;
          // LabelsDataObj.position[0] = item.longitude
          // LabelsDataObj.position[1] = item.latitude
          // _this.LabelsData.push(LabelsDataObj)
          if(!item.longitude||!item.latitude){
            return false;
          }
          let marker = new AMap.Marker({
              position: [item.longitude,item.latitude],
              icon: require('../../../../public/img/grid/xiaoqu.png'),
              offset: new AMap.Pixel(-13, -30)
          });
          // 设置鼠标划过点标记显示的文字提示
          // 设置label标签
          // label默认蓝框白底左上角显示，样式className为：amap-marker-label
          marker.setLabel({
              offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
              content: item.name, //设置文本标注内容
              direction: 'top' //设置文本标注方位
          });
          marker.setMap(this.map);
          marker.on('click',(res)=>{
            localStorage.setItem("agencies2",JSON.stringify(item))
            _this.$router.push({path:'index3'})
           })
           _this.initPolygon(item.boundaryPath)
        })
         var newCenter = this.map.setFitView();
         newCenter.getCenter();
        // _this.initMap();
      }
    },
    mounted() {
      this.userInfo = getUserInfo();
      var _this = this;
      if(this.mapIndex==3&&this.userInfo){
        this.$nextTick(()=>{
          _this.imgEvent()
        })
      }
      this.map = new AMap.Map('container', {
         resizeEnable: true, //是否监控地图容器尺寸变化
         // center: [106.24749,38.508705],
         center: [this.agencies.longitude,this.agencies.latitude],
         zoom:_this.zoom,
         viewMode:'3D',
         showBuildingBlock:true,
         pitch:50,
         pitchEnable:true,
         mapStyle: _this.mapStyle,
         showIndoorMap:true,
       });
       console.log(this.agencies)
       let path = this.agencies.boundaryPath
       this.initPolygon(this.agencies.boundaryPath)
    },
    methods:{
      initPolygon(path){
        if(path==""||path==null||path==undefined){
          return
        }
        var _this = this;
        this.polyEditor = new AMap.PolygonEditor(this.map);
        this.setPolygon(JSON.parse(path))
        this.polyEditor.on('add', function (data) {
          var polygon = data.target;
          _this.polyEditor.addAdsorbPolygons(polygon);
          // polygon.on('click', (res) => {
          //   console.log(res)
          //   _this.polyEditor.setTarget(polygon);
          //   _this.polyEditor.open();
          // })
        })
      },
      setPolygon(data){
        if(data.length<1)return
        var _this = this
            let polygon = new AMap.Polygon({
              path: data,
              fillColor: '',
              strokeOpacity: 1,
              fillOpacity: 0.5,
              strokeColor: '#4cd5de',
              strokeWeight: 4,
              strokeStyle: 'solid',
              strokeDasharray: [5, 5],
            });
            polygon.on('mouseover', () => {
              polygon.setOptions({
                fillOpacity: 0.3,
                fillColor: '#4cd5de'
              })
            })
            polygon.on('mouseout', () => {
              polygon.setOptions({
                fillOpacity: 0.1,
                fillColor: '#4cd5de'
              })
            })
            polygon.on('click', () => {
              // this.polyEditor.open();
            })
            this.map.add(polygon);
            this.map.setFitView();
            _this.polyEditor.setTarget(polygon)
      },
      imgEvent(){
         var oipc = document.getElementById('imgdom');
            // var timeStart,timeEnd,time;//申明全局变量
            var isDrag = false;//是否开始拖拽 false 不拖拽
            var disX, disY;//图片相对于图片的位置
            //鼠标按下时
            oipc.onmousedown = function (e) {
                isDrag = true;
                this.style.cursor = 'move';
                e = e || window.event;//兼容性写法
                //鼠标位置
                var x = e.clientX;
                var y = e.clientY;
                //鼠标相对于图片的位置
                disX = x - this.offsetLeft;
                disY = y - this.offsetTop;

            }
            //鼠标移动时
            document.onmousemove = function (e) {
                if (!isDrag) {
                    return;
                }
                e = e || window.event;//兼容性写法
                //鼠标位置
                var x = e.clientX;
                var y = e.clientY;
                //修改图片位置
                oipc.style.left = x - disX + 'px';
                oipc.style.top = y - disY + 'px';
            }


            //鼠标抬起时
            document.onmouseup = function () {
                isDrag = false;
                oipc.style.cursor = 'default';
            }
            // function getTimeNow()//获取此刻时间
            //  {
            //      var now=new Date();
            //      return now.getTime();
            //  }
            //  function holdDown()//鼠标按下时触发
            //  {
            //      timeStart=getTimeNow();//获取鼠标按下时的时间
            //      time=setInterval(function()//setInterval会每100毫秒执行一次
            //      {
            //          timeEnd=getTimeNow();//也就是每100毫秒获取一次时间
            //          if(timeEnd-timeStart>1000)//如果此时检测到的时间与第一次获取的时间差有1000毫秒
            //          {
            //              clearInterval(time);//便不再继续重复此函数 （clearInterval取消周期性执行）
            //  　　　     alert("长按");//并弹出代码
            //          }
            //      },100);
            //  }
            //  function holdUp()
            //  {
            //      clearInterval(time);//如果按下时间不到1000毫秒便弹起，
            // }
      },
      imgOutClick(){
        this.windowAddMouseWheel()
      },
      imgMoveClick(){
          document.removeEventListener('DOMMouseScroll', this.scrollFunc);
          window.onmousewheel = document.onmousewheel = null
      },
      scrollFunc(e) {
        e = e || window.event;
        if (e.wheelDelta) {  //判断浏览器IE，谷歌滑轮事件
          if (e.wheelDelta > 0) { //当滑轮向上滚动时
            this.imgSize += 10
          }
          if (e.wheelDelta < 0) { //当滑轮向下滚动时
            if(this.imgSize>100){
              this.imgSize -= 10
            }
          }
        } else if (e.detail) {  //Firefox滑轮事件
          if (e.detail> 0) { //当滑轮向上滚动时
            this.imgSize += 10
          }
          if (e.detail< 0) { //当滑轮向下滚动时
            if(this.imgSize>100){
              this.imgSize -= 10
            }
          }
        }
      },
      windowAddMouseWheel() {
          //给页面绑定滑轮滚动事件
          if (document.addEventListener) { //火狐使用DOMMouseScroll绑定
            document.addEventListener('DOMMouseScroll', this.scrollFunc, false);
          }
          //其他浏览器直接绑定滚动事件
          window.onmousewheel = document.onmousewheel = this.scrollFunc;
      },
      initMap(){
        var _this = this;
        //初始化地图
          let map = new AMap.Map('container', {
             resizeEnable: true, //是否监控地图容器尺寸变化
             // center: [106.24749,38.508705],
             center: [this.agencies.longitude,this.agencies.latitude],
             zoom:16,
             viewMode:'3D',
             showBuildingBlock:true,
             pitch:50,
             pitchEnable:true,
             mapStyle: "amap://styles/blue",
             showIndoorMap:true,
           });


            // var markers = [];
            //     var layer = new AMap.LabelsLayer({
            //         zooms: [3, 20],
            //         zIndex: 1000,
            //         collision: false,
            //         // 设置 allowCollision：true，可以让标注避让用户的标注
            //         // allowCollision :false,
            //     });
            //     // 图层添加到地图
            //     map.add(layer);
            //     // 初始化 labelMarker
            //     for (var i = 0; i < this.LabelsData.length; i++) {
            //         var curData = this.LabelsData[i];
            //         curData.extData = {
            //             index: i
            //         };
            //         var labelMarker = new AMap.LabelMarker(curData);
            //         labelMarker.on('click',function(ev){
            //           _this.residentials.map((item)=>{
            //             if(ev.data.data.txt==item.name){
            //               localStorage.setItem("agencies2",JSON.stringify(item))
            //               _this.$router.push({path:'index3'})
            //             }
            //           })
            //         });
            //         // // 普通点
            //         //         var normalMarker = new AMap.Marker({
            //         //             offset: new AMap.Pixel(-75, -40),
            //         //         });
            //         // // 事件
            //         // labelMarker.on('mouseover', function(e){
            //         //     var position = e.data.data && e.data.data.position;
            //         //     if(position){
            //         //         normalMarker.setContent(
            //         //             '<div class="amap-info-window">'
            //         //                 + position +
            //         //                 '<div class="amap-info-sharp"></div>' +
            //         //             '</div>');
            //         //         normalMarker.setPosition(position);
            //         //         map.add(normalMarker);
            //         //     }
            //         // });
            //         markers.push(labelMarker);
            //     }

            //     // 将 marker 添加到图层
            //     layer.add(markers);
            //     map.setFitView();

      }
    }
  }
</script>

<style lang="less">
  #map{
    .mengbang{
      -webkit-pointer-events: none;
      -moz-pointer-events: none;
      -ms-pointer-events: none;
      -o-pointer-events: none;
      pointer-events: none;
      position: absolute;
      left: 0;
      top:0;
      right:0;
      bottom:0;
      background-image: linear-gradient(
              top,
              rgba(255, 255, 255, 0) 80%,
              rgba(0, 11, 44, 1) 100%
          ),linear-gradient(
              bottom,
              rgba(255, 255, 255, 0) 80%,
              rgba(0, 11, 44, 1) 100%
          ),linear-gradient(
              left,
              rgba(255, 255, 255, 0) 80%,
              rgba(0, 11, 44, 1) 100%
          ),linear-gradient(
              right,
              rgba(255, 255, 255, 0) 80%,
              rgba(0, 11, 44, 1) 100%
          );
    }
    position: relative;
    width: 100%;
    height: 100%;
    /*去除下标*/
    .amap-logo{
    display: none!important;
    }
    .amap-copyright{
    opacity:0;
    }
       #container {
          width: 100%;
          height: 100%;
          background-color: transparent;
        }
        .amap-icon img {
                    width: 30px;
                    height: 30px;
                }

                .amap-marker-label{
                    border: 0;
                    background-color: transparent;
                }

                .info{
                    position: relative;
                    top: 0;
                  left:0;
                    right: 0;
                  bottom:0;
                  margin:0 auto;
                    min-width: 0;
                    background-color: transparent!important;
                    box-shadow: none!important;
                }
                .amap-marker-label{
                  color: #00CCFF!important;
                }
                .imgContent{
                  position: absolute;
                  top: 0;
                  bottom: 0;
                  left: 0;
                  right: 0;
                }
  }
</style>
